Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / ffmpeg / libavformat / movenc.c
1 /*
2  * MOV, 3GP, MP4 muxer
3  * Copyright (c) 2003 Thomas Raivio
4  * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
5  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 #include <stdint.h>
25 #include <inttypes.h>
26
27 #include "movenc.h"
28 #include "avformat.h"
29 #include "avio_internal.h"
30 #include "riff.h"
31 #include "avio.h"
32 #include "isom.h"
33 #include "avc.h"
34 #include "libavcodec/get_bits.h"
35 #include "libavcodec/put_bits.h"
36 #include "libavcodec/vc1_common.h"
37 #include "libavcodec/raw.h"
38 #include "internal.h"
39 #include "libavutil/avstring.h"
40 #include "libavutil/intfloat.h"
41 #include "libavutil/mathematics.h"
42 #include "libavutil/opt.h"
43 #include "libavutil/dict.h"
44 #include "libavutil/pixdesc.h"
45 #include "libavutil/timecode.h"
46 #include "hevc.h"
47 #include "rtpenc.h"
48 #include "mov_chan.h"
49
50 #undef NDEBUG
51 #include <assert.h>
52
53 static const AVOption options[] = {
54     { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
55     { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
56     { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
57     { "empty_moov", "Make the initial moov atom empty (not supported by QuickTime)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
58     { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
59     { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
60     { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
61     { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
62     { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
63     { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
64     { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
65     FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
66     { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
67     { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
68     { "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
69     { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
70     { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
71     { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
72     { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
73     { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
74     { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
75     { "brand",    "Override major brand", offsetof(MOVMuxContext, major_brand),   AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
76     { NULL },
77 };
78
79 #define MOV_CLASS(flavor)\
80 static const AVClass flavor ## _muxer_class = {\
81     .class_name = #flavor " muxer",\
82     .item_name  = av_default_item_name,\
83     .option     = options,\
84     .version    = LIBAVUTIL_VERSION_INT,\
85 };
86
87 static int get_moov_size(AVFormatContext *s);
88
89 static int utf8len(const uint8_t *b)
90 {
91     int len = 0;
92     int val;
93     while (*b) {
94         GET_UTF8(val, *b++, return -1;)
95         len++;
96     }
97     return len;
98 }
99
100 //FIXME support 64 bit variant with wide placeholders
101 static int64_t update_size(AVIOContext *pb, int64_t pos)
102 {
103     int64_t curpos = avio_tell(pb);
104     avio_seek(pb, pos, SEEK_SET);
105     avio_wb32(pb, curpos - pos); /* rewrite size */
106     avio_seek(pb, curpos, SEEK_SET);
107
108     return curpos - pos;
109 }
110
111 static int supports_edts(MOVMuxContext *mov)
112 {
113     // EDTS with fragments is tricky as we don't know the duration when its written
114     return (mov->use_editlist<0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) || mov->use_editlist>0;
115 }
116
117 static int co64_required(const MOVTrack *track)
118 {
119     if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
120         return 1;
121     return 0;
122 }
123
124 /* Chunk offset atom */
125 static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
126 {
127     int i;
128     int mode64 = co64_required(track); // use 32 bit size variant if possible
129     int64_t pos = avio_tell(pb);
130     avio_wb32(pb, 0); /* size */
131     if (mode64)
132         ffio_wfourcc(pb, "co64");
133     else
134         ffio_wfourcc(pb, "stco");
135     avio_wb32(pb, 0); /* version & flags */
136     avio_wb32(pb, track->chunkCount); /* entry count */
137     for (i = 0; i < track->entry; i++) {
138         if (!track->cluster[i].chunkNum)
139             continue;
140         if (mode64 == 1)
141             avio_wb64(pb, track->cluster[i].pos + track->data_offset);
142         else
143             avio_wb32(pb, track->cluster[i].pos + track->data_offset);
144     }
145     return update_size(pb, pos);
146 }
147
148 /* Sample size atom */
149 static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
150 {
151     int equalChunks = 1;
152     int i, j, entries = 0, tst = -1, oldtst = -1;
153
154     int64_t pos = avio_tell(pb);
155     avio_wb32(pb, 0); /* size */
156     ffio_wfourcc(pb, "stsz");
157     avio_wb32(pb, 0); /* version & flags */
158
159     for (i = 0; i < track->entry; i++) {
160         tst = track->cluster[i].size / track->cluster[i].entries;
161         if (oldtst != -1 && tst != oldtst)
162             equalChunks = 0;
163         oldtst = tst;
164         entries += track->cluster[i].entries;
165     }
166     if (equalChunks && track->entry) {
167         int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
168         sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
169         avio_wb32(pb, sSize); // sample size
170         avio_wb32(pb, entries); // sample count
171     } else {
172         avio_wb32(pb, 0); // sample size
173         avio_wb32(pb, entries); // sample count
174         for (i = 0; i < track->entry; i++) {
175             for (j = 0; j < track->cluster[i].entries; j++) {
176                 avio_wb32(pb, track->cluster[i].size /
177                           track->cluster[i].entries);
178             }
179         }
180     }
181     return update_size(pb, pos);
182 }
183
184 /* Sample to chunk atom */
185 static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
186 {
187     int index = 0, oldval = -1, i;
188     int64_t entryPos, curpos;
189
190     int64_t pos = avio_tell(pb);
191     avio_wb32(pb, 0); /* size */
192     ffio_wfourcc(pb, "stsc");
193     avio_wb32(pb, 0); // version & flags
194     entryPos = avio_tell(pb);
195     avio_wb32(pb, track->chunkCount); // entry count
196     for (i = 0; i < track->entry; i++) {
197         if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
198             avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
199             avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
200             avio_wb32(pb, 0x1); // sample description index
201             oldval = track->cluster[i].samples_in_chunk;
202             index++;
203         }
204     }
205     curpos = avio_tell(pb);
206     avio_seek(pb, entryPos, SEEK_SET);
207     avio_wb32(pb, index); // rewrite size
208     avio_seek(pb, curpos, SEEK_SET);
209
210     return update_size(pb, pos);
211 }
212
213 /* Sync sample atom */
214 static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
215 {
216     int64_t curpos, entryPos;
217     int i, index = 0;
218     int64_t pos = avio_tell(pb);
219     avio_wb32(pb, 0); // size
220     ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
221     avio_wb32(pb, 0); // version & flags
222     entryPos = avio_tell(pb);
223     avio_wb32(pb, track->entry); // entry count
224     for (i = 0; i < track->entry; i++) {
225         if (track->cluster[i].flags & flag) {
226             avio_wb32(pb, i + 1);
227             index++;
228         }
229     }
230     curpos = avio_tell(pb);
231     avio_seek(pb, entryPos, SEEK_SET);
232     avio_wb32(pb, index); // rewrite size
233     avio_seek(pb, curpos, SEEK_SET);
234     return update_size(pb, pos);
235 }
236
237 static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
238 {
239     avio_wb32(pb, 0x11); /* size */
240     if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
241     else                         ffio_wfourcc(pb, "damr");
242     ffio_wfourcc(pb, "FFMP");
243     avio_w8(pb, 0); /* decoder version */
244
245     avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
246     avio_w8(pb, 0x00); /* Mode change period (no restriction) */
247     avio_w8(pb, 0x01); /* Frames per sample */
248     return 0x11;
249 }
250
251 static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
252 {
253     GetBitContext gbc;
254     PutBitContext pbc;
255     uint8_t buf[3];
256     int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
257
258     if (track->vos_len < 7)
259         return -1;
260
261     avio_wb32(pb, 11);
262     ffio_wfourcc(pb, "dac3");
263
264     init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
265     fscod      = get_bits(&gbc, 2);
266     frmsizecod = get_bits(&gbc, 6);
267     bsid       = get_bits(&gbc, 5);
268     bsmod      = get_bits(&gbc, 3);
269     acmod      = get_bits(&gbc, 3);
270     if (acmod == 2) {
271         skip_bits(&gbc, 2); // dsurmod
272     } else {
273         if ((acmod & 1) && acmod != 1)
274             skip_bits(&gbc, 2); // cmixlev
275         if (acmod & 4)
276             skip_bits(&gbc, 2); // surmixlev
277     }
278     lfeon = get_bits1(&gbc);
279
280     init_put_bits(&pbc, buf, sizeof(buf));
281     put_bits(&pbc, 2, fscod);
282     put_bits(&pbc, 5, bsid);
283     put_bits(&pbc, 3, bsmod);
284     put_bits(&pbc, 3, acmod);
285     put_bits(&pbc, 1, lfeon);
286     put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
287     put_bits(&pbc, 5, 0); // reserved
288
289     flush_put_bits(&pbc);
290     avio_write(pb, buf, sizeof(buf));
291
292     return 11;
293 }
294
295 /**
296  * This function writes extradata "as is".
297  * Extradata must be formatted like a valid atom (with size and tag).
298  */
299 static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
300 {
301     avio_write(pb, track->enc->extradata, track->enc->extradata_size);
302     return track->enc->extradata_size;
303 }
304
305 static int mov_write_enda_tag(AVIOContext *pb)
306 {
307     avio_wb32(pb, 10);
308     ffio_wfourcc(pb, "enda");
309     avio_wb16(pb, 1); /* little endian */
310     return 10;
311 }
312
313 static int mov_write_enda_tag_be(AVIOContext *pb)
314 {
315   avio_wb32(pb, 10);
316   ffio_wfourcc(pb, "enda");
317   avio_wb16(pb, 0); /* big endian */
318   return 10;
319 }
320
321 static void put_descr(AVIOContext *pb, int tag, unsigned int size)
322 {
323     int i = 3;
324     avio_w8(pb, tag);
325     for (; i > 0; i--)
326         avio_w8(pb, (size >> (7 * i)) | 0x80);
327     avio_w8(pb, size & 0x7F);
328 }
329
330 static unsigned compute_avg_bitrate(MOVTrack *track)
331 {
332     uint64_t size = 0;
333     int i;
334     if (!track->track_duration)
335         return 0;
336     for (i = 0; i < track->entry; i++)
337         size += track->cluster[i].size;
338     return size * 8 * track->timescale / track->track_duration;
339 }
340
341 static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
342 {
343     int64_t pos = avio_tell(pb);
344     int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
345     unsigned avg_bitrate;
346
347     avio_wb32(pb, 0); // size
348     ffio_wfourcc(pb, "esds");
349     avio_wb32(pb, 0); // Version
350
351     // ES descriptor
352     put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
353     avio_wb16(pb, track->track_id);
354     avio_w8(pb, 0x00); // flags (= no flags)
355
356     // DecoderConfig descriptor
357     put_descr(pb, 0x04, 13 + decoder_specific_info_len);
358
359     // Object type indication
360     if ((track->enc->codec_id == AV_CODEC_ID_MP2 ||
361          track->enc->codec_id == AV_CODEC_ID_MP3) &&
362         track->enc->sample_rate > 24000)
363         avio_w8(pb, 0x6B); // 11172-3
364     else
365         avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
366
367     // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
368     // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
369     if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
370         avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
371     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
372         avio_w8(pb, 0x15); // flags (= Audiostream)
373     else
374         avio_w8(pb, 0x11); // flags (= Visualstream)
375
376     avio_wb24(pb, track->enc->rc_buffer_size >> 3); // Buffersize DB
377
378     avg_bitrate = compute_avg_bitrate(track);
379     // maxbitrate (FIXME should be max rate in any 1 sec window)
380     avio_wb32(pb, FFMAX3(track->enc->bit_rate, track->enc->rc_max_rate, avg_bitrate));
381     avio_wb32(pb, avg_bitrate);
382
383     if (track->vos_len) {
384         // DecoderSpecific info descriptor
385         put_descr(pb, 0x05, track->vos_len);
386         avio_write(pb, track->vos_data, track->vos_len);
387     }
388
389     // SL descriptor
390     put_descr(pb, 0x06, 1);
391     avio_w8(pb, 0x02);
392     return update_size(pb, pos);
393 }
394
395 static int mov_pcm_le_gt16(enum AVCodecID codec_id)
396 {
397     return codec_id == AV_CODEC_ID_PCM_S24LE ||
398            codec_id == AV_CODEC_ID_PCM_S32LE ||
399            codec_id == AV_CODEC_ID_PCM_F32LE ||
400            codec_id == AV_CODEC_ID_PCM_F64LE;
401 }
402
403 static int mov_pcm_be_gt16(enum AVCodecID codec_id)
404 {
405     return codec_id == AV_CODEC_ID_PCM_S24BE ||
406            codec_id == AV_CODEC_ID_PCM_S32BE ||
407            codec_id == AV_CODEC_ID_PCM_F32BE ||
408            codec_id == AV_CODEC_ID_PCM_F64BE;
409 }
410
411 static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
412 {
413     int ret;
414     int64_t pos = avio_tell(pb);
415     avio_wb32(pb, 0);
416     avio_wl32(pb, track->tag); // store it byteswapped
417     track->enc->codec_tag = av_bswap16(track->tag >> 16);
418     if ((ret = ff_put_wav_header(pb, track->enc, 0)) < 0)
419         return ret;
420     return update_size(pb, pos);
421 }
422
423 static int mov_write_wfex_tag(AVIOContext *pb, MOVTrack *track)
424 {
425     int ret;
426     int64_t pos = avio_tell(pb);
427     avio_wb32(pb, 0);
428     ffio_wfourcc(pb, "wfex");
429     if ((ret = ff_put_wav_header(pb, track->enc, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
430         return ret;
431     return update_size(pb, pos);
432 }
433
434 static int mov_write_chan_tag(AVIOContext *pb, MOVTrack *track)
435 {
436     uint32_t layout_tag, bitmap;
437     int64_t pos = avio_tell(pb);
438
439     layout_tag = ff_mov_get_channel_layout_tag(track->enc->codec_id,
440                                                track->enc->channel_layout,
441                                                &bitmap);
442     if (!layout_tag) {
443         av_log(track->enc, AV_LOG_WARNING, "not writing 'chan' tag due to "
444                "lack of channel information\n");
445         return 0;
446     }
447
448     if (track->multichannel_as_mono)
449         return 0;
450
451     avio_wb32(pb, 0);           // Size
452     ffio_wfourcc(pb, "chan");   // Type
453     avio_w8(pb, 0);             // Version
454     avio_wb24(pb, 0);           // Flags
455     avio_wb32(pb, layout_tag);  // mChannelLayoutTag
456     avio_wb32(pb, bitmap);      // mChannelBitmap
457     avio_wb32(pb, 0);           // mNumberChannelDescriptions
458
459     return update_size(pb, pos);
460 }
461
462 static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)
463 {
464     int64_t pos = avio_tell(pb);
465
466     avio_wb32(pb, 0);     /* size */
467     ffio_wfourcc(pb, "wave");
468
469     if (track->enc->codec_id != AV_CODEC_ID_QDM2) {
470     avio_wb32(pb, 12);    /* size */
471     ffio_wfourcc(pb, "frma");
472     avio_wl32(pb, track->tag);
473     }
474
475     if (track->enc->codec_id == AV_CODEC_ID_AAC) {
476         /* useless atom needed by mplayer, ipod, not needed by quicktime */
477         avio_wb32(pb, 12); /* size */
478         ffio_wfourcc(pb, "mp4a");
479         avio_wb32(pb, 0);
480         mov_write_esds_tag(pb, track);
481     } else if (mov_pcm_le_gt16(track->enc->codec_id))  {
482       mov_write_enda_tag(pb);
483     } else if (mov_pcm_be_gt16(track->enc->codec_id))  {
484       mov_write_enda_tag_be(pb);
485     } else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB) {
486         mov_write_amr_tag(pb, track);
487     } else if (track->enc->codec_id == AV_CODEC_ID_AC3) {
488         mov_write_ac3_tag(pb, track);
489     } else if (track->enc->codec_id == AV_CODEC_ID_ALAC ||
490                track->enc->codec_id == AV_CODEC_ID_QDM2) {
491         mov_write_extradata_tag(pb, track);
492     } else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
493                track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
494         mov_write_ms_tag(pb, track);
495     }
496
497     avio_wb32(pb, 8);     /* size */
498     avio_wb32(pb, 0);     /* null tag */
499
500     return update_size(pb, pos);
501 }
502
503 static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
504 {
505     uint8_t *unescaped;
506     const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
507     int unescaped_size, seq_found = 0;
508     int level = 0, interlace = 0;
509     int packet_seq   = track->vc1_info.packet_seq;
510     int packet_entry = track->vc1_info.packet_entry;
511     int slices       = track->vc1_info.slices;
512     PutBitContext pbc;
513
514     if (track->start_dts == AV_NOPTS_VALUE) {
515         /* No packets written yet, vc1_info isn't authoritative yet. */
516         /* Assume inline sequence and entry headers. This will be
517          * overwritten at the end if the file is seekable. */
518         packet_seq = packet_entry = 1;
519     }
520
521     unescaped = av_mallocz(track->vos_len + FF_INPUT_BUFFER_PADDING_SIZE);
522     if (!unescaped)
523         return AVERROR(ENOMEM);
524     start = find_next_marker(track->vos_data, end);
525     for (next = start; next < end; start = next) {
526         GetBitContext gb;
527         int size;
528         next = find_next_marker(start + 4, end);
529         size = next - start - 4;
530         if (size <= 0)
531             continue;
532         unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
533         init_get_bits(&gb, unescaped, 8 * unescaped_size);
534         if (AV_RB32(start) == VC1_CODE_SEQHDR) {
535             int profile = get_bits(&gb, 2);
536             if (profile != PROFILE_ADVANCED) {
537                 av_free(unescaped);
538                 return AVERROR(ENOSYS);
539             }
540             seq_found = 1;
541             level = get_bits(&gb, 3);
542             /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
543              * width, height */
544             skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
545             skip_bits(&gb, 1); /* broadcast */
546             interlace = get_bits1(&gb);
547             skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
548         }
549     }
550     if (!seq_found) {
551         av_free(unescaped);
552         return AVERROR(ENOSYS);
553     }
554
555     init_put_bits(&pbc, buf, 7);
556     /* VC1DecSpecStruc */
557     put_bits(&pbc, 4, 12); /* profile - advanced */
558     put_bits(&pbc, 3, level);
559     put_bits(&pbc, 1, 0); /* reserved */
560     /* VC1AdvDecSpecStruc */
561     put_bits(&pbc, 3, level);
562     put_bits(&pbc, 1, 0); /* cbr */
563     put_bits(&pbc, 6, 0); /* reserved */
564     put_bits(&pbc, 1, !interlace); /* no interlace */
565     put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
566     put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
567     put_bits(&pbc, 1, !slices); /* no slice code */
568     put_bits(&pbc, 1, 0); /* no bframe */
569     put_bits(&pbc, 1, 0); /* reserved */
570
571     /* framerate */
572     if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
573         put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
574     else
575         put_bits32(&pbc, 0xffffffff);
576
577     flush_put_bits(&pbc);
578
579     av_free(unescaped);
580
581     return 0;
582 }
583
584 static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
585 {
586     uint8_t buf[7] = { 0 };
587     int ret;
588
589     if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
590         return ret;
591
592     avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
593     ffio_wfourcc(pb, "dvc1");
594     track->vc1_info.struct_offset = avio_tell(pb);
595     avio_write(pb, buf, sizeof(buf));
596     avio_write(pb, track->vos_data, track->vos_len);
597
598     return 0;
599 }
600
601 static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
602 {
603     avio_wb32(pb, track->vos_len + 8);
604     ffio_wfourcc(pb, "glbl");
605     avio_write(pb, track->vos_data, track->vos_len);
606     return 8 + track->vos_len;
607 }
608
609 /**
610  * Compute flags for 'lpcm' tag.
611  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
612  */
613 static int mov_get_lpcm_flags(enum AVCodecID codec_id)
614 {
615     switch (codec_id) {
616     case AV_CODEC_ID_PCM_F32BE:
617     case AV_CODEC_ID_PCM_F64BE:
618         return 11;
619     case AV_CODEC_ID_PCM_F32LE:
620     case AV_CODEC_ID_PCM_F64LE:
621         return 9;
622     case AV_CODEC_ID_PCM_U8:
623         return 10;
624     case AV_CODEC_ID_PCM_S16BE:
625     case AV_CODEC_ID_PCM_S24BE:
626     case AV_CODEC_ID_PCM_S32BE:
627         return 14;
628     case AV_CODEC_ID_PCM_S8:
629     case AV_CODEC_ID_PCM_S16LE:
630     case AV_CODEC_ID_PCM_S24LE:
631     case AV_CODEC_ID_PCM_S32LE:
632         return 12;
633     default:
634         return 0;
635     }
636 }
637
638 static int get_cluster_duration(MOVTrack *track, int cluster_idx)
639 {
640     int64_t next_dts;
641
642     if (cluster_idx >= track->entry)
643         return 0;
644
645     if (cluster_idx + 1 == track->entry)
646         next_dts = track->track_duration + track->start_dts;
647     else
648         next_dts = track->cluster[cluster_idx + 1].dts;
649
650     next_dts -= track->cluster[cluster_idx].dts;
651
652     av_assert0(next_dts >= 0);
653     av_assert0(next_dts <= INT_MAX);
654
655     return next_dts;
656 }
657
658 static int get_samples_per_packet(MOVTrack *track)
659 {
660     int i, first_duration;
661
662 // return track->enc->frame_size;
663
664     /* use 1 for raw PCM */
665     if (!track->audio_vbr)
666         return 1;
667
668     /* check to see if duration is constant for all clusters */
669     if (!track->entry)
670         return 0;
671     first_duration = get_cluster_duration(track, 0);
672     for (i = 1; i < track->entry; i++) {
673         if (get_cluster_duration(track, i) != first_duration)
674             return 0;
675     }
676     return first_duration;
677 }
678
679 static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
680 {
681     int64_t pos = avio_tell(pb);
682     int version = 0;
683     uint32_t tag = track->tag;
684
685     if (track->mode == MODE_MOV) {
686         if (track->timescale > UINT16_MAX) {
687             if (mov_get_lpcm_flags(track->enc->codec_id))
688                 tag = AV_RL32("lpcm");
689             version = 2;
690         } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||
691                    mov_pcm_be_gt16(track->enc->codec_id) ||
692                    track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
693                    track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
694                    track->enc->codec_id == AV_CODEC_ID_QDM2) {
695             version = 1;
696         }
697     }
698
699     avio_wb32(pb, 0); /* size */
700     avio_wl32(pb, tag); // store it byteswapped
701     avio_wb32(pb, 0); /* Reserved */
702     avio_wb16(pb, 0); /* Reserved */
703     avio_wb16(pb, 1); /* Data-reference index, XXX  == 1 */
704
705     /* SoundDescription */
706     avio_wb16(pb, version); /* Version */
707     avio_wb16(pb, 0); /* Revision level */
708     avio_wb32(pb, 0); /* Reserved */
709
710     if (version == 2) {
711         avio_wb16(pb, 3);
712         avio_wb16(pb, 16);
713         avio_wb16(pb, 0xfffe);
714         avio_wb16(pb, 0);
715         avio_wb32(pb, 0x00010000);
716         avio_wb32(pb, 72);
717         avio_wb64(pb, av_double2int(track->enc->sample_rate));
718         avio_wb32(pb, track->enc->channels);
719         avio_wb32(pb, 0x7F000000);
720         avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));
721         avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));
722         avio_wb32(pb, track->sample_size);
723         avio_wb32(pb, get_samples_per_packet(track));
724     } else {
725         if (track->mode == MODE_MOV) {
726             avio_wb16(pb, track->enc->channels);
727             if (track->enc->codec_id == AV_CODEC_ID_PCM_U8 ||
728                 track->enc->codec_id == AV_CODEC_ID_PCM_S8)
729                 avio_wb16(pb, 8); /* bits per sample */
730             else
731                 avio_wb16(pb, 16);
732             avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
733         } else { /* reserved for mp4/3gp */
734             avio_wb16(pb, 2);
735             avio_wb16(pb, 16);
736             avio_wb16(pb, 0);
737         }
738
739         avio_wb16(pb, 0); /* packet size (= 0) */
740         avio_wb16(pb, track->enc->sample_rate <= UINT16_MAX ?
741                       track->enc->sample_rate : 0);
742         avio_wb16(pb, 0); /* Reserved */
743     }
744
745     if (version == 1) { /* SoundDescription V1 extended info */
746         if (mov_pcm_le_gt16(track->enc->codec_id) ||
747             mov_pcm_be_gt16(track->enc->codec_id))
748             avio_wb32(pb, 1); /*  must be 1 for  uncompressed formats */
749         else
750             avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
751         avio_wb32(pb, track->sample_size / track->enc->channels); /* Bytes per packet */
752         avio_wb32(pb, track->sample_size); /* Bytes per frame */
753         avio_wb32(pb, 2); /* Bytes per sample */
754     }
755
756     if (track->mode == MODE_MOV &&
757         (track->enc->codec_id == AV_CODEC_ID_AAC           ||
758          track->enc->codec_id == AV_CODEC_ID_AC3           ||
759          track->enc->codec_id == AV_CODEC_ID_AMR_NB        ||
760          track->enc->codec_id == AV_CODEC_ID_ALAC          ||
761          track->enc->codec_id == AV_CODEC_ID_ADPCM_MS      ||
762          track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
763          track->enc->codec_id == AV_CODEC_ID_QDM2          ||
764          (mov_pcm_le_gt16(track->enc->codec_id) && version==1) ||
765          (mov_pcm_be_gt16(track->enc->codec_id) && version==1)))
766         mov_write_wave_tag(pb, track);
767     else if (track->tag == MKTAG('m','p','4','a'))
768         mov_write_esds_tag(pb, track);
769     else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB)
770         mov_write_amr_tag(pb, track);
771     else if (track->enc->codec_id == AV_CODEC_ID_AC3)
772         mov_write_ac3_tag(pb, track);
773     else if (track->enc->codec_id == AV_CODEC_ID_ALAC)
774         mov_write_extradata_tag(pb, track);
775     else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO)
776         mov_write_wfex_tag(pb, track);
777     else if (track->vos_len > 0)
778         mov_write_glbl_tag(pb, track);
779
780     if (track->mode == MODE_MOV && track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
781         mov_write_chan_tag(pb, track);
782
783     return update_size(pb, pos);
784 }
785
786 static int mov_write_d263_tag(AVIOContext *pb)
787 {
788     avio_wb32(pb, 0xf); /* size */
789     ffio_wfourcc(pb, "d263");
790     ffio_wfourcc(pb, "FFMP");
791     avio_w8(pb, 0); /* decoder version */
792     /* FIXME use AVCodecContext level/profile, when encoder will set values */
793     avio_w8(pb, 0xa); /* level */
794     avio_w8(pb, 0); /* profile */
795     return 0xf;
796 }
797
798 static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
799 {
800     int64_t pos = avio_tell(pb);
801
802     avio_wb32(pb, 0);
803     ffio_wfourcc(pb, "avcC");
804     ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
805     return update_size(pb, pos);
806 }
807
808 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
809 {
810     int64_t pos = avio_tell(pb);
811
812     avio_wb32(pb, 0);
813     ffio_wfourcc(pb, "hvcC");
814     ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
815     return update_size(pb, pos);
816 }
817
818 /* also used by all avid codecs (dv, imx, meridien) and their variants */
819 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
820 {
821     int i;
822     avio_wb32(pb, 24); /* size */
823     ffio_wfourcc(pb, "ACLR");
824     ffio_wfourcc(pb, "ACLR");
825     ffio_wfourcc(pb, "0001");
826     if (track->enc->color_range == AVCOL_RANGE_MPEG) { /* Legal range (16-235) */
827         avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
828     } else { /* Full range (0-255) */
829         avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
830     }
831     avio_wb32(pb, 0); /* unknown */
832
833     avio_wb32(pb, 24); /* size */
834     ffio_wfourcc(pb, "APRG");
835     ffio_wfourcc(pb, "APRG");
836     ffio_wfourcc(pb, "0001");
837     avio_wb32(pb, 1); /* unknown */
838     avio_wb32(pb, 0); /* unknown */
839
840     avio_wb32(pb, 120); /* size */
841     ffio_wfourcc(pb, "ARES");
842     ffio_wfourcc(pb, "ARES");
843     ffio_wfourcc(pb, "0001");
844     avio_wb32(pb, AV_RB32(track->vos_data + 0x28)); /* dnxhd cid, some id ? */
845     avio_wb32(pb, track->enc->width);
846     /* values below are based on samples created with quicktime and avid codecs */
847     if (track->vos_data[5] & 2) { // interlaced
848         avio_wb32(pb, track->enc->height / 2);
849         avio_wb32(pb, 2); /* unknown */
850         avio_wb32(pb, 0); /* unknown */
851         avio_wb32(pb, 4); /* unknown */
852     } else {
853         avio_wb32(pb, track->enc->height);
854         avio_wb32(pb, 1); /* unknown */
855         avio_wb32(pb, 0); /* unknown */
856         if (track->enc->height == 1080)
857             avio_wb32(pb, 5); /* unknown */
858         else
859             avio_wb32(pb, 6); /* unknown */
860     }
861     /* padding */
862     for (i = 0; i < 10; i++)
863         avio_wb64(pb, 0);
864
865     /* extra padding for stsd needed */
866     avio_wb32(pb, 0);
867     return 0;
868 }
869
870 static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
871 {
872     int tag = track->enc->codec_tag;
873
874     if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
875         return 0;
876
877     if      (track->enc->codec_id == AV_CODEC_ID_H264)      tag = MKTAG('a','v','c','1');
878     else if (track->enc->codec_id == AV_CODEC_ID_HEVC)      tag = MKTAG('h','e','v','1');
879     else if (track->enc->codec_id == AV_CODEC_ID_AC3)       tag = MKTAG('a','c','-','3');
880     else if (track->enc->codec_id == AV_CODEC_ID_DIRAC)     tag = MKTAG('d','r','a','c');
881     else if (track->enc->codec_id == AV_CODEC_ID_MOV_TEXT)  tag = MKTAG('t','x','3','g');
882     else if (track->enc->codec_id == AV_CODEC_ID_VC1)       tag = MKTAG('v','c','-','1');
883     else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)  tag = MKTAG('m','p','4','v');
884     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)  tag = MKTAG('m','p','4','a');
885     else if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)  tag = MKTAG('m','p','4','s');
886
887     return tag;
888 }
889
890 static const AVCodecTag codec_ipod_tags[] = {
891     { AV_CODEC_ID_H264,     MKTAG('a','v','c','1') },
892     { AV_CODEC_ID_MPEG4,    MKTAG('m','p','4','v') },
893     { AV_CODEC_ID_AAC,      MKTAG('m','p','4','a') },
894     { AV_CODEC_ID_ALAC,     MKTAG('a','l','a','c') },
895     { AV_CODEC_ID_AC3,      MKTAG('a','c','-','3') },
896     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
897     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
898     { AV_CODEC_ID_NONE, 0 },
899 };
900
901 static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
902 {
903     int tag = track->enc->codec_tag;
904
905     // keep original tag for subs, ipod supports both formats
906     if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
907           (tag == MKTAG('t', 'x', '3', 'g') ||
908            tag == MKTAG('t', 'e', 'x', 't'))))
909         tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
910
911     if (!av_match_ext(s->filename, "m4a") &&
912         !av_match_ext(s->filename, "m4b") &&
913         !av_match_ext(s->filename, "m4v"))
914         av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor  .m4b "
915                "Quicktime/Ipod might not play the file\n");
916
917     return tag;
918 }
919
920 static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
921 {
922     int tag;
923
924     if (track->enc->width == 720) { /* SD */
925         if (track->enc->height == 480) { /* NTSC */
926             if  (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
927             else                                            tag = MKTAG('d','v','c',' ');
928        }else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
929         else if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
930         else                                                tag = MKTAG('d','v','p','p');
931     } else if (track->enc->height == 720) { /* HD 720 line */
932         if  (track->st->time_base.den == 50)                tag = MKTAG('d','v','h','q');
933         else                                                tag = MKTAG('d','v','h','p');
934     } else if (track->enc->height == 1080) { /* HD 1080 line */
935         if  (track->st->time_base.den == 25)                tag = MKTAG('d','v','h','5');
936         else                                                tag = MKTAG('d','v','h','6');
937     } else {
938         av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
939         return 0;
940     }
941
942     return tag;
943 }
944
945 static AVRational find_fps(AVFormatContext *s, AVStream *st)
946 {
947     AVRational rate = {st->codec->time_base.den, st->codec->time_base.num};
948     /* if the codec time base makes no sense, try to fallback on stream frame rate */
949     if (av_timecode_check_frame_rate(rate) < 0) {
950         av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
951                rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
952         rate = st->avg_frame_rate;
953     }
954
955     return rate;
956 }
957
958 static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
959 {
960     int tag = track->enc->codec_tag;
961     int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
962     AVStream *st = track->st;
963     int rate = av_q2d(find_fps(s, st));
964
965     if (!tag)
966         tag = MKTAG('m', '2', 'v', '1'); //fallback tag
967
968     if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) {
969         if (track->enc->width == 1280 && track->enc->height == 720) {
970             if (!interlaced) {
971                 if      (rate == 24) tag = MKTAG('x','d','v','4');
972                 else if (rate == 25) tag = MKTAG('x','d','v','5');
973                 else if (rate == 30) tag = MKTAG('x','d','v','1');
974                 else if (rate == 50) tag = MKTAG('x','d','v','a');
975                 else if (rate == 60) tag = MKTAG('x','d','v','9');
976             }
977         } else if (track->enc->width == 1440 && track->enc->height == 1080) {
978             if (!interlaced) {
979                 if      (rate == 24) tag = MKTAG('x','d','v','6');
980                 else if (rate == 25) tag = MKTAG('x','d','v','7');
981                 else if (rate == 30) tag = MKTAG('x','d','v','8');
982             } else {
983                 if      (rate == 25) tag = MKTAG('x','d','v','3');
984                 else if (rate == 30) tag = MKTAG('x','d','v','2');
985             }
986         } else if (track->enc->width == 1920 && track->enc->height == 1080) {
987             if (!interlaced) {
988                 if      (rate == 24) tag = MKTAG('x','d','v','d');
989                 else if (rate == 25) tag = MKTAG('x','d','v','e');
990                 else if (rate == 30) tag = MKTAG('x','d','v','f');
991             } else {
992                 if      (rate == 25) tag = MKTAG('x','d','v','c');
993                 else if (rate == 30) tag = MKTAG('x','d','v','b');
994             }
995         }
996     } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
997         if (track->enc->width == 1280 && track->enc->height == 720) {
998             if (!interlaced) {
999                 if      (rate == 24) tag = MKTAG('x','d','5','4');
1000                 else if (rate == 25) tag = MKTAG('x','d','5','5');
1001                 else if (rate == 30) tag = MKTAG('x','d','5','1');
1002                 else if (rate == 50) tag = MKTAG('x','d','5','a');
1003                 else if (rate == 60) tag = MKTAG('x','d','5','9');
1004             }
1005         } else if (track->enc->width == 1920 && track->enc->height == 1080) {
1006             if (!interlaced) {
1007                 if      (rate == 24) tag = MKTAG('x','d','5','d');
1008                 else if (rate == 25) tag = MKTAG('x','d','5','e');
1009                 else if (rate == 30) tag = MKTAG('x','d','5','f');
1010             } else {
1011                 if      (rate == 25) tag = MKTAG('x','d','5','c');
1012                 else if (rate == 30) tag = MKTAG('x','d','5','b');
1013             }
1014         }
1015     }
1016
1017     return tag;
1018 }
1019
1020 static const struct {
1021     enum AVPixelFormat pix_fmt;
1022     uint32_t tag;
1023     unsigned bps;
1024 } mov_pix_fmt_tags[] = {
1025     { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'),  0 },
1026     { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'),  0 },
1027     { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'),  0 },
1028     { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1029     { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1030     { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1031     { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1032     { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1033     { AV_PIX_FMT_RGB24,   MKTAG('r','a','w',' '), 24 },
1034     { AV_PIX_FMT_BGR24,   MKTAG('2','4','B','G'), 24 },
1035     { AV_PIX_FMT_ARGB,    MKTAG('r','a','w',' '), 32 },
1036     { AV_PIX_FMT_BGRA,    MKTAG('B','G','R','A'), 32 },
1037     { AV_PIX_FMT_RGBA,    MKTAG('R','G','B','A'), 32 },
1038     { AV_PIX_FMT_ABGR,    MKTAG('A','B','G','R'), 32 },
1039     { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1040 };
1041
1042 static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
1043 {
1044     int tag = track->enc->codec_tag;
1045     int i;
1046     enum AVPixelFormat pix_fmt;
1047
1048     for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1049         if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
1050             tag = mov_pix_fmt_tags[i].tag;
1051             track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
1052             if (track->enc->codec_tag == mov_pix_fmt_tags[i].tag)
1053                 break;
1054         }
1055     }
1056
1057     pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
1058                                   track->enc->bits_per_coded_sample);
1059     if (tag == MKTAG('r','a','w',' ') &&
1060         track->enc->pix_fmt != pix_fmt &&
1061         track->enc->pix_fmt != AV_PIX_FMT_NONE)
1062         av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1063                av_get_pix_fmt_name(track->enc->pix_fmt));
1064     return tag;
1065 }
1066
1067 static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1068 {
1069     int tag = track->enc->codec_tag;
1070
1071     if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1072                  (track->enc->codec_id == AV_CODEC_ID_DVVIDEO ||
1073                   track->enc->codec_id == AV_CODEC_ID_RAWVIDEO ||
1074                   track->enc->codec_id == AV_CODEC_ID_H263 ||
1075                   track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1076                   av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
1077         if (track->enc->codec_id == AV_CODEC_ID_DVVIDEO)
1078             tag = mov_get_dv_codec_tag(s, track);
1079         else if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO)
1080             tag = mov_get_rawvideo_codec_tag(s, track);
1081         else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1082             tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
1083         else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1084             tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->enc->codec_id);
1085             if (!tag) { // if no mac fcc found, try with Microsoft tags
1086                 tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
1087                 if (tag)
1088                     av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1089                            "the file may be unplayable!\n");
1090             }
1091         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1092             tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->enc->codec_id);
1093             if (!tag) { // if no mac fcc found, try with Microsoft tags
1094                 int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
1095                 if (ms_tag) {
1096                     tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1097                     av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1098                            "the file may be unplayable!\n");
1099                 }
1100             }
1101         } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1102             tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
1103     }
1104
1105     return tag;
1106 }
1107
1108 static const AVCodecTag codec_3gp_tags[] = {
1109     { AV_CODEC_ID_H263,     MKTAG('s','2','6','3') },
1110     { AV_CODEC_ID_H264,     MKTAG('a','v','c','1') },
1111     { AV_CODEC_ID_MPEG4,    MKTAG('m','p','4','v') },
1112     { AV_CODEC_ID_AAC,      MKTAG('m','p','4','a') },
1113     { AV_CODEC_ID_AMR_NB,   MKTAG('s','a','m','r') },
1114     { AV_CODEC_ID_AMR_WB,   MKTAG('s','a','w','b') },
1115     { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
1116     { AV_CODEC_ID_NONE, 0 },
1117 };
1118
1119 static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
1120     { AV_CODEC_ID_MP3,    MKTAG('.','m','p','3') },
1121     { AV_CODEC_ID_AAC,    MKTAG('m','p','4','a') },
1122     { AV_CODEC_ID_H264,   MKTAG('a','v','c','1') },
1123     { AV_CODEC_ID_VP6A,   MKTAG('V','P','6','A') },
1124     { AV_CODEC_ID_VP6F,   MKTAG('V','P','6','F') },
1125     { AV_CODEC_ID_NONE, 0 },
1126 };
1127
1128 static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1129 {
1130     int tag;
1131
1132     if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
1133         tag = mp4_get_codec_tag(s, track);
1134     else if (track->mode == MODE_ISM) {
1135         tag = mp4_get_codec_tag(s, track);
1136         if (!tag && track->enc->codec_id == AV_CODEC_ID_WMAPRO)
1137             tag = MKTAG('w', 'm', 'a', ' ');
1138     } else if (track->mode == MODE_IPOD)
1139         tag = ipod_get_codec_tag(s, track);
1140     else if (track->mode & MODE_3GP)
1141         tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
1142     else if (track->mode == MODE_F4V)
1143         tag = ff_codec_get_tag(codec_f4v_tags, track->enc->codec_id);
1144     else
1145         tag = mov_get_codec_tag(s, track);
1146
1147     return tag;
1148 }
1149
1150 /** Write uuid atom.
1151  * Needed to make file play in iPods running newest firmware
1152  * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1153  */
1154 static int mov_write_uuid_tag_ipod(AVIOContext *pb)
1155 {
1156     avio_wb32(pb, 28);
1157     ffio_wfourcc(pb, "uuid");
1158     avio_wb32(pb, 0x6b6840f2);
1159     avio_wb32(pb, 0x5f244fc5);
1160     avio_wb32(pb, 0xba39a51b);
1161     avio_wb32(pb, 0xcf0323f3);
1162     avio_wb32(pb, 0x0);
1163     return 28;
1164 }
1165
1166 static const uint16_t fiel_data[] = {
1167     0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1168 };
1169
1170 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
1171 {
1172     unsigned mov_field_order = 0;
1173     if (track->enc->field_order < FF_ARRAY_ELEMS(fiel_data))
1174         mov_field_order = fiel_data[track->enc->field_order];
1175     else
1176         return 0;
1177     avio_wb32(pb, 10);
1178     ffio_wfourcc(pb, "fiel");
1179     avio_wb16(pb, mov_field_order);
1180     return 10;
1181 }
1182
1183 static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
1184 {
1185     int64_t pos = avio_tell(pb);
1186     avio_wb32(pb, 0);    /* size */
1187     avio_wl32(pb, track->tag); // store it byteswapped
1188     avio_wb32(pb, 0);    /* Reserved */
1189     avio_wb16(pb, 0);    /* Reserved */
1190     avio_wb16(pb, 1);    /* Data-reference index */
1191
1192     if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1193         mov_write_esds_tag(pb, track);
1194     else if (track->enc->extradata_size)
1195         avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1196
1197     return update_size(pb, pos);
1198 }
1199
1200 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1201 {
1202     AVRational sar;
1203     av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
1204               track->enc->sample_aspect_ratio.den, INT_MAX);
1205
1206     avio_wb32(pb, 16);
1207     ffio_wfourcc(pb, "pasp");
1208     avio_wb32(pb, sar.num);
1209     avio_wb32(pb, sar.den);
1210     return 16;
1211 }
1212
1213 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
1214 {
1215     AVDictionaryEntry *encoder;
1216     int xdcam_res =  (track->enc->width == 1280 && track->enc->height == 720)
1217                   || (track->enc->width == 1440 && track->enc->height == 1080)
1218                   || (track->enc->width == 1920 && track->enc->height == 1080);
1219
1220     if (track->mode == MODE_MOV &&
1221         (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
1222         av_strlcpy(compressor_name, encoder->value, 32);
1223     } else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
1224         int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
1225         AVStream *st = track->st;
1226         int rate = av_q2d(find_fps(NULL, st));
1227         av_strlcatf(compressor_name, len, "XDCAM");
1228         if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
1229             av_strlcatf(compressor_name, len, " HD422");
1230         } else if(track->enc->width == 1440) {
1231             av_strlcatf(compressor_name, len, " HD");
1232         } else
1233             av_strlcatf(compressor_name, len, " EX");
1234
1235         av_strlcatf(compressor_name, len, " %d%c", track->enc->height, interlaced ? 'i' : 'p');
1236
1237         av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
1238     }
1239 }
1240
1241 static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
1242 {
1243     int64_t pos = avio_tell(pb);
1244     char compressor_name[32] = { 0 };
1245
1246     avio_wb32(pb, 0); /* size */
1247     avio_wl32(pb, track->tag); // store it byteswapped
1248     avio_wb32(pb, 0); /* Reserved */
1249     avio_wb16(pb, 0); /* Reserved */
1250     avio_wb16(pb, 1); /* Data-reference index */
1251
1252     avio_wb16(pb, 0); /* Codec stream version */
1253     avio_wb16(pb, 0); /* Codec stream revision (=0) */
1254     if (track->mode == MODE_MOV) {
1255         ffio_wfourcc(pb, "FFMP"); /* Vendor */
1256         if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO) {
1257             avio_wb32(pb, 0); /* Temporal Quality */
1258             avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
1259         } else {
1260             avio_wb32(pb, 0x200); /* Temporal Quality = normal */
1261             avio_wb32(pb, 0x200); /* Spatial Quality = normal */
1262         }
1263     } else {
1264         avio_wb32(pb, 0); /* Reserved */
1265         avio_wb32(pb, 0); /* Reserved */
1266         avio_wb32(pb, 0); /* Reserved */
1267     }
1268     avio_wb16(pb, track->enc->width); /* Video width */
1269     avio_wb16(pb, track->height); /* Video height */
1270     avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
1271     avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
1272     avio_wb32(pb, 0); /* Data size (= 0) */
1273     avio_wb16(pb, 1); /* Frame count (= 1) */
1274
1275     /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
1276     find_compressor(compressor_name, 32, track);
1277     avio_w8(pb, strlen(compressor_name));
1278     avio_write(pb, compressor_name, 31);
1279
1280     if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
1281         avio_wb16(pb, track->enc->bits_per_coded_sample);
1282     else
1283         avio_wb16(pb, 0x18); /* Reserved */
1284     avio_wb16(pb, 0xffff); /* Reserved */
1285     if (track->tag == MKTAG('m','p','4','v'))
1286         mov_write_esds_tag(pb, track);
1287     else if (track->enc->codec_id == AV_CODEC_ID_H263)
1288         mov_write_d263_tag(pb);
1289     else if (track->enc->codec_id == AV_CODEC_ID_AVUI ||
1290             track->enc->codec_id == AV_CODEC_ID_SVQ3) {
1291         mov_write_extradata_tag(pb, track);
1292         avio_wb32(pb, 0);
1293     } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD)
1294         mov_write_avid_tag(pb, track);
1295     else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
1296         mov_write_hvcc_tag(pb, track);
1297     else if (track->enc->codec_id == AV_CODEC_ID_H264) {
1298         mov_write_avcc_tag(pb, track);
1299         if (track->mode == MODE_IPOD)
1300             mov_write_uuid_tag_ipod(pb);
1301     } else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
1302         mov_write_dvc1_tag(pb, track);
1303     else if (track->enc->codec_id == AV_CODEC_ID_VP6F ||
1304              track->enc->codec_id == AV_CODEC_ID_VP6A) {
1305         /* Don't write any potential extradata here - the cropping
1306          * is signalled via the normal width/height fields. */
1307     } else if (track->vos_len > 0)
1308         mov_write_glbl_tag(pb, track);
1309
1310     if (track->enc->codec_id != AV_CODEC_ID_H264 &&
1311         track->enc->codec_id != AV_CODEC_ID_MPEG4 &&
1312         track->enc->codec_id != AV_CODEC_ID_DNXHD)
1313         if (track->enc->field_order != AV_FIELD_UNKNOWN)
1314             mov_write_fiel_tag(pb, track);
1315
1316     if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
1317         track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
1318         mov_write_pasp_tag(pb, track);
1319     }
1320
1321     return update_size(pb, pos);
1322 }
1323
1324 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
1325 {
1326     int64_t pos = avio_tell(pb);
1327     avio_wb32(pb, 0); /* size */
1328     ffio_wfourcc(pb, "rtp ");
1329     avio_wb32(pb, 0); /* Reserved */
1330     avio_wb16(pb, 0); /* Reserved */
1331     avio_wb16(pb, 1); /* Data-reference index */
1332
1333     avio_wb16(pb, 1); /* Hint track version */
1334     avio_wb16(pb, 1); /* Highest compatible version */
1335     avio_wb32(pb, track->max_packet_size); /* Max packet size */
1336
1337     avio_wb32(pb, 12); /* size */
1338     ffio_wfourcc(pb, "tims");
1339     avio_wb32(pb, track->timescale);
1340
1341     return update_size(pb, pos);
1342 }
1343
1344 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
1345 {
1346     uint64_t str_size =strlen(reel_name);
1347     int64_t pos = avio_tell(pb);
1348
1349     if (str_size >= UINT16_MAX){
1350         av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
1351         avio_wb16(pb, 0);
1352         return AVERROR(EINVAL);
1353     }
1354
1355     avio_wb32(pb, 0);                              /* size */
1356     ffio_wfourcc(pb, "name");                      /* Data format */
1357     avio_wb16(pb, str_size);                       /* string size */
1358     avio_wb16(pb, track->language);                /* langcode */
1359     avio_write(pb, reel_name, str_size);           /* reel name */
1360     return update_size(pb,pos);
1361 }
1362
1363 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
1364 {
1365     int64_t pos = avio_tell(pb);
1366 #if 1
1367     int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);
1368     int nb_frames = 1.0/av_q2d(track->enc->time_base) + 0.5;
1369     AVDictionaryEntry *t = NULL;
1370
1371     if (nb_frames > 255) {
1372         av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
1373         return AVERROR(EINVAL);
1374     }
1375
1376     avio_wb32(pb, 0); /* size */
1377     ffio_wfourcc(pb, "tmcd");               /* Data format */
1378     avio_wb32(pb, 0);                       /* Reserved */
1379     avio_wb32(pb, 1);                       /* Data reference index */
1380     avio_wb32(pb, 0);                       /* Flags */
1381     avio_wb32(pb, track->timecode_flags);   /* Flags (timecode) */
1382     avio_wb32(pb, track->timescale);        /* Timescale */
1383     avio_wb32(pb, frame_duration);          /* Frame duration */
1384     avio_w8(pb, nb_frames);                 /* Number of frames */
1385     avio_w8(pb, 0);                         /* Reserved */
1386
1387     if (track->st)
1388         t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
1389
1390     if (t && utf8len(t->value))
1391         mov_write_source_reference_tag(pb, track, t->value);
1392     else
1393         avio_wb16(pb, 0); /* zero size */
1394 #else
1395
1396     avio_wb32(pb, 0); /* size */
1397     ffio_wfourcc(pb, "tmcd");               /* Data format */
1398     avio_wb32(pb, 0);                       /* Reserved */
1399     avio_wb32(pb, 1);                       /* Data reference index */
1400     if (track->enc->extradata_size)
1401         avio_write(pb, track->enc->extradata, track->enc->extradata_size);
1402 #endif
1403     return update_size(pb, pos);
1404 }
1405
1406 static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
1407 {
1408     int64_t pos = avio_tell(pb);
1409     avio_wb32(pb, 0); /* size */
1410     ffio_wfourcc(pb, "stsd");
1411     avio_wb32(pb, 0); /* version & flags */
1412     avio_wb32(pb, 1); /* entry count */
1413     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1414         mov_write_video_tag(pb, track);
1415     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1416         mov_write_audio_tag(pb, track);
1417     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
1418         mov_write_subtitle_tag(pb, track);
1419     else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
1420         mov_write_rtp_tag(pb, track);
1421     else if (track->enc->codec_tag == MKTAG('t','m','c','d'))
1422         mov_write_tmcd_tag(pb, track);
1423     return update_size(pb, pos);
1424 }
1425
1426 static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
1427 {
1428     MOVStts *ctts_entries;
1429     uint32_t entries = 0;
1430     uint32_t atom_size;
1431     int i;
1432
1433     ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
1434     ctts_entries[0].count = 1;
1435     ctts_entries[0].duration = track->cluster[0].cts;
1436     for (i = 1; i < track->entry; i++) {
1437         if (track->cluster[i].cts == ctts_entries[entries].duration) {
1438             ctts_entries[entries].count++; /* compress */
1439         } else {
1440             entries++;
1441             ctts_entries[entries].duration = track->cluster[i].cts;
1442             ctts_entries[entries].count = 1;
1443         }
1444     }
1445     entries++; /* last one */
1446     atom_size = 16 + (entries * 8);
1447     avio_wb32(pb, atom_size); /* size */
1448     ffio_wfourcc(pb, "ctts");
1449     avio_wb32(pb, 0); /* version & flags */
1450     avio_wb32(pb, entries); /* entry count */
1451     for (i = 0; i < entries; i++) {
1452         avio_wb32(pb, ctts_entries[i].count);
1453         avio_wb32(pb, ctts_entries[i].duration);
1454     }
1455     av_free(ctts_entries);
1456     return atom_size;
1457 }
1458
1459 /* Time to sample atom */
1460 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
1461 {
1462     MOVStts *stts_entries;
1463     uint32_t entries = -1;
1464     uint32_t atom_size;
1465     int i;
1466
1467     if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
1468         stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
1469         stts_entries[0].count = track->sample_count;
1470         stts_entries[0].duration = 1;
1471         entries = 1;
1472     } else {
1473         stts_entries = track->entry ?
1474                        av_malloc_array(track->entry, sizeof(*stts_entries)) : /* worst case */
1475                        NULL;
1476         for (i = 0; i < track->entry; i++) {
1477             int duration = get_cluster_duration(track, i);
1478             if (i && duration == stts_entries[entries].duration) {
1479                 stts_entries[entries].count++; /* compress */
1480             } else {
1481                 entries++;
1482                 stts_entries[entries].duration = duration;
1483                 stts_entries[entries].count = 1;
1484             }
1485         }
1486         entries++; /* last one */
1487     }
1488     atom_size = 16 + (entries * 8);
1489     avio_wb32(pb, atom_size); /* size */
1490     ffio_wfourcc(pb, "stts");
1491     avio_wb32(pb, 0); /* version & flags */
1492     avio_wb32(pb, entries); /* entry count */
1493     for (i = 0; i < entries; i++) {
1494         avio_wb32(pb, stts_entries[i].count);
1495         avio_wb32(pb, stts_entries[i].duration);
1496     }
1497     av_free(stts_entries);
1498     return atom_size;
1499 }
1500
1501 static int mov_write_dref_tag(AVIOContext *pb)
1502 {
1503     avio_wb32(pb, 28); /* size */
1504     ffio_wfourcc(pb, "dref");
1505     avio_wb32(pb, 0); /* version & flags */
1506     avio_wb32(pb, 1); /* entry count */
1507
1508     avio_wb32(pb, 0xc); /* size */
1509     //FIXME add the alis and rsrc atom
1510     ffio_wfourcc(pb, "url ");
1511     avio_wb32(pb, 1); /* version & flags */
1512
1513     return 28;
1514 }
1515
1516 static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
1517 {
1518     int64_t pos = avio_tell(pb);
1519     avio_wb32(pb, 0); /* size */
1520     ffio_wfourcc(pb, "stbl");
1521     mov_write_stsd_tag(pb, track);
1522     mov_write_stts_tag(pb, track);
1523     if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1524          track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
1525         track->has_keyframes && track->has_keyframes < track->entry)
1526         mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
1527     if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
1528         mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
1529     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
1530         track->flags & MOV_TRACK_CTTS)
1531         mov_write_ctts_tag(pb, track);
1532     mov_write_stsc_tag(pb, track);
1533     mov_write_stsz_tag(pb, track);
1534     mov_write_stco_tag(pb, track);
1535     return update_size(pb, pos);
1536 }
1537
1538 static int mov_write_dinf_tag(AVIOContext *pb)
1539 {
1540     int64_t pos = avio_tell(pb);
1541     avio_wb32(pb, 0); /* size */
1542     ffio_wfourcc(pb, "dinf");
1543     mov_write_dref_tag(pb);
1544     return update_size(pb, pos);
1545 }
1546
1547 static int mov_write_nmhd_tag(AVIOContext *pb)
1548 {
1549     avio_wb32(pb, 12);
1550     ffio_wfourcc(pb, "nmhd");
1551     avio_wb32(pb, 0);
1552     return 12;
1553 }
1554
1555 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
1556 {
1557     int64_t pos = avio_tell(pb);
1558     const char *font = "Lucida Grande";
1559     avio_wb32(pb, 0);                   /* size */
1560     ffio_wfourcc(pb, "tcmi");           /* timecode media information atom */
1561     avio_wb32(pb, 0);                   /* version & flags */
1562     avio_wb16(pb, 0);                   /* text font */
1563     avio_wb16(pb, 0);                   /* text face */
1564     avio_wb16(pb, 12);                  /* text size */
1565     avio_wb16(pb, 0);                   /* (unknown, not in the QT specs...) */
1566     avio_wb16(pb, 0x0000);              /* text color (red) */
1567     avio_wb16(pb, 0x0000);              /* text color (green) */
1568     avio_wb16(pb, 0x0000);              /* text color (blue) */
1569     avio_wb16(pb, 0xffff);              /* background color (red) */
1570     avio_wb16(pb, 0xffff);              /* background color (green) */
1571     avio_wb16(pb, 0xffff);              /* background color (blue) */
1572     avio_w8(pb, strlen(font));          /* font len (part of the pascal string) */
1573     avio_write(pb, font, strlen(font)); /* font name */
1574     return update_size(pb, pos);
1575 }
1576
1577 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
1578 {
1579     int64_t pos = avio_tell(pb);
1580     avio_wb32(pb, 0);      /* size */
1581     ffio_wfourcc(pb, "gmhd");
1582     avio_wb32(pb, 0x18);   /* gmin size */
1583     ffio_wfourcc(pb, "gmin");/* generic media info */
1584     avio_wb32(pb, 0);      /* version & flags */
1585     avio_wb16(pb, 0x40);   /* graphics mode = */
1586     avio_wb16(pb, 0x8000); /* opColor (r?) */
1587     avio_wb16(pb, 0x8000); /* opColor (g?) */
1588     avio_wb16(pb, 0x8000); /* opColor (b?) */
1589     avio_wb16(pb, 0);      /* balance */
1590     avio_wb16(pb, 0);      /* reserved */
1591
1592     /*
1593      * This special text atom is required for
1594      * Apple Quicktime chapters. The contents
1595      * don't appear to be documented, so the
1596      * bytes are copied verbatim.
1597      */
1598     if (track->tag != MKTAG('c','6','0','8')) {
1599     avio_wb32(pb, 0x2C);   /* size */
1600     ffio_wfourcc(pb, "text");
1601     avio_wb16(pb, 0x01);
1602     avio_wb32(pb, 0x00);
1603     avio_wb32(pb, 0x00);
1604     avio_wb32(pb, 0x00);
1605     avio_wb32(pb, 0x01);
1606     avio_wb32(pb, 0x00);
1607     avio_wb32(pb, 0x00);
1608     avio_wb32(pb, 0x00);
1609     avio_wb32(pb, 0x00004000);
1610     avio_wb16(pb, 0x0000);
1611     }
1612
1613     if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1614         int64_t tmcd_pos = avio_tell(pb);
1615         avio_wb32(pb, 0); /* size */
1616         ffio_wfourcc(pb, "tmcd");
1617         mov_write_tcmi_tag(pb, track);
1618         update_size(pb, tmcd_pos);
1619     }
1620     return update_size(pb, pos);
1621 }
1622
1623 static int mov_write_smhd_tag(AVIOContext *pb)
1624 {
1625     avio_wb32(pb, 16); /* size */
1626     ffio_wfourcc(pb, "smhd");
1627     avio_wb32(pb, 0); /* version & flags */
1628     avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
1629     avio_wb16(pb, 0); /* reserved */
1630     return 16;
1631 }
1632
1633 static int mov_write_vmhd_tag(AVIOContext *pb)
1634 {
1635     avio_wb32(pb, 0x14); /* size (always 0x14) */
1636     ffio_wfourcc(pb, "vmhd");
1637     avio_wb32(pb, 0x01); /* version & flags */
1638     avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
1639     return 0x14;
1640 }
1641
1642 static int is_clcp_track(MOVTrack *track)
1643 {
1644     return track->tag == MKTAG('c','7','0','8') ||
1645            track->tag == MKTAG('c','6','0','8');
1646 }
1647
1648 static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
1649 {
1650     const char *hdlr, *descr = NULL, *hdlr_type = NULL;
1651     int64_t pos = avio_tell(pb);
1652
1653     hdlr      = "dhlr";
1654     hdlr_type = "url ";
1655     descr     = "DataHandler";
1656
1657     if (track) {
1658         hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
1659         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1660             hdlr_type = "vide";
1661             descr     = "VideoHandler";
1662         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
1663             hdlr_type = "soun";
1664             descr     = "SoundHandler";
1665         } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1666             if (is_clcp_track(track)) {
1667                 hdlr_type = "clcp";
1668                 descr = "ClosedCaptionHandler";
1669             } else {
1670                 if (track->tag == MKTAG('t','x','3','g')) {
1671                     hdlr_type = "sbtl";
1672                 } else if (track->tag == MKTAG('m','p','4','s')) {
1673                     hdlr_type = "subp";
1674                 } else {
1675                     hdlr_type = "text";
1676                 }
1677             descr = "SubtitleHandler";
1678             }
1679         } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
1680             hdlr_type = "hint";
1681             descr     = "HintHandler";
1682         } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
1683             hdlr_type = "tmcd";
1684             descr = "TimeCodeHandler";
1685         } else {
1686             char tag_buf[32];
1687             av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
1688                                     track->enc->codec_tag);
1689
1690             av_log(track->enc, AV_LOG_WARNING,
1691                    "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
1692                    tag_buf, track->enc->codec_tag);
1693         }
1694         if (track->st) {
1695             // hdlr.name is used by some players to identify the content title
1696             // of the track. So if an alternate handler description is
1697             // specified, use it.
1698             AVDictionaryEntry *t;
1699             t = av_dict_get(track->st->metadata, "handler", NULL, 0);
1700             if (t && utf8len(t->value))
1701                 descr = t->value;
1702         }
1703     }
1704
1705     avio_wb32(pb, 0); /* size */
1706     ffio_wfourcc(pb, "hdlr");
1707     avio_wb32(pb, 0); /* Version & flags */
1708     avio_write(pb, hdlr, 4); /* handler */
1709     ffio_wfourcc(pb, hdlr_type); /* handler type */
1710     avio_wb32(pb, 0); /* reserved */
1711     avio_wb32(pb, 0); /* reserved */
1712     avio_wb32(pb, 0); /* reserved */
1713     if (!track || track->mode == MODE_MOV)
1714         avio_w8(pb, strlen(descr)); /* pascal string */
1715     avio_write(pb, descr, strlen(descr)); /* handler description */
1716     if (track && track->mode != MODE_MOV)
1717         avio_w8(pb, 0); /* c string */
1718     return update_size(pb, pos);
1719 }
1720
1721 static int mov_write_hmhd_tag(AVIOContext *pb)
1722 {
1723     /* This atom must be present, but leaving the values at zero
1724      * seems harmless. */
1725     avio_wb32(pb, 28); /* size */
1726     ffio_wfourcc(pb, "hmhd");
1727     avio_wb32(pb, 0); /* version, flags */
1728     avio_wb16(pb, 0); /* maxPDUsize */
1729     avio_wb16(pb, 0); /* avgPDUsize */
1730     avio_wb32(pb, 0); /* maxbitrate */
1731     avio_wb32(pb, 0); /* avgbitrate */
1732     avio_wb32(pb, 0); /* reserved */
1733     return 28;
1734 }
1735
1736 static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
1737 {
1738     int64_t pos = avio_tell(pb);
1739     avio_wb32(pb, 0); /* size */
1740     ffio_wfourcc(pb, "minf");
1741     if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
1742         mov_write_vmhd_tag(pb);
1743     else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1744         mov_write_smhd_tag(pb);
1745     else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1746         if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
1747             mov_write_gmhd_tag(pb, track);
1748         } else {
1749             mov_write_nmhd_tag(pb);
1750         }
1751     } else if (track->tag == MKTAG('r','t','p',' ')) {
1752         mov_write_hmhd_tag(pb);
1753     } else if (track->tag == MKTAG('t','m','c','d')) {
1754         mov_write_gmhd_tag(pb, track);
1755     }
1756     if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
1757         mov_write_hdlr_tag(pb, NULL);
1758     mov_write_dinf_tag(pb);
1759     mov_write_stbl_tag(pb, track);
1760     return update_size(pb, pos);
1761 }
1762
1763 static int mov_write_mdhd_tag(AVIOContext *pb, MOVTrack *track)
1764 {
1765     int version = track->track_duration < INT32_MAX ? 0 : 1;
1766
1767     if (track->mode == MODE_ISM)
1768         version = 1;
1769
1770     (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
1771     ffio_wfourcc(pb, "mdhd");
1772     avio_w8(pb, version);
1773     avio_wb24(pb, 0); /* flags */
1774     if (version == 1) {
1775         avio_wb64(pb, track->time);
1776         avio_wb64(pb, track->time);
1777     } else {
1778         avio_wb32(pb, track->time); /* creation time */
1779         avio_wb32(pb, track->time); /* modification time */
1780     }
1781     avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
1782     if (!track->entry)
1783         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1784     else
1785         (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
1786     avio_wb16(pb, track->language); /* language */
1787     avio_wb16(pb, 0); /* reserved (quality) */
1788
1789     if (version != 0 && track->mode == MODE_MOV) {
1790         av_log(NULL, AV_LOG_ERROR,
1791                "FATAL error, file duration too long for timebase, this file will not be\n"
1792                "playable with quicktime. Choose a different timebase or a different\n"
1793                "container format\n");
1794     }
1795
1796     return 32;
1797 }
1798
1799 static int mov_write_mdia_tag(AVIOContext *pb, MOVTrack *track)
1800 {
1801     int64_t pos = avio_tell(pb);
1802     avio_wb32(pb, 0); /* size */
1803     ffio_wfourcc(pb, "mdia");
1804     mov_write_mdhd_tag(pb, track);
1805     mov_write_hdlr_tag(pb, track);
1806     mov_write_minf_tag(pb, track);
1807     return update_size(pb, pos);
1808 }
1809
1810 /* transformation matrix
1811      |a  b  u|
1812      |c  d  v|
1813      |tx ty w| */
1814 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
1815                          int16_t d, int16_t tx, int16_t ty)
1816 {
1817     avio_wb32(pb, a << 16);  /* 16.16 format */
1818     avio_wb32(pb, b << 16);  /* 16.16 format */
1819     avio_wb32(pb, 0);        /* u in 2.30 format */
1820     avio_wb32(pb, c << 16);  /* 16.16 format */
1821     avio_wb32(pb, d << 16);  /* 16.16 format */
1822     avio_wb32(pb, 0);        /* v in 2.30 format */
1823     avio_wb32(pb, tx << 16); /* 16.16 format */
1824     avio_wb32(pb, ty << 16); /* 16.16 format */
1825     avio_wb32(pb, 1 << 30);  /* w in 2.30 format */
1826 }
1827
1828 static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
1829                               MOVTrack *track, AVStream *st)
1830 {
1831     int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1832                                       track->timescale, AV_ROUND_UP);
1833     int version = duration < INT32_MAX ? 0 : 1;
1834     int flags   = MOV_TKHD_FLAG_IN_MOVIE;
1835     int rotation = 0;
1836     int group   = 0;
1837
1838
1839     if (st) {
1840         if (mov->per_stream_grouping)
1841             group = st->index;
1842         else
1843             group = st->codec->codec_type;
1844     }
1845
1846     if (track->flags & MOV_TRACK_ENABLED)
1847         flags |= MOV_TKHD_FLAG_ENABLED;
1848
1849     if (track->mode == MODE_ISM)
1850         version = 1;
1851
1852     (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
1853     ffio_wfourcc(pb, "tkhd");
1854     avio_w8(pb, version);
1855     avio_wb24(pb, flags);
1856     if (version == 1) {
1857         avio_wb64(pb, track->time);
1858         avio_wb64(pb, track->time);
1859     } else {
1860         avio_wb32(pb, track->time); /* creation time */
1861         avio_wb32(pb, track->time); /* modification time */
1862     }
1863     avio_wb32(pb, track->track_id); /* track-id */
1864     avio_wb32(pb, 0); /* reserved */
1865     if (!track->entry)
1866         (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
1867     else
1868         (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
1869
1870     avio_wb32(pb, 0); /* reserved */
1871     avio_wb32(pb, 0); /* reserved */
1872     avio_wb16(pb, 0); /* layer */
1873     avio_wb16(pb, group); /* alternate group) */
1874     /* Volume, only for audio */
1875     if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
1876         avio_wb16(pb, 0x0100);
1877     else
1878         avio_wb16(pb, 0);
1879     avio_wb16(pb, 0); /* reserved */
1880
1881     /* Matrix structure */
1882     if (st && st->metadata) {
1883         AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
1884         rotation = (rot && rot->value) ? atoi(rot->value) : 0;
1885     }
1886     if (rotation == 90) {
1887         write_matrix(pb,  0,  1, -1,  0, track->enc->height, 0);
1888     } else if (rotation == 180) {
1889         write_matrix(pb, -1,  0,  0, -1, track->enc->width, track->enc->height);
1890     } else if (rotation == 270) {
1891         write_matrix(pb,  0, -1,  1,  0, 0, track->enc->width);
1892     } else {
1893         write_matrix(pb,  1,  0,  0,  1, 0, 0);
1894     }
1895     /* Track width and height, for visual only */
1896     if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
1897                track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
1898         if (track->mode == MODE_MOV) {
1899             avio_wb32(pb, track->enc->width << 16);
1900             avio_wb32(pb, track->height << 16);
1901         } else {
1902             double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
1903             if (!sample_aspect_ratio || track->height != track->enc->height)
1904                 sample_aspect_ratio = 1;
1905             avio_wb32(pb, sample_aspect_ratio * track->enc->width * 0x10000);
1906             avio_wb32(pb, track->height * 0x10000);
1907         }
1908     } else {
1909         avio_wb32(pb, 0);
1910         avio_wb32(pb, 0);
1911     }
1912     return 0x5c;
1913 }
1914
1915 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
1916 {
1917     int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
1918                                track->enc->sample_aspect_ratio.den);
1919
1920     int64_t pos = avio_tell(pb);
1921
1922     avio_wb32(pb, 0); /* size */
1923     ffio_wfourcc(pb, "tapt");
1924
1925     avio_wb32(pb, 20);
1926     ffio_wfourcc(pb, "clef");
1927     avio_wb32(pb, 0);
1928     avio_wb32(pb, width << 16);
1929     avio_wb32(pb, track->enc->height << 16);
1930
1931     avio_wb32(pb, 20);
1932     ffio_wfourcc(pb, "prof");
1933     avio_wb32(pb, 0);
1934     avio_wb32(pb, width << 16);
1935     avio_wb32(pb, track->enc->height << 16);
1936
1937     avio_wb32(pb, 20);
1938     ffio_wfourcc(pb, "enof");
1939     avio_wb32(pb, 0);
1940     avio_wb32(pb, track->enc->width << 16);
1941     avio_wb32(pb, track->enc->height << 16);
1942
1943     return update_size(pb, pos);
1944 }
1945
1946 // This box seems important for the psp playback ... without it the movie seems to hang
1947 static int mov_write_edts_tag(AVIOContext *pb, MOVTrack *track)
1948 {
1949     int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
1950                                       track->timescale, AV_ROUND_UP);
1951     int version = duration < INT32_MAX ? 0 : 1;
1952     int entry_size, entry_count, size;
1953     int64_t delay, start_ct = track->cluster[0].cts;
1954     delay = av_rescale_rnd(track->cluster[0].dts + start_ct, MOV_TIMESCALE,
1955                            track->timescale, AV_ROUND_DOWN);
1956     version |= delay < INT32_MAX ? 0 : 1;
1957
1958     entry_size = (version == 1) ? 20 : 12;
1959     entry_count = 1 + (delay > 0);
1960     size = 24 + entry_count * entry_size;
1961
1962     /* write the atom data */
1963     avio_wb32(pb, size);
1964     ffio_wfourcc(pb, "edts");
1965     avio_wb32(pb, size - 8);
1966     ffio_wfourcc(pb, "elst");
1967     avio_w8(pb, version);
1968     avio_wb24(pb, 0); /* flags */
1969
1970     avio_wb32(pb, entry_count);
1971     if (delay > 0) { /* add an empty edit to delay presentation */
1972         if (version == 1) {
1973             avio_wb64(pb, delay);
1974             avio_wb64(pb, -1);
1975         } else {
1976             avio_wb32(pb, delay);
1977             avio_wb32(pb, -1);
1978         }
1979         avio_wb32(pb, 0x00010000);
1980     } else {
1981         av_assert0(av_rescale_rnd(track->cluster[0].dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
1982         start_ct  = -FFMIN(track->cluster[0].dts, 0); //FFMIN needed due to rounding
1983         duration += delay;
1984     }
1985
1986     /* duration */
1987     if (version == 1) {
1988         avio_wb64(pb, duration);
1989         avio_wb64(pb, start_ct);
1990     } else {
1991         avio_wb32(pb, duration);
1992         avio_wb32(pb, start_ct);
1993     }
1994     avio_wb32(pb, 0x00010000);
1995     return size;
1996 }
1997
1998 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
1999 {
2000     avio_wb32(pb, 20);   // size
2001     ffio_wfourcc(pb, "tref");
2002     avio_wb32(pb, 12);   // size (subatom)
2003     avio_wl32(pb, track->tref_tag);
2004     avio_wb32(pb, track->tref_id);
2005     return 20;
2006 }
2007
2008 // goes at the end of each track!  ... Critical for PSP playback ("Incompatible data" without it)
2009 static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
2010 {
2011     avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
2012     ffio_wfourcc(pb, "uuid");
2013     ffio_wfourcc(pb, "USMT");
2014     avio_wb32(pb, 0x21d24fce);
2015     avio_wb32(pb, 0xbb88695c);
2016     avio_wb32(pb, 0xfac9c740);
2017     avio_wb32(pb, 0x1c);     // another size here!
2018     ffio_wfourcc(pb, "MTDT");
2019     avio_wb32(pb, 0x00010012);
2020     avio_wb32(pb, 0x0a);
2021     avio_wb32(pb, 0x55c40000);
2022     avio_wb32(pb, 0x1);
2023     avio_wb32(pb, 0x0);
2024     return 0x34;
2025 }
2026
2027 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
2028 {
2029     AVFormatContext *ctx = track->rtp_ctx;
2030     char buf[1000] = "";
2031     int len;
2032
2033     ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
2034                        NULL, NULL, 0, 0, ctx);
2035     av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
2036     len = strlen(buf);
2037
2038     avio_wb32(pb, len + 24);
2039     ffio_wfourcc(pb, "udta");
2040     avio_wb32(pb, len + 16);
2041     ffio_wfourcc(pb, "hnti");
2042     avio_wb32(pb, len + 8);
2043     ffio_wfourcc(pb, "sdp ");
2044     avio_write(pb, buf, len);
2045     return len + 24;
2046 }
2047
2048 static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
2049                                     const char *tag, const char *str)
2050 {
2051     int64_t pos = avio_tell(pb);
2052     AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
2053     if (!t || !utf8len(t->value))
2054         return 0;
2055
2056     avio_wb32(pb, 0);   /* size */
2057     ffio_wfourcc(pb, tag); /* type */
2058     avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
2059     return update_size(pb, pos);
2060 }
2061
2062 static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2063                                     AVStream *st)
2064 {
2065     AVIOContext *pb_buf;
2066     int ret, size;
2067     uint8_t *buf;
2068
2069     if (!st || mov->fc->flags & AVFMT_FLAG_BITEXACT)
2070         return 0;
2071
2072     ret = avio_open_dyn_buf(&pb_buf);
2073     if (ret < 0)
2074         return ret;
2075
2076     if (mov->mode & MODE_MP4)
2077         mov_write_track_metadata(pb_buf, st, "name", "title");
2078
2079     if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2080         avio_wb32(pb, size + 8);
2081         ffio_wfourcc(pb, "udta");
2082         avio_write(pb, buf, size);
2083     }
2084     av_free(buf);
2085
2086     return 0;
2087 }
2088
2089 static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
2090                               MOVTrack *track, AVStream *st)
2091 {
2092     int64_t pos = avio_tell(pb);
2093     avio_wb32(pb, 0); /* size */
2094     ffio_wfourcc(pb, "trak");
2095     mov_write_tkhd_tag(pb, mov, track, st);
2096     if (supports_edts(mov))
2097         mov_write_edts_tag(pb, track);  // PSP Movies and several other cases require edts box
2098     if (track->tref_tag)
2099         mov_write_tref_tag(pb, track);
2100     mov_write_mdia_tag(pb, track);
2101     if (track->mode == MODE_PSP)
2102         mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
2103     if (track->tag == MKTAG('r','t','p',' '))
2104         mov_write_udta_sdp(pb, track);
2105     if (track->mode == MODE_MOV) {
2106         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2107             double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
2108             if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
2109                 mov_write_tapt_tag(pb, track);
2110             }
2111         }
2112         if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
2113             mov_write_tapt_tag(pb, track);
2114         }
2115     }
2116     mov_write_track_udta_tag(pb, mov, st);
2117     return update_size(pb, pos);
2118 }
2119
2120 static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
2121 {
2122     int i, has_audio = 0, has_video = 0;
2123     int64_t pos = avio_tell(pb);
2124     int audio_profile = mov->iods_audio_profile;
2125     int video_profile = mov->iods_video_profile;
2126     for (i = 0; i < mov->nb_streams; i++) {
2127         if (mov->tracks[i].entry > 0) {
2128             has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
2129             has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
2130         }
2131     }
2132     if (audio_profile < 0)
2133         audio_profile = 0xFF - has_audio;
2134     if (video_profile < 0)
2135         video_profile = 0xFF - has_video;
2136     avio_wb32(pb, 0x0); /* size */
2137     ffio_wfourcc(pb, "iods");
2138     avio_wb32(pb, 0);    /* version & flags */
2139     put_descr(pb, 0x10, 7);
2140     avio_wb16(pb, 0x004f);
2141     avio_w8(pb, 0xff);
2142     avio_w8(pb, 0xff);
2143     avio_w8(pb, audio_profile);
2144     avio_w8(pb, video_profile);
2145     avio_w8(pb, 0xff);
2146     return update_size(pb, pos);
2147 }
2148
2149 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
2150 {
2151     avio_wb32(pb, 0x20); /* size */
2152     ffio_wfourcc(pb, "trex");
2153     avio_wb32(pb, 0);   /* version & flags */
2154     avio_wb32(pb, track->track_id); /* track ID */
2155     avio_wb32(pb, 1);   /* default sample description index */
2156     avio_wb32(pb, 0);   /* default sample duration */
2157     avio_wb32(pb, 0);   /* default sample size */
2158     avio_wb32(pb, 0);   /* default sample flags */
2159     return 0;
2160 }
2161
2162 static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
2163 {
2164     int64_t pos = avio_tell(pb);
2165     int i;
2166     avio_wb32(pb, 0x0); /* size */
2167     ffio_wfourcc(pb, "mvex");
2168     for (i = 0; i < mov->nb_streams; i++)
2169         mov_write_trex_tag(pb, &mov->tracks[i]);
2170     return update_size(pb, pos);
2171 }
2172
2173 static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2174 {
2175     int max_track_id = 1, i;
2176     int64_t max_track_len_temp, max_track_len = 0;
2177     int version;
2178
2179     for (i = 0; i < mov->nb_streams; i++) {
2180         if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
2181             max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
2182                                                 MOV_TIMESCALE,
2183                                                 mov->tracks[i].timescale,
2184                                                 AV_ROUND_UP);
2185             if (max_track_len < max_track_len_temp)
2186                 max_track_len = max_track_len_temp;
2187             if (max_track_id < mov->tracks[i].track_id)
2188                 max_track_id = mov->tracks[i].track_id;
2189         }
2190     }
2191
2192     version = max_track_len < UINT32_MAX ? 0 : 1;
2193     (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
2194     ffio_wfourcc(pb, "mvhd");
2195     avio_w8(pb, version);
2196     avio_wb24(pb, 0); /* flags */
2197     if (version == 1) {
2198         avio_wb64(pb, mov->time);
2199         avio_wb64(pb, mov->time);
2200     } else {
2201         avio_wb32(pb, mov->time); /* creation time */
2202         avio_wb32(pb, mov->time); /* modification time */
2203     }
2204     avio_wb32(pb, MOV_TIMESCALE);
2205     (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
2206
2207     avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
2208     avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
2209     avio_wb16(pb, 0); /* reserved */
2210     avio_wb32(pb, 0); /* reserved */
2211     avio_wb32(pb, 0); /* reserved */
2212
2213     /* Matrix structure */
2214     write_matrix(pb, 1, 0, 0, 1, 0, 0);
2215
2216     avio_wb32(pb, 0); /* reserved (preview time) */
2217     avio_wb32(pb, 0); /* reserved (preview duration) */
2218     avio_wb32(pb, 0); /* reserved (poster time) */
2219     avio_wb32(pb, 0); /* reserved (selection time) */
2220     avio_wb32(pb, 0); /* reserved (selection duration) */
2221     avio_wb32(pb, 0); /* reserved (current time) */
2222     avio_wb32(pb, max_track_id + 1); /* Next track id */
2223     return 0x6c;
2224 }
2225
2226 static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
2227                                      AVFormatContext *s)
2228 {
2229     avio_wb32(pb, 33); /* size */
2230     ffio_wfourcc(pb, "hdlr");
2231     avio_wb32(pb, 0);
2232     avio_wb32(pb, 0);
2233     ffio_wfourcc(pb, "mdir");
2234     ffio_wfourcc(pb, "appl");
2235     avio_wb32(pb, 0);
2236     avio_wb32(pb, 0);
2237     avio_w8(pb, 0);
2238     return 33;
2239 }
2240
2241 /* helper function to write a data tag with the specified string as data */
2242 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
2243 {
2244     if (long_style) {
2245         int size = 16 + strlen(data);
2246         avio_wb32(pb, size); /* size */
2247         ffio_wfourcc(pb, "data");
2248         avio_wb32(pb, 1);
2249         avio_wb32(pb, 0);
2250         avio_write(pb, data, strlen(data));
2251         return size;
2252     } else {
2253         if (!lang)
2254             lang = ff_mov_iso639_to_lang("und", 1);
2255         avio_wb16(pb, strlen(data)); /* string length */
2256         avio_wb16(pb, lang);
2257         avio_write(pb, data, strlen(data));
2258         return strlen(data) + 4;
2259     }
2260 }
2261
2262 static int mov_write_string_tag(AVIOContext *pb, const char *name,
2263                                 const char *value, int lang, int long_style)
2264 {
2265     int size = 0;
2266     if (value && value[0]) {
2267         int64_t pos = avio_tell(pb);
2268         avio_wb32(pb, 0); /* size */
2269         ffio_wfourcc(pb, name);
2270         mov_write_string_data_tag(pb, value, lang, long_style);
2271         size = update_size(pb, pos);
2272     }
2273     return size;
2274 }
2275
2276 static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
2277                                      const char *name, const char *tag,
2278                                      int long_style)
2279 {
2280     int l, lang = 0, len, len2;
2281     AVDictionaryEntry *t, *t2 = NULL;
2282     char tag2[16];
2283
2284     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2285         return 0;
2286
2287     len = strlen(t->key);
2288     snprintf(tag2, sizeof(tag2), "%s-", tag);
2289     while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
2290         len2 = strlen(t2->key);
2291         if (len2 == len + 4 && !strcmp(t->value, t2->value)
2292             && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
2293             lang = l;
2294             break;
2295         }
2296     }
2297     return mov_write_string_tag(pb, name, t->value, lang, long_style);
2298 }
2299
2300 /* iTunes bpm number */
2301 static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
2302 {
2303     AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
2304     int size = 0, tmpo = t ? atoi(t->value) : 0;
2305     if (tmpo) {
2306         size = 26;
2307         avio_wb32(pb, size);
2308         ffio_wfourcc(pb, "tmpo");
2309         avio_wb32(pb, size-8); /* size */
2310         ffio_wfourcc(pb, "data");
2311         avio_wb32(pb, 0x15);  //type specifier
2312         avio_wb32(pb, 0);
2313         avio_wb16(pb, tmpo);        // data
2314     }
2315     return size;
2316 }
2317
2318 /* iTunes track or disc number */
2319 static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
2320                               AVFormatContext *s, int disc)
2321 {
2322     AVDictionaryEntry *t = av_dict_get(s->metadata,
2323                                        disc ? "disc" : "track",
2324                                        NULL, 0);
2325     int size = 0, track = t ? atoi(t->value) : 0;
2326     if (track) {
2327         int tracks = 0;
2328         char *slash = strchr(t->value, '/');
2329         if (slash)
2330             tracks = atoi(slash + 1);
2331         avio_wb32(pb, 32); /* size */
2332         ffio_wfourcc(pb, disc ? "disk" : "trkn");
2333         avio_wb32(pb, 24); /* size */
2334         ffio_wfourcc(pb, "data");
2335         avio_wb32(pb, 0);        // 8 bytes empty
2336         avio_wb32(pb, 0);
2337         avio_wb16(pb, 0);        // empty
2338         avio_wb16(pb, track);    // track / disc number
2339         avio_wb16(pb, tracks);   // total track / disc number
2340         avio_wb16(pb, 0);        // empty
2341         size = 32;
2342     }
2343     return size;
2344 }
2345
2346 static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
2347                                    const char *name, const char *tag,
2348                                    int len)
2349 {
2350     AVDictionaryEntry *t = NULL;
2351     uint8_t num;
2352     int size = 24 + len;
2353
2354     if (len != 1 && len != 4)
2355         return -1;
2356
2357     if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
2358         return 0;
2359     num = atoi(t->value);
2360
2361     avio_wb32(pb, size);
2362     ffio_wfourcc(pb, name);
2363     avio_wb32(pb, size - 8);
2364     ffio_wfourcc(pb, "data");
2365     avio_wb32(pb, 0x15);
2366     avio_wb32(pb, 0);
2367     if (len==4) avio_wb32(pb, num);
2368     else        avio_w8 (pb, num);
2369
2370     return size;
2371 }
2372
2373 /* iTunes meta data list */
2374 static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
2375                               AVFormatContext *s)
2376 {
2377     int64_t pos = avio_tell(pb);
2378     avio_wb32(pb, 0); /* size */
2379     ffio_wfourcc(pb, "ilst");
2380     mov_write_string_metadata(s, pb, "\251nam", "title"    , 1);
2381     mov_write_string_metadata(s, pb, "\251ART", "artist"   , 1);
2382     mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
2383     mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
2384     mov_write_string_metadata(s, pb, "\251alb", "album"    , 1);
2385     mov_write_string_metadata(s, pb, "\251day", "date"     , 1);
2386     if (!mov->exact &&
2387         !mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1))
2388         mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
2389     mov_write_string_metadata(s, pb, "\251cmt", "comment"  , 1);
2390     mov_write_string_metadata(s, pb, "\251gen", "genre"    , 1);
2391     mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
2392     mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
2393     mov_write_string_metadata(s, pb, "\251lyr", "lyrics"   , 1);
2394     mov_write_string_metadata(s, pb, "desc",    "description",1);
2395     mov_write_string_metadata(s, pb, "ldes",    "synopsis" , 1);
2396     mov_write_string_metadata(s, pb, "tvsh",    "show"     , 1);
2397     mov_write_string_metadata(s, pb, "tven",    "episode_id",1);
2398     mov_write_string_metadata(s, pb, "tvnn",    "network"  , 1);
2399     mov_write_int8_metadata  (s, pb, "tves",    "episode_sort",4);
2400     mov_write_int8_metadata  (s, pb, "tvsn",    "season_number",4);
2401     mov_write_int8_metadata  (s, pb, "stik",    "media_type",1);
2402     mov_write_int8_metadata  (s, pb, "hdvd",    "hd_video",  1);
2403     mov_write_int8_metadata  (s, pb, "pgap",    "gapless_playback",1);
2404     mov_write_int8_metadata  (s, pb, "cpil",    "compilation", 1);
2405     mov_write_trkn_tag(pb, mov, s, 0); // track number
2406     mov_write_trkn_tag(pb, mov, s, 1); // disc number
2407     mov_write_tmpo_tag(pb, s);
2408     return update_size(pb, pos);
2409 }
2410
2411 /* iTunes meta data tag */
2412 static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
2413                               AVFormatContext *s)
2414 {
2415     int size = 0;
2416     int64_t pos = avio_tell(pb);
2417     avio_wb32(pb, 0); /* size */
2418     ffio_wfourcc(pb, "meta");
2419     avio_wb32(pb, 0);
2420     mov_write_itunes_hdlr_tag(pb, mov, s);
2421     mov_write_ilst_tag(pb, mov, s);
2422     size = update_size(pb, pos);
2423     return size;
2424 }
2425
2426 static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
2427                                       const char *name, const char *key)
2428 {
2429     int len;
2430     AVDictionaryEntry *t;
2431
2432     if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
2433         return 0;
2434
2435     len = strlen(t->value);
2436     if (len > 0) {
2437         int size = len + 8;
2438         avio_wb32(pb, size);
2439         ffio_wfourcc(pb, name);
2440         avio_write(pb, t->value, len);
2441         return size;
2442     }
2443     return 0;
2444 }
2445
2446 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
2447 {
2448     int val;
2449     while (*b) {
2450         GET_UTF8(val, *b++, return -1;)
2451         avio_wb16(pb, val);
2452     }
2453     avio_wb16(pb, 0x00);
2454     return 0;
2455 }
2456
2457 static uint16_t language_code(const char *str)
2458 {
2459     return (((str[0] - 0x60) & 0x1F) << 10) +
2460            (((str[1] - 0x60) & 0x1F) <<  5) +
2461            (( str[2] - 0x60) & 0x1F);
2462 }
2463
2464 static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
2465                                   const char *tag, const char *str)
2466 {
2467     int64_t pos = avio_tell(pb);
2468     AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
2469     if (!t || !utf8len(t->value))
2470         return 0;
2471     avio_wb32(pb, 0);   /* size */
2472     ffio_wfourcc(pb, tag); /* type */
2473     avio_wb32(pb, 0);   /* version + flags */
2474     if (!strcmp(tag, "yrrc"))
2475         avio_wb16(pb, atoi(t->value));
2476     else {
2477         avio_wb16(pb, language_code("eng")); /* language */
2478         avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
2479         if (!strcmp(tag, "albm") &&
2480             (t = av_dict_get(s->metadata, "track", NULL, 0)))
2481             avio_w8(pb, atoi(t->value));
2482     }
2483     return update_size(pb, pos);
2484 }
2485
2486 static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
2487 {
2488     int64_t pos = avio_tell(pb);
2489     int i, nb_chapters = FFMIN(s->nb_chapters, 255);
2490
2491     avio_wb32(pb, 0);            // size
2492     ffio_wfourcc(pb, "chpl");
2493     avio_wb32(pb, 0x01000000);   // version + flags
2494     avio_wb32(pb, 0);            // unknown
2495     avio_w8(pb, nb_chapters);
2496
2497     for (i = 0; i < nb_chapters; i++) {
2498         AVChapter *c = s->chapters[i];
2499         AVDictionaryEntry *t;
2500         avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
2501
2502         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
2503             int len = FFMIN(strlen(t->value), 255);
2504             avio_w8(pb, len);
2505             avio_write(pb, t->value, len);
2506         } else
2507             avio_w8(pb, 0);
2508     }
2509     return update_size(pb, pos);
2510 }
2511
2512 static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
2513                               AVFormatContext *s)
2514 {
2515     AVIOContext *pb_buf;
2516     int ret, size;
2517     uint8_t *buf;
2518
2519     ret = avio_open_dyn_buf(&pb_buf);
2520     if (ret < 0)
2521         return ret;
2522
2523     if (mov->mode & MODE_3GP) {
2524         mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
2525         mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
2526         mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
2527         mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
2528         mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
2529         mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
2530         mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
2531         mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
2532     } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
2533         mov_write_string_metadata(s, pb_buf, "\251ART", "artist",      0);
2534         mov_write_string_metadata(s, pb_buf, "\251nam", "title",       0);
2535         mov_write_string_metadata(s, pb_buf, "\251aut", "author",      0);
2536         mov_write_string_metadata(s, pb_buf, "\251alb", "album",       0);
2537         mov_write_string_metadata(s, pb_buf, "\251day", "date",        0);
2538         mov_write_string_metadata(s, pb_buf, "\251swr", "encoder",     0);
2539         // currently ignored by mov.c
2540         mov_write_string_metadata(s, pb_buf, "\251des", "comment",     0);
2541         // add support for libquicktime, this atom is also actually read by mov.c
2542         mov_write_string_metadata(s, pb_buf, "\251cmt", "comment",     0);
2543         mov_write_string_metadata(s, pb_buf, "\251gen", "genre",       0);
2544         mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright",   0);
2545         mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
2546     } else {
2547         /* iTunes meta data */
2548         mov_write_meta_tag(pb_buf, mov, s);
2549     }
2550
2551     if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
2552         mov_write_chpl_tag(pb_buf, s);
2553
2554     if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
2555         avio_wb32(pb, size + 8);
2556         ffio_wfourcc(pb, "udta");
2557         avio_write(pb, buf, size);
2558     }
2559     av_free(buf);
2560
2561     return 0;
2562 }
2563
2564 static void mov_write_psp_udta_tag(AVIOContext *pb,
2565                                    const char *str, const char *lang, int type)
2566 {
2567     int len = utf8len(str) + 1;
2568     if (len <= 0)
2569         return;
2570     avio_wb16(pb, len * 2 + 10);        /* size */
2571     avio_wb32(pb, type);                /* type */
2572     avio_wb16(pb, language_code(lang)); /* language */
2573     avio_wb16(pb, 0x01);                /* ? */
2574     ascii_to_wc(pb, str);
2575 }
2576
2577 static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
2578 {
2579     MOVMuxContext *mov = s->priv_data;
2580     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
2581     int64_t pos, pos2;
2582
2583     if (title) {
2584         pos = avio_tell(pb);
2585         avio_wb32(pb, 0); /* size placeholder*/
2586         ffio_wfourcc(pb, "uuid");
2587         ffio_wfourcc(pb, "USMT");
2588         avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
2589         avio_wb32(pb, 0xbb88695c);
2590         avio_wb32(pb, 0xfac9c740);
2591
2592         pos2 = avio_tell(pb);
2593         avio_wb32(pb, 0); /* size placeholder*/
2594         ffio_wfourcc(pb, "MTDT");
2595         avio_wb16(pb, 4);
2596
2597         // ?
2598         avio_wb16(pb, 0x0C);                 /* size */
2599         avio_wb32(pb, 0x0B);                 /* type */
2600         avio_wb16(pb, language_code("und")); /* language */
2601         avio_wb16(pb, 0x0);                  /* ? */
2602         avio_wb16(pb, 0x021C);               /* data */
2603
2604         if (!mov->exact)
2605             mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT,      "eng", 0x04);
2606         mov_write_psp_udta_tag(pb, title->value,          "eng", 0x01);
2607         mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
2608
2609         update_size(pb, pos2);
2610         return update_size(pb, pos);
2611     }
2612
2613     return 0;
2614 }
2615
2616 static void build_chunks(MOVTrack *trk)
2617 {
2618     int i;
2619     MOVIentry *chunk = &trk->cluster[0];
2620     uint64_t chunkSize = chunk->size;
2621     chunk->chunkNum = 1;
2622     if (trk->chunkCount)
2623         return;
2624     trk->chunkCount = 1;
2625     for (i = 1; i<trk->entry; i++){
2626         if (chunk->pos + chunkSize == trk->cluster[i].pos &&
2627             chunkSize + trk->cluster[i].size < (1<<20)){
2628             chunkSize             += trk->cluster[i].size;
2629             chunk->samples_in_chunk += trk->cluster[i].entries;
2630         } else {
2631             trk->cluster[i].chunkNum = chunk->chunkNum+1;
2632             chunk=&trk->cluster[i];
2633             chunkSize = chunk->size;
2634             trk->chunkCount++;
2635         }
2636     }
2637 }
2638
2639 static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
2640                               AVFormatContext *s)
2641 {
2642     int i;
2643     int64_t pos = avio_tell(pb);
2644     avio_wb32(pb, 0); /* size placeholder*/
2645     ffio_wfourcc(pb, "moov");
2646
2647     for (i = 0; i < mov->nb_streams; i++) {
2648         if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
2649             continue;
2650
2651         mov->tracks[i].time     = mov->time;
2652         mov->tracks[i].track_id = i + 1;
2653
2654         if (mov->tracks[i].entry)
2655             build_chunks(&mov->tracks[i]);
2656     }
2657
2658     if (mov->chapter_track)
2659         for (i = 0; i < s->nb_streams; i++) {
2660             mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
2661             mov->tracks[i].tref_id  = mov->tracks[mov->chapter_track].track_id;
2662         }
2663     for (i = 0; i < mov->nb_streams; i++) {
2664         if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
2665             mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
2666             mov->tracks[i].tref_id =
2667                 mov->tracks[mov->tracks[i].src_track].track_id;
2668         }
2669     }
2670     for (i = 0; i < mov->nb_streams; i++) {
2671         if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
2672             int src_trk = mov->tracks[i].src_track;
2673             mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
2674             mov->tracks[src_trk].tref_id  = mov->tracks[i].track_id;
2675             //src_trk may have a different timescale than the tmcd track
2676             mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
2677                                                        mov->tracks[i].timescale,
2678                                                        mov->tracks[src_trk].timescale);
2679         }
2680     }
2681
2682     mov_write_mvhd_tag(pb, mov);
2683     if (mov->mode != MODE_MOV && !mov->iods_skip)
2684         mov_write_iods_tag(pb, mov);
2685     for (i = 0; i < mov->nb_streams; i++) {
2686         if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
2687             mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
2688         }
2689     }
2690     if (mov->flags & FF_MOV_FLAG_FRAGMENT)
2691         mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
2692
2693     if (mov->mode == MODE_PSP)
2694         mov_write_uuidusmt_tag(pb, s);
2695     else
2696         mov_write_udta_tag(pb, mov, s);
2697
2698     return update_size(pb, pos);
2699 }
2700
2701 static void param_write_int(AVIOContext *pb, const char *name, int value)
2702 {
2703     avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
2704 }
2705
2706 static void param_write_string(AVIOContext *pb, const char *name, const char *value)
2707 {
2708     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
2709 }
2710
2711 static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
2712 {
2713     char buf[150];
2714     len = FFMIN(sizeof(buf) / 2 - 1, len);
2715     ff_data_to_hex(buf, value, len, 0);
2716     buf[2 * len] = '\0';
2717     avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
2718 }
2719
2720 static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
2721 {
2722     int64_t pos = avio_tell(pb);
2723     int i;
2724     static const uint8_t uuid[] = {
2725         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
2726         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
2727     };
2728
2729     avio_wb32(pb, 0);
2730     ffio_wfourcc(pb, "uuid");
2731     avio_write(pb, uuid, sizeof(uuid));
2732     avio_wb32(pb, 0);
2733
2734     avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
2735     avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
2736     avio_printf(pb, "<head>\n");
2737     if (!mov->exact)
2738         avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
2739                     LIBAVFORMAT_IDENT);
2740     avio_printf(pb, "</head>\n");
2741     avio_printf(pb, "<body>\n");
2742     avio_printf(pb, "<switch>\n");
2743     for (i = 0; i < mov->nb_streams; i++) {
2744         MOVTrack *track = &mov->tracks[i];
2745         const char *type;
2746         /* track->track_id is initialized in write_moov, and thus isn't known
2747          * here yet */
2748         int track_id = i + 1;
2749
2750         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2751             type = "video";
2752         } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
2753             type = "audio";
2754         } else {
2755             continue;
2756         }
2757         avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
2758                                                        track->enc->bit_rate);
2759         param_write_int(pb, "systemBitrate", track->enc->bit_rate);
2760         param_write_int(pb, "trackID", track_id);
2761         if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2762             if (track->enc->codec_id == AV_CODEC_ID_H264) {
2763                 uint8_t *ptr;
2764                 int size = track->enc->extradata_size;
2765                 if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
2766                                                    &size)) {
2767                     param_write_hex(pb, "CodecPrivateData",
2768                                     ptr ? ptr : track->enc->extradata,
2769                                     size);
2770                     av_free(ptr);
2771                 }
2772                 param_write_string(pb, "FourCC", "H264");
2773             } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
2774                 param_write_string(pb, "FourCC", "WVC1");
2775                 param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2776                                 track->enc->extradata_size);
2777             }
2778             param_write_int(pb, "MaxWidth", track->enc->width);
2779             param_write_int(pb, "MaxHeight", track->enc->height);
2780             param_write_int(pb, "DisplayWidth", track->enc->width);
2781             param_write_int(pb, "DisplayHeight", track->enc->height);
2782         } else {
2783             if (track->enc->codec_id == AV_CODEC_ID_AAC) {
2784                 param_write_string(pb, "FourCC", "AACL");
2785             } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
2786                 param_write_string(pb, "FourCC", "WMAP");
2787             }
2788             param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
2789                             track->enc->extradata_size);
2790             param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
2791                                                              track->enc->codec_id));
2792             param_write_int(pb, "Channels", track->enc->channels);
2793             param_write_int(pb, "SamplingRate", track->enc->sample_rate);
2794             param_write_int(pb, "BitsPerSample", 16);
2795             param_write_int(pb, "PacketSize", track->enc->block_align ?
2796                                               track->enc->block_align : 4);
2797         }
2798         avio_printf(pb, "</%s>\n", type);
2799     }
2800     avio_printf(pb, "</switch>\n");
2801     avio_printf(pb, "</body>\n");
2802     avio_printf(pb, "</smil>\n");
2803
2804     return update_size(pb, pos);
2805 }
2806
2807 static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
2808 {
2809     avio_wb32(pb, 16);
2810     ffio_wfourcc(pb, "mfhd");
2811     avio_wb32(pb, 0);
2812     avio_wb32(pb, mov->fragments);
2813     return 0;
2814 }
2815
2816 static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
2817                               MOVTrack *track, int64_t moof_offset)
2818 {
2819     int64_t pos = avio_tell(pb);
2820     uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2821                      MOV_TFHD_BASE_DATA_OFFSET;
2822     if (!track->entry) {
2823         flags |= MOV_TFHD_DURATION_IS_EMPTY;
2824     } else {
2825         flags |= MOV_TFHD_DEFAULT_FLAGS;
2826     }
2827     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
2828         flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
2829
2830     /* Don't set a default sample size, the silverlight player refuses
2831      * to play files with that set. Don't set a default sample duration,
2832      * WMP freaks out if it is set. Don't set a base data offset, PIFF
2833      * file format says it MUST NOT be set. */
2834     if (track->mode == MODE_ISM)
2835         flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
2836                    MOV_TFHD_BASE_DATA_OFFSET);
2837
2838     avio_wb32(pb, 0); /* size placeholder */
2839     ffio_wfourcc(pb, "tfhd");
2840     avio_w8(pb, 0); /* version */
2841     avio_wb24(pb, flags);
2842
2843     avio_wb32(pb, track->track_id); /* track-id */
2844     if (flags & MOV_TFHD_BASE_DATA_OFFSET)
2845         avio_wb64(pb, moof_offset);
2846     if (flags & MOV_TFHD_DEFAULT_DURATION) {
2847         track->default_duration = get_cluster_duration(track, 0);
2848         avio_wb32(pb, track->default_duration);
2849     }
2850     if (flags & MOV_TFHD_DEFAULT_SIZE) {
2851         track->default_size = track->entry ? track->cluster[0].size : 1;
2852         avio_wb32(pb, track->default_size);
2853     } else
2854         track->default_size = -1;
2855
2856     if (flags & MOV_TFHD_DEFAULT_FLAGS) {
2857         track->default_sample_flags =
2858             track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
2859             (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
2860             MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
2861         avio_wb32(pb, track->default_sample_flags);
2862     }
2863
2864     return update_size(pb, pos);
2865 }
2866
2867 static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
2868 {
2869     return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
2870            (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
2871 }
2872
2873 static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
2874                               MOVTrack *track, int moof_size)
2875 {
2876     int64_t pos = avio_tell(pb);
2877     uint32_t flags = MOV_TRUN_DATA_OFFSET;
2878     int i;
2879
2880     for (i = 0; i < track->entry; i++) {
2881         if (get_cluster_duration(track, i) != track->default_duration)
2882             flags |= MOV_TRUN_SAMPLE_DURATION;
2883         if (track->cluster[i].size != track->default_size)
2884             flags |= MOV_TRUN_SAMPLE_SIZE;
2885         if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
2886             flags |= MOV_TRUN_SAMPLE_FLAGS;
2887     }
2888     if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
2889         flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
2890     if (track->flags & MOV_TRACK_CTTS)
2891         flags |= MOV_TRUN_SAMPLE_CTS;
2892
2893     avio_wb32(pb, 0); /* size placeholder */
2894     ffio_wfourcc(pb, "trun");
2895     avio_w8(pb, 0); /* version */
2896     avio_wb24(pb, flags);
2897
2898     avio_wb32(pb, track->entry); /* sample count */
2899     if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
2900         !(mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) &&
2901         track->track_id != 1)
2902         avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
2903     else
2904         avio_wb32(pb, moof_size + 8 + track->data_offset +
2905                       track->cluster[0].pos); /* data offset */
2906     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
2907         avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
2908
2909     for (i = 0; i < track->entry; i++) {
2910         if (flags & MOV_TRUN_SAMPLE_DURATION)
2911             avio_wb32(pb, get_cluster_duration(track, i));
2912         if (flags & MOV_TRUN_SAMPLE_SIZE)
2913             avio_wb32(pb, track->cluster[i].size);
2914         if (flags & MOV_TRUN_SAMPLE_FLAGS)
2915             avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
2916         if (flags & MOV_TRUN_SAMPLE_CTS)
2917             avio_wb32(pb, track->cluster[i].cts);
2918     }
2919
2920     return update_size(pb, pos);
2921 }
2922
2923 static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
2924 {
2925     int64_t pos = avio_tell(pb);
2926     static const uint8_t uuid[] = {
2927         0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
2928         0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
2929     };
2930
2931     avio_wb32(pb, 0); /* size placeholder */
2932     ffio_wfourcc(pb, "uuid");
2933     avio_write(pb, uuid, sizeof(uuid));
2934     avio_w8(pb, 1);
2935     avio_wb24(pb, 0);
2936     avio_wb64(pb, track->frag_start);
2937     avio_wb64(pb, track->start_dts + track->track_duration -
2938                   track->cluster[0].dts);
2939
2940     return update_size(pb, pos);
2941 }
2942
2943 static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
2944                               MOVTrack *track, int entry)
2945 {
2946     int n = track->nb_frag_info - 1 - entry, i;
2947     int size = 8 + 16 + 4 + 1 + 16*n;
2948     static const uint8_t uuid[] = {
2949         0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
2950         0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
2951     };
2952
2953     if (entry < 0)
2954         return 0;
2955
2956     avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
2957     avio_wb32(pb, size);
2958     ffio_wfourcc(pb, "uuid");
2959     avio_write(pb, uuid, sizeof(uuid));
2960     avio_w8(pb, 1);
2961     avio_wb24(pb, 0);
2962     avio_w8(pb, n);
2963     for (i = 0; i < n; i++) {
2964         int index = entry + 1 + i;
2965         avio_wb64(pb, track->frag_info[index].time);
2966         avio_wb64(pb, track->frag_info[index].duration);
2967     }
2968     if (n < mov->ism_lookahead) {
2969         int free_size = 16 * (mov->ism_lookahead - n);
2970         avio_wb32(pb, free_size);
2971         ffio_wfourcc(pb, "free");
2972         ffio_fill(pb, 0, free_size - 8);
2973     }
2974
2975     return 0;
2976 }
2977
2978 static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
2979                                MOVTrack *track)
2980 {
2981     int64_t pos = avio_tell(pb);
2982     int i;
2983     for (i = 0; i < mov->ism_lookahead; i++) {
2984         /* Update the tfrf tag for the last ism_lookahead fragments,
2985          * nb_frag_info - 1 is the next fragment to be written. */
2986         mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
2987     }
2988     avio_seek(pb, pos, SEEK_SET);
2989     return 0;
2990 }
2991
2992 static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
2993                               MOVTrack *track, int64_t moof_offset,
2994                               int moof_size)
2995 {
2996     int64_t pos = avio_tell(pb);
2997     avio_wb32(pb, 0); /* size placeholder */
2998     ffio_wfourcc(pb, "traf");
2999
3000     mov_write_tfhd_tag(pb, mov, track, moof_offset);
3001     mov_write_trun_tag(pb, mov, track, moof_size);
3002     if (mov->mode == MODE_ISM) {
3003         mov_write_tfxd_tag(pb, track);
3004
3005         if (mov->ism_lookahead) {
3006             int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
3007
3008             track->tfrf_offset = avio_tell(pb);
3009             avio_wb32(pb, 8 + size);
3010             ffio_wfourcc(pb, "free");
3011             for (i = 0; i < size; i++)
3012                 avio_w8(pb, 0);
3013         }
3014     }
3015
3016     return update_size(pb, pos);
3017 }
3018
3019 static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
3020                                        int tracks, int moof_size)
3021 {
3022     int64_t pos = avio_tell(pb);
3023     int i;
3024
3025     avio_wb32(pb, 0); /* size placeholder */
3026     ffio_wfourcc(pb, "moof");
3027
3028     mov_write_mfhd_tag(pb, mov);
3029     for (i = 0; i < mov->nb_streams; i++) {
3030         MOVTrack *track = &mov->tracks[i];
3031         if (tracks >= 0 && i != tracks)
3032             continue;
3033         if (!track->entry)
3034             continue;
3035         mov_write_traf_tag(pb, mov, track, pos, moof_size);
3036     }
3037
3038     return update_size(pb, pos);
3039 }
3040
3041 static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
3042 {
3043     AVIOContext *avio_buf;
3044     int ret, moof_size;
3045
3046     if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
3047         return ret;
3048     mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
3049     moof_size = ffio_close_null_buf(avio_buf);
3050     return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
3051 }
3052
3053 static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
3054 {
3055     int64_t pos = avio_tell(pb);
3056     int i;
3057
3058     avio_wb32(pb, 0); /* size placeholder */
3059     ffio_wfourcc(pb, "tfra");
3060     avio_w8(pb, 1); /* version */
3061     avio_wb24(pb, 0);
3062
3063     avio_wb32(pb, track->track_id);
3064     avio_wb32(pb, 0); /* length of traf/trun/sample num */
3065     avio_wb32(pb, track->nb_frag_info);
3066     for (i = 0; i < track->nb_frag_info; i++) {
3067         avio_wb64(pb, track->frag_info[i].time);
3068         avio_wb64(pb, track->frag_info[i].offset);
3069         avio_w8(pb, 1); /* traf number */
3070         avio_w8(pb, 1); /* trun number */
3071         avio_w8(pb, 1); /* sample number */
3072     }
3073
3074     return update_size(pb, pos);
3075 }
3076
3077 static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
3078 {
3079     int64_t pos = avio_tell(pb);
3080     int i;
3081
3082     avio_wb32(pb, 0); /* size placeholder */
3083     ffio_wfourcc(pb, "mfra");
3084     /* An empty mfra atom is enough to indicate to the publishing point that
3085      * the stream has ended. */
3086     if (mov->flags & FF_MOV_FLAG_ISML)
3087         return update_size(pb, pos);
3088
3089     for (i = 0; i < mov->nb_streams; i++) {
3090         MOVTrack *track = &mov->tracks[i];
3091         if (track->nb_frag_info)
3092             mov_write_tfra_tag(pb, track);
3093     }
3094
3095     avio_wb32(pb, 16);
3096     ffio_wfourcc(pb, "mfro");
3097     avio_wb32(pb, 0); /* version + flags */
3098     avio_wb32(pb, avio_tell(pb) + 4 - pos);
3099
3100     return update_size(pb, pos);
3101 }
3102
3103 static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
3104 {
3105     avio_wb32(pb, 8);    // placeholder for extended size field (64 bit)
3106     ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
3107
3108     mov->mdat_pos = avio_tell(pb);
3109     avio_wb32(pb, 0); /* size placeholder*/
3110     ffio_wfourcc(pb, "mdat");
3111     return 0;
3112 }
3113
3114 /* TODO: This needs to be more general */
3115 static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
3116 {
3117     MOVMuxContext *mov = s->priv_data;
3118     int64_t pos = avio_tell(pb);
3119     int has_h264 = 0, has_video = 0;
3120     int minor = 0x200;
3121     int i;
3122
3123     for (i = 0; i < s->nb_streams; i++) {
3124         AVStream *st = s->streams[i];
3125         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3126             has_video = 1;
3127         if (st->codec->codec_id == AV_CODEC_ID_H264)
3128             has_h264 = 1;
3129     }
3130
3131     avio_wb32(pb, 0); /* size */
3132     ffio_wfourcc(pb, "ftyp");
3133
3134     if (mov->major_brand && strlen(mov->major_brand) >= 4)
3135         ffio_wfourcc(pb, mov->major_brand);
3136     else if (mov->mode == MODE_3GP) {
3137         ffio_wfourcc(pb, has_h264 ? "3gp6"  : "3gp4");
3138         minor =     has_h264 ?   0x100 :   0x200;
3139     } else if (mov->mode & MODE_3G2) {
3140         ffio_wfourcc(pb, has_h264 ? "3g2b"  : "3g2a");
3141         minor =     has_h264 ? 0x20000 : 0x10000;
3142     } else if (mov->mode == MODE_PSP)
3143         ffio_wfourcc(pb, "MSNV");
3144     else if (mov->mode == MODE_MP4)
3145         ffio_wfourcc(pb, "isom");
3146     else if (mov->mode == MODE_IPOD)
3147         ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
3148     else if (mov->mode == MODE_ISM)
3149         ffio_wfourcc(pb, "isml");
3150     else if (mov->mode == MODE_F4V)
3151         ffio_wfourcc(pb, "f4v ");
3152     else
3153         ffio_wfourcc(pb, "qt  ");
3154
3155     avio_wb32(pb, minor);
3156
3157     if (mov->mode == MODE_MOV)
3158         ffio_wfourcc(pb, "qt  ");
3159     else if (mov->mode == MODE_ISM) {
3160         ffio_wfourcc(pb, "piff");
3161         ffio_wfourcc(pb, "iso2");
3162     } else {
3163         ffio_wfourcc(pb, "isom");
3164         ffio_wfourcc(pb, "iso2");
3165         if (has_h264)
3166             ffio_wfourcc(pb, "avc1");
3167     }
3168
3169     if (mov->mode == MODE_3GP)
3170         ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
3171     else if (mov->mode & MODE_3G2)
3172         ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
3173     else if (mov->mode == MODE_PSP)
3174         ffio_wfourcc(pb, "MSNV");
3175     else if (mov->mode == MODE_MP4)
3176         ffio_wfourcc(pb, "mp41");
3177     return update_size(pb, pos);
3178 }
3179
3180 static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
3181 {
3182     AVStream       *video_st    = s->streams[0];
3183     AVCodecContext *video_codec = s->streams[0]->codec;
3184     AVCodecContext *audio_codec = s->streams[1]->codec;
3185     int audio_rate = audio_codec->sample_rate;
3186     // TODO: should be avg_frame_rate
3187     int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);
3188     int audio_kbitrate = audio_codec->bit_rate / 1000;
3189     int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
3190
3191     avio_wb32(pb, 0x94); /* size */
3192     ffio_wfourcc(pb, "uuid");
3193     ffio_wfourcc(pb, "PROF");
3194
3195     avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
3196     avio_wb32(pb, 0xbb88695c);
3197     avio_wb32(pb, 0xfac9c740);
3198
3199     avio_wb32(pb, 0x0);  /* ? */
3200     avio_wb32(pb, 0x3);  /* 3 sections ? */
3201
3202     avio_wb32(pb, 0x14); /* size */
3203     ffio_wfourcc(pb, "FPRF");
3204     avio_wb32(pb, 0x0);  /* ? */
3205     avio_wb32(pb, 0x0);  /* ? */
3206     avio_wb32(pb, 0x0);  /* ? */
3207
3208     avio_wb32(pb, 0x2c);  /* size */
3209     ffio_wfourcc(pb, "APRF"); /* audio */
3210     avio_wb32(pb, 0x0);
3211     avio_wb32(pb, 0x2);   /* TrackID */
3212     ffio_wfourcc(pb, "mp4a");
3213     avio_wb32(pb, 0x20f);
3214     avio_wb32(pb, 0x0);
3215     avio_wb32(pb, audio_kbitrate);
3216     avio_wb32(pb, audio_kbitrate);
3217     avio_wb32(pb, audio_rate);
3218     avio_wb32(pb, audio_codec->channels);
3219
3220     avio_wb32(pb, 0x34);  /* size */
3221     ffio_wfourcc(pb, "VPRF");   /* video */
3222     avio_wb32(pb, 0x0);
3223     avio_wb32(pb, 0x1);    /* TrackID */
3224     if (video_codec->codec_id == AV_CODEC_ID_H264) {
3225         ffio_wfourcc(pb, "avc1");
3226         avio_wb16(pb, 0x014D);
3227         avio_wb16(pb, 0x0015);
3228     } else {
3229         ffio_wfourcc(pb, "mp4v");
3230         avio_wb16(pb, 0x0000);
3231         avio_wb16(pb, 0x0103);
3232     }
3233     avio_wb32(pb, 0x0);
3234     avio_wb32(pb, video_kbitrate);
3235     avio_wb32(pb, video_kbitrate);
3236     avio_wb32(pb, frame_rate);
3237     avio_wb32(pb, frame_rate);
3238     avio_wb16(pb, video_codec->width);
3239     avio_wb16(pb, video_codec->height);
3240     avio_wb32(pb, 0x010001); /* ? */
3241 }
3242
3243 static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
3244 {
3245     uint32_t c = -1;
3246     int i, closed_gop = 0;
3247
3248     for (i = 0; i < pkt->size - 4; i++) {
3249         c = (c << 8) + pkt->data[i];
3250         if (c == 0x1b8) { // gop
3251             closed_gop = pkt->data[i + 4] >> 6 & 0x01;
3252         } else if (c == 0x100) { // pic
3253             int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
3254             if (!temp_ref || closed_gop) // I picture is not reordered
3255                 *flags = MOV_SYNC_SAMPLE;
3256             else
3257                 *flags = MOV_PARTIAL_SYNC_SAMPLE;
3258             break;
3259         }
3260     }
3261     return 0;
3262 }
3263
3264 static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
3265 {
3266     const uint8_t *start, *next, *end = pkt->data + pkt->size;
3267     int seq = 0, entry = 0;
3268     int key = pkt->flags & AV_PKT_FLAG_KEY;
3269     start = find_next_marker(pkt->data, end);
3270     for (next = start; next < end; start = next) {
3271         next = find_next_marker(start + 4, end);
3272         switch (AV_RB32(start)) {
3273         case VC1_CODE_SEQHDR:
3274             seq = 1;
3275             break;
3276         case VC1_CODE_ENTRYPOINT:
3277             entry = 1;
3278             break;
3279         case VC1_CODE_SLICE:
3280             trk->vc1_info.slices = 1;
3281             break;
3282         }
3283     }
3284     if (!trk->entry && !fragment) {
3285         /* First packet in first fragment */
3286         trk->vc1_info.first_packet_seq   = seq;
3287         trk->vc1_info.first_packet_entry = entry;
3288     } else if ((seq && !trk->vc1_info.packet_seq) ||
3289                (entry && !trk->vc1_info.packet_entry)) {
3290         int i;
3291         for (i = 0; i < trk->entry; i++)
3292             trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
3293         trk->has_keyframes = 0;
3294         if (seq)
3295             trk->vc1_info.packet_seq = 1;
3296         if (entry)
3297             trk->vc1_info.packet_entry = 1;
3298         if (!fragment) {
3299             /* First fragment */
3300             if ((!seq   || trk->vc1_info.first_packet_seq) &&
3301                 (!entry || trk->vc1_info.first_packet_entry)) {
3302                 /* First packet had the same headers as this one, readd the
3303                  * sync sample flag. */
3304                 trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
3305                 trk->has_keyframes = 1;
3306             }
3307         }
3308     }
3309     if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
3310         key = seq && entry;
3311     else if (trk->vc1_info.packet_seq)
3312         key = seq;
3313     else if (trk->vc1_info.packet_entry)
3314         key = entry;
3315     if (key) {
3316         trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
3317         trk->has_keyframes++;
3318     }
3319 }
3320
3321 static int mov_flush_fragment(AVFormatContext *s)
3322 {
3323     MOVMuxContext *mov = s->priv_data;
3324     int i, first_track = -1;
3325     int64_t mdat_size = 0;
3326
3327     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
3328         return 0;
3329
3330     if (!(mov->flags & FF_MOV_FLAG_EMPTY_MOOV) && mov->fragments == 0) {
3331         int64_t pos = avio_tell(s->pb);
3332         uint8_t *buf;
3333         int buf_size, moov_size;
3334
3335         for (i = 0; i < mov->nb_streams; i++)
3336             if (!mov->tracks[i].entry)
3337                 break;
3338         /* Don't write the initial moov unless all tracks have data */
3339         if (i < mov->nb_streams)
3340             return 0;
3341
3342         moov_size = get_moov_size(s);
3343         for (i = 0; i < mov->nb_streams; i++)
3344             mov->tracks[i].data_offset = pos + moov_size + 8;
3345
3346         mov_write_moov_tag(s->pb, mov, s);
3347
3348         buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
3349         mov->mdat_buf = NULL;
3350         avio_wb32(s->pb, buf_size + 8);
3351         ffio_wfourcc(s->pb, "mdat");
3352         avio_write(s->pb, buf, buf_size);
3353         av_free(buf);
3354
3355         mov->fragments++;
3356         mov->mdat_size = 0;
3357         for (i = 0; i < mov->nb_streams; i++) {
3358             if (mov->tracks[i].entry)
3359                 mov->tracks[i].frag_start += mov->tracks[i].start_dts +
3360                                              mov->tracks[i].track_duration -
3361                                              mov->tracks[i].cluster[0].dts;
3362             mov->tracks[i].entry = 0;
3363         }
3364         avio_flush(s->pb);
3365         return 0;
3366     }
3367
3368     for (i = 0; i < mov->nb_streams; i++) {
3369         MOVTrack *track = &mov->tracks[i];
3370         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
3371             track->data_offset = 0;
3372         else
3373             track->data_offset = mdat_size;
3374         if (!track->mdat_buf)
3375             continue;
3376         mdat_size += avio_tell(track->mdat_buf);
3377         if (first_track < 0)
3378             first_track = i;
3379     }
3380
3381     if (!mdat_size)
3382         return 0;
3383
3384     for (i = 0; i < mov->nb_streams; i++) {
3385         MOVTrack *track = &mov->tracks[i];
3386         int buf_size, write_moof = 1, moof_tracks = -1;
3387         uint8_t *buf;
3388         int64_t duration = 0;
3389
3390         if (track->entry)
3391             duration = track->start_dts + track->track_duration -
3392                        track->cluster[0].dts;
3393         if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
3394             if (!track->mdat_buf)
3395                 continue;
3396             mdat_size = avio_tell(track->mdat_buf);
3397             moof_tracks = i;
3398         } else {
3399             write_moof = i == first_track;
3400         }
3401
3402         if (write_moof) {
3403             MOVFragmentInfo *info;
3404             avio_flush(s->pb);
3405             track->nb_frag_info++;
3406             if (track->nb_frag_info >= track->frag_info_capacity) {
3407                 unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
3408                 if (av_reallocp_array(&track->frag_info,
3409                                       new_capacity,
3410                                       sizeof(*track->frag_info)))
3411                     return AVERROR(ENOMEM);
3412                 track->frag_info_capacity = new_capacity;
3413             }
3414             info = &track->frag_info[track->nb_frag_info - 1];
3415             info->offset   = avio_tell(s->pb);
3416             info->time     = mov->tracks[i].frag_start;
3417             info->duration = duration;
3418             mov_write_tfrf_tags(s->pb, mov, track);
3419
3420             mov_write_moof_tag(s->pb, mov, moof_tracks);
3421             info->tfrf_offset = track->tfrf_offset;
3422             mov->fragments++;
3423
3424             avio_wb32(s->pb, mdat_size + 8);
3425             ffio_wfourcc(s->pb, "mdat");
3426         }
3427
3428         if (track->entry)
3429             track->frag_start += duration;
3430         track->entry = 0;
3431         if (!track->mdat_buf)
3432             continue;
3433         buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
3434         track->mdat_buf = NULL;
3435
3436         avio_write(s->pb, buf, buf_size);
3437         av_free(buf);
3438     }
3439
3440     mov->mdat_size = 0;
3441
3442     avio_flush(s->pb);
3443     return 0;
3444 }
3445
3446 int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3447 {
3448     MOVMuxContext *mov = s->priv_data;
3449     AVIOContext *pb = s->pb;
3450     MOVTrack *trk = &mov->tracks[pkt->stream_index];
3451     AVCodecContext *enc = trk->enc;
3452     unsigned int samples_in_chunk = 0;
3453     int size = pkt->size;
3454     uint8_t *reformatted_data = NULL;
3455
3456     if (trk->entry) {
3457         int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
3458         if (duration < 0 || duration > INT_MAX) {
3459             av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
3460                 duration, pkt->dts
3461             );
3462
3463             pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
3464             pkt->pts = AV_NOPTS_VALUE;
3465         }
3466         if (pkt->duration < 0) {
3467             av_log(s, AV_LOG_ERROR, "Application provided duration: %d is invalid\n", pkt->duration);
3468             return AVERROR(EINVAL);
3469         }
3470     }
3471     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
3472         int ret;
3473         if (mov->fragments > 0) {
3474             if (!trk->mdat_buf) {
3475                 if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
3476                     return ret;
3477             }
3478             pb = trk->mdat_buf;
3479         } else {
3480             if (!mov->mdat_buf) {
3481                 if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
3482                     return ret;
3483             }
3484             pb = mov->mdat_buf;
3485         }
3486     }
3487
3488     if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
3489         /* We must find out how many AMR blocks there are in one packet */
3490         static uint16_t packed_size[16] =
3491             {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
3492         int len = 0;
3493
3494         while (len < size && samples_in_chunk < 100) {
3495             len += packed_size[(pkt->data[len] >> 3) & 0x0F];
3496             samples_in_chunk++;
3497         }
3498         if (samples_in_chunk > 1) {
3499             av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
3500             return -1;
3501         }
3502     } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
3503                enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
3504         samples_in_chunk = enc->frame_size;
3505     } else if (trk->sample_size)
3506         samples_in_chunk = size / trk->sample_size;
3507     else
3508         samples_in_chunk = 1;
3509
3510     /* copy extradata if it exists */
3511     if (trk->vos_len == 0 && enc->extradata_size > 0) {
3512         trk->vos_len  = enc->extradata_size;
3513         trk->vos_data = av_malloc(trk->vos_len);
3514         memcpy(trk->vos_data, enc->extradata, trk->vos_len);
3515     }
3516
3517     if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
3518         (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
3519         if (!s->streams[pkt->stream_index]->nb_frames) {
3520             av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
3521                    "use the audio bitstream filter 'aac_adtstoasc' to fix it "
3522                    "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
3523             return -1;
3524         }
3525         av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
3526     }
3527     if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1) {
3528         /* from x264 or from bytestream h264 */
3529         /* nal reformating needed */
3530         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
3531             ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
3532                                        &size);
3533             avio_write(pb, reformatted_data, size);
3534         } else {
3535             size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
3536         }
3537     } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
3538                (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
3539         /* extradata is Annex B, assume the bitstream is too and convert it */
3540         if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
3541             ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
3542             avio_write(pb, reformatted_data, size);
3543         } else {
3544             size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
3545         }
3546     } else {
3547         avio_write(pb, pkt->data, size);
3548     }
3549
3550     if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
3551          enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
3552         /* copy frame to create needed atoms */
3553         trk->vos_len  = size;
3554         trk->vos_data = av_malloc(size);
3555         if (!trk->vos_data)
3556             return AVERROR(ENOMEM);
3557         memcpy(trk->vos_data, pkt->data, size);
3558     }
3559
3560     if (trk->entry >= trk->cluster_capacity) {
3561         unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
3562         if (av_reallocp_array(&trk->cluster, new_capacity,
3563                               sizeof(*trk->cluster)))
3564             return AVERROR(ENOMEM);
3565         trk->cluster_capacity = new_capacity;
3566     }
3567
3568     trk->cluster[trk->entry].pos              = avio_tell(pb) - size;
3569     trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
3570     trk->cluster[trk->entry].chunkNum         = 0;
3571     trk->cluster[trk->entry].size             = size;
3572     trk->cluster[trk->entry].entries          = samples_in_chunk;
3573     trk->cluster[trk->entry].dts              = pkt->dts;
3574     if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
3575         /* First packet of a new fragment. We already wrote the duration
3576          * of the last packet of the previous fragment based on track_duration,
3577          * which might not exactly match our dts. Therefore adjust the dts
3578          * of this packet to be what the previous packets duration implies. */
3579         trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
3580     }
3581     if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !supports_edts(mov)) {
3582         trk->cluster[trk->entry].dts = trk->start_dts = 0;
3583     }
3584     if (trk->start_dts == AV_NOPTS_VALUE)
3585         trk->start_dts = pkt->dts;
3586     trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
3587     trk->last_sample_is_subtitle_end = 0;
3588
3589     if (pkt->pts == AV_NOPTS_VALUE) {
3590         av_log(s, AV_LOG_WARNING, "pts has no value\n");
3591         pkt->pts = pkt->dts;
3592     }
3593     if (pkt->dts != pkt->pts)
3594         trk->flags |= MOV_TRACK_CTTS;
3595     trk->cluster[trk->entry].cts   = pkt->pts - pkt->dts;
3596     trk->cluster[trk->entry].flags = 0;
3597     if (enc->codec_id == AV_CODEC_ID_VC1) {
3598         mov_parse_vc1_frame(pkt, trk, mov->fragments);
3599     } else if (pkt->flags & AV_PKT_FLAG_KEY) {
3600         if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
3601             trk->entry > 0) { // force sync sample for the first key frame
3602             mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
3603             if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
3604                 trk->flags |= MOV_TRACK_STPS;
3605         } else {
3606             trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
3607         }
3608         if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
3609             trk->has_keyframes++;
3610     }
3611     trk->entry++;
3612     trk->sample_count += samples_in_chunk;
3613     mov->mdat_size    += size;
3614
3615     if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
3616         ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
3617                                  reformatted_data, size);
3618     av_free(reformatted_data);
3619     return 0;
3620 }
3621
3622 static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
3623 {
3624         MOVMuxContext *mov = s->priv_data;
3625         MOVTrack *trk = &mov->tracks[pkt->stream_index];
3626         AVCodecContext *enc = trk->enc;
3627         int64_t frag_duration = 0;
3628         int size = pkt->size;
3629
3630         if (!pkt->size)
3631             return 0;             /* Discard 0 sized packets */
3632
3633         if (trk->entry && pkt->stream_index < s->nb_streams)
3634             frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
3635                                          s->streams[pkt->stream_index]->time_base,
3636                                          AV_TIME_BASE_Q);
3637         if ((mov->max_fragment_duration &&
3638              frag_duration >= mov->max_fragment_duration) ||
3639              (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
3640              (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
3641               enc->codec_type == AVMEDIA_TYPE_VIDEO &&
3642               trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
3643             if (frag_duration >= mov->min_fragment_duration)
3644                 mov_flush_fragment(s);
3645         }
3646
3647         return ff_mov_write_packet(s, pkt);
3648 }
3649
3650 static int mov_write_subtitle_end_packet(AVFormatContext *s,
3651                                          int stream_index,
3652                                          int64_t dts) {
3653     AVPacket end;
3654     uint8_t data[2] = {0};
3655     int ret;
3656
3657     av_init_packet(&end);
3658     end.size = sizeof(data);
3659     end.data = data;
3660     end.pts = dts;
3661     end.dts = dts;
3662     end.duration = 0;
3663     end.stream_index = stream_index;
3664
3665     ret = mov_write_single_packet(s, &end);
3666     av_free_packet(&end);
3667
3668     return ret;
3669 }
3670
3671 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
3672 {
3673     if (!pkt) {
3674         mov_flush_fragment(s);
3675         return 1;
3676     } else {
3677         int i;
3678         MOVMuxContext *mov = s->priv_data;
3679
3680         if (!pkt->size) return 0; /* Discard 0 sized packets */
3681
3682         /*
3683          * Subtitles require special handling.
3684          *
3685          * 1) For full complaince, every track must have a sample at
3686          * dts == 0, which is rarely true for subtitles. So, as soon
3687          * as we see any packet with dts > 0, write an empty subtitle
3688          * at dts == 0 for any subtitle track with no samples in it.
3689          *
3690          * 2) For each subtitle track, check if the current packet's
3691          * dts is past the duration of the last subtitle sample. If
3692          * so, we now need to write an end sample for that subtitle.
3693          *
3694          * This must be done conditionally to allow for subtitles that
3695          * immediately replace each other, in which case an end sample
3696          * is not needed, and is, in fact, actively harmful.
3697          *
3698          * 3) See mov_write_trailer for how the final end sample is
3699          * handled.
3700          */
3701         for (i = 0; i < mov->nb_streams; i++) {
3702             MOVTrack *trk = &mov->tracks[i];
3703             int ret;
3704
3705             if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
3706                 trk->track_duration < pkt->dts &&
3707                 (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
3708                 ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
3709                 if (ret < 0) return ret;
3710                 trk->last_sample_is_subtitle_end = 1;
3711             }
3712         }
3713
3714         return mov_write_single_packet(s, pkt);
3715     }
3716 }
3717
3718 // QuickTime chapters involve an additional text track with the chapter names
3719 // as samples, and a tref pointing from the other tracks to the chapter one.
3720 static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
3721 {
3722     AVIOContext *pb;
3723
3724     MOVMuxContext *mov = s->priv_data;
3725     MOVTrack *track = &mov->tracks[tracknum];
3726     AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
3727     int i, len;
3728
3729     track->mode = mov->mode;
3730     track->tag = MKTAG('t','e','x','t');
3731     track->timescale = MOV_TIMESCALE;
3732     track->enc = avcodec_alloc_context3(NULL);
3733     if (!track->enc)
3734         return AVERROR(ENOMEM);
3735     track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
3736 #if 0
3737     // These properties are required to make QT recognize the chapter track
3738     uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
3739     if (ff_alloc_extradata(track->enc, sizeof(chapter_properties)))
3740         return AVERROR(ENOMEM);
3741     memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));
3742 #else
3743     if (avio_open_dyn_buf(&pb) >= 0) {
3744         int size;
3745         uint8_t *buf;
3746
3747         /* Stub header (usually for Quicktime chapter track) */
3748         // TextSampleEntry
3749         avio_wb32(pb, 0x01); // displayFlags
3750         avio_w8(pb, 0x00);   // horizontal justification
3751         avio_w8(pb, 0x00);   // vertical justification
3752         avio_w8(pb, 0x00);   // bgColourRed
3753         avio_w8(pb, 0x00);   // bgColourGreen
3754         avio_w8(pb, 0x00);   // bgColourBlue
3755         avio_w8(pb, 0x00);   // bgColourAlpha
3756         // BoxRecord
3757         avio_wb16(pb, 0x00); // defTextBoxTop
3758         avio_wb16(pb, 0x00); // defTextBoxLeft
3759         avio_wb16(pb, 0x00); // defTextBoxBottom
3760         avio_wb16(pb, 0x00); // defTextBoxRight
3761         // StyleRecord
3762         avio_wb16(pb, 0x00); // startChar
3763         avio_wb16(pb, 0x00); // endChar
3764         avio_wb16(pb, 0x01); // fontID
3765         avio_w8(pb, 0x00);   // fontStyleFlags
3766         avio_w8(pb, 0x00);   // fontSize
3767         avio_w8(pb, 0x00);   // fgColourRed
3768         avio_w8(pb, 0x00);   // fgColourGreen
3769         avio_w8(pb, 0x00);   // fgColourBlue
3770         avio_w8(pb, 0x00);   // fgColourAlpha
3771         // FontTableBox
3772         avio_wb32(pb, 0x0D); // box size
3773         ffio_wfourcc(pb, "ftab"); // box atom name
3774         avio_wb16(pb, 0x01); // entry count
3775         // FontRecord
3776         avio_wb16(pb, 0x01); // font ID
3777         avio_w8(pb, 0x00);   // font name length
3778
3779         if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
3780             track->enc->extradata = buf;
3781             track->enc->extradata_size = size;
3782         } else {
3783             av_freep(&buf);
3784         }
3785     }
3786 #endif
3787
3788     for (i = 0; i < s->nb_chapters; i++) {
3789         AVChapter *c = s->chapters[i];
3790         AVDictionaryEntry *t;
3791
3792         int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
3793         pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
3794         pkt.duration = end - pkt.dts;
3795
3796         if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
3797             const char encd[12] = {
3798                 0x00, 0x00, 0x00, 0x0C,
3799                 'e',  'n',  'c',  'd',
3800                 0x00, 0x00, 0x01, 0x00 };
3801             len      = strlen(t->value);
3802             pkt.size = len + 2 + 12;
3803             pkt.data = av_malloc(pkt.size);
3804             if (!pkt.data)
3805                 return AVERROR(ENOMEM);
3806             AV_WB16(pkt.data, len);
3807             memcpy(pkt.data + 2, t->value, len);
3808             memcpy(pkt.data + len + 2, encd, sizeof(encd));
3809             ff_mov_write_packet(s, &pkt);
3810             av_freep(&pkt.data);
3811         }
3812     }
3813
3814     return 0;
3815 }
3816
3817 static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
3818 {
3819     int ret;
3820     MOVMuxContext *mov  = s->priv_data;
3821     MOVTrack *track     = &mov->tracks[index];
3822     AVStream *src_st    = s->streams[src_index];
3823     AVTimecode tc;
3824     AVPacket pkt    = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
3825     AVRational rate = find_fps(s, src_st);
3826
3827     /* compute the frame number */
3828     ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
3829     if (ret < 0)
3830         return ret;
3831
3832     /* tmcd track based on video stream */
3833     track->mode      = mov->mode;
3834     track->tag       = MKTAG('t','m','c','d');
3835     track->src_track = src_index;
3836     track->timescale = mov->tracks[src_index].timescale;
3837     if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
3838         track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
3839
3840     /* set st to src_st for metadata access*/
3841     track->st = src_st;
3842
3843     /* encode context: tmcd data stream */
3844     track->enc = avcodec_alloc_context3(NULL);
3845     track->enc->codec_type = AVMEDIA_TYPE_DATA;
3846     track->enc->codec_tag  = track->tag;
3847     track->enc->time_base  = av_inv_q(rate);
3848
3849     /* the tmcd track just contains one packet with the frame number */
3850     pkt.data = av_malloc(pkt.size);
3851     AV_WB32(pkt.data, tc.start);
3852     ret = ff_mov_write_packet(s, &pkt);
3853     av_free(pkt.data);
3854     return ret;
3855 }
3856
3857 /*
3858  * st->disposition controls the "enabled" flag in the tkhd tag.
3859  * QuickTime will not play a track if it is not enabled.  So make sure
3860  * that one track of each type (audio, video, subtitle) is enabled.
3861  *
3862  * Subtitles are special.  For audio and video, setting "enabled" also
3863  * makes the track "default" (i.e. it is rendered when played). For
3864  * subtitles, an "enabled" subtitle is not rendered by default, but
3865  * if no subtitle is enabled, the subtitle menu in QuickTime will be
3866  * empty!
3867  */
3868 static void enable_tracks(AVFormatContext *s)
3869 {
3870     MOVMuxContext *mov = s->priv_data;
3871     int i;
3872     int enabled[AVMEDIA_TYPE_NB];
3873     int first[AVMEDIA_TYPE_NB];
3874
3875     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
3876         enabled[i] = 0;
3877         first[i] = -1;
3878     }
3879
3880     for (i = 0; i < s->nb_streams; i++) {
3881         AVStream *st = s->streams[i];
3882
3883         if (st->codec->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
3884             st->codec->codec_type >= AVMEDIA_TYPE_NB)
3885             continue;
3886
3887         if (first[st->codec->codec_type] < 0)
3888             first[st->codec->codec_type] = i;
3889         if (st->disposition & AV_DISPOSITION_DEFAULT) {
3890             mov->tracks[i].flags |= MOV_TRACK_ENABLED;
3891             enabled[st->codec->codec_type]++;
3892         }
3893     }
3894
3895     for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
3896         switch (i) {
3897         case AVMEDIA_TYPE_VIDEO:
3898         case AVMEDIA_TYPE_AUDIO:
3899         case AVMEDIA_TYPE_SUBTITLE:
3900             if (enabled[i] > 1)
3901                 mov->per_stream_grouping = 1;
3902             if (!enabled[i] && first[i] >= 0)
3903                 mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
3904             break;
3905         }
3906     }
3907 }
3908
3909 static void mov_free(AVFormatContext *s)
3910 {
3911     MOVMuxContext *mov = s->priv_data;
3912     int i;
3913
3914     if (mov->chapter_track) {
3915         if (mov->tracks[mov->chapter_track].enc)
3916             av_freep(&mov->tracks[mov->chapter_track].enc->extradata);
3917         av_freep(&mov->tracks[mov->chapter_track].enc);
3918     }
3919
3920     for (i = 0; i < mov->nb_streams; i++) {
3921         if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
3922             ff_mov_close_hinting(&mov->tracks[i]);
3923         else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
3924             av_freep(&mov->tracks[i].enc);
3925         av_freep(&mov->tracks[i].cluster);
3926         av_freep(&mov->tracks[i].frag_info);
3927
3928         if (mov->tracks[i].vos_len)
3929             av_freep(&mov->tracks[i].vos_data);
3930     }
3931
3932     av_freep(&mov->tracks);
3933 }
3934
3935 static uint32_t rgb_to_yuv(uint32_t rgb)
3936 {
3937     uint8_t r, g, b;
3938     int y, cb, cr;
3939
3940     r = (rgb >> 16) & 0xFF;
3941     g = (rgb >>  8) & 0xFF;
3942     b = (rgb      ) & 0xFF;
3943
3944     y  = av_clip_uint8( 16. +  0.257 * r + 0.504 * g + 0.098 * b);
3945     cb = av_clip_uint8(128. -  0.148 * r - 0.291 * g + 0.439 * b);
3946     cr = av_clip_uint8(128. +  0.439 * r - 0.368 * g - 0.071 * b);
3947
3948     return (y << 16) | (cr << 8) | cb;
3949 }
3950
3951 static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
3952                                                     AVStream *st)
3953 {
3954     int i, width = 720, height = 480;
3955     int have_palette = 0, have_size = 0;
3956     uint32_t palette[16];
3957     char *cur = st->codec->extradata;
3958
3959     while (cur && *cur) {
3960         if (strncmp("palette:", cur, 8) == 0) {
3961             int i, count;
3962             count = sscanf(cur + 8,
3963                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
3964                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
3965                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
3966                 "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
3967                 &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
3968                 &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
3969                 &palette[ 8], &palette[ 9], &palette[10], &palette[11],
3970                 &palette[12], &palette[13], &palette[14], &palette[15]);
3971
3972             for (i = 0; i < count; i++) {
3973                 palette[i] = rgb_to_yuv(palette[i]);
3974             }
3975             have_palette = 1;
3976         } else if (!strncmp("size:", cur, 5)) {
3977             sscanf(cur + 5, "%dx%d", &width, &height);
3978             have_size = 1;
3979         }
3980         if (have_palette && have_size)
3981             break;
3982         cur += strcspn(cur, "\n\r");
3983         cur += strspn(cur, "\n\r");
3984     }
3985     if (have_palette) {
3986         track->vos_data = av_malloc(16*4);
3987         if (!track->vos_data)
3988             return AVERROR(ENOMEM);
3989         for (i = 0; i < 16; i++) {
3990             AV_WB32(track->vos_data + i * 4, palette[i]);
3991         }
3992         track->vos_len = 16 * 4;
3993     }
3994     st->codec->width = width;
3995     st->codec->height = track->height = height;
3996
3997     return 0;
3998 }
3999
4000 static int mov_write_header(AVFormatContext *s)
4001 {
4002     AVIOContext *pb = s->pb;
4003     MOVMuxContext *mov = s->priv_data;
4004     AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
4005     int i, ret, hint_track = 0, tmcd_track = 0;
4006
4007     mov->fc = s;
4008
4009     /* Default mode == MP4 */
4010     mov->mode = MODE_MP4;
4011
4012     if (s->oformat) {
4013         if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
4014         else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
4015         else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
4016         else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
4017         else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
4018         else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
4019         else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
4020     }
4021
4022     if (s->flags & AVFMT_FLAG_BITEXACT)
4023         mov->exact = 1;
4024
4025     /* Set the FRAGMENT flag if any of the fragmentation methods are
4026      * enabled. */
4027     if (mov->max_fragment_duration || mov->max_fragment_size ||
4028         mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
4029                       FF_MOV_FLAG_FRAG_KEYFRAME |
4030                       FF_MOV_FLAG_FRAG_CUSTOM))
4031         mov->flags |= FF_MOV_FLAG_FRAGMENT;
4032
4033     /* Set other implicit flags immediately */
4034     if (mov->mode == MODE_ISM)
4035         mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
4036                       FF_MOV_FLAG_FRAGMENT;
4037
4038     /* faststart: moov at the beginning of the file, if supported */
4039     if (mov->flags & FF_MOV_FLAG_FASTSTART) {
4040         if ((mov->flags & FF_MOV_FLAG_FRAGMENT) ||
4041             (s->flags & AVFMT_FLAG_CUSTOM_IO)) {
4042             av_log(s, AV_LOG_WARNING, "The faststart flag is incompatible "
4043                    "with fragmentation and custom IO, disabling faststart\n");
4044             mov->flags &= ~FF_MOV_FLAG_FASTSTART;
4045         } else
4046             mov->reserved_moov_size = -1;
4047     }
4048
4049     if (!supports_edts(mov) && s->avoid_negative_ts < 0) {
4050         s->avoid_negative_ts = 2;
4051     }
4052
4053     /* Non-seekable output is ok if using fragmentation. If ism_lookahead
4054      * is enabled, we don't support non-seekable output at all. */
4055     if (!s->pb->seekable &&
4056         (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
4057         av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
4058         return AVERROR(EINVAL);
4059     }
4060
4061     mov_write_ftyp_tag(pb,s);
4062     if (mov->mode == MODE_PSP) {
4063         int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
4064         for (i = 0; i < s->nb_streams; i++) {
4065             AVStream *st = s->streams[i];
4066             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
4067                 video_streams_nb++;
4068             else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
4069                 audio_streams_nb++;
4070             else
4071                 other_streams_nb++;
4072             }
4073
4074         if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
4075             av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
4076             return AVERROR(EINVAL);
4077         }
4078         mov_write_uuidprof_tag(pb, s);
4079     }
4080
4081     mov->nb_streams = s->nb_streams;
4082     if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
4083         mov->chapter_track = mov->nb_streams++;
4084
4085     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4086         /* Add hint tracks for each audio and video stream */
4087         hint_track = mov->nb_streams;
4088         for (i = 0; i < s->nb_streams; i++) {
4089             AVStream *st = s->streams[i];
4090             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4091                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4092                 mov->nb_streams++;
4093             }
4094         }
4095     }
4096
4097     if (mov->mode == MODE_MOV) {
4098         tmcd_track = mov->nb_streams;
4099
4100         /* +1 tmcd track for each video stream with a timecode */
4101         for (i = 0; i < s->nb_streams; i++) {
4102             AVStream *st = s->streams[i];
4103             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4104                 (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
4105                 mov->nb_meta_tmcd++;
4106         }
4107
4108         /* check if there is already a tmcd track to remux */
4109         if (mov->nb_meta_tmcd) {
4110             for (i = 0; i < s->nb_streams; i++) {
4111                 AVStream *st = s->streams[i];
4112                 if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
4113                     av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
4114                            "so timecode metadata are now ignored\n");
4115                     mov->nb_meta_tmcd = 0;
4116                 }
4117             }
4118         }
4119
4120         mov->nb_streams += mov->nb_meta_tmcd;
4121     }
4122
4123     // Reserve an extra stream for chapters for the case where chapters
4124     // are written in the trailer
4125     mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
4126     if (!mov->tracks)
4127         return AVERROR(ENOMEM);
4128
4129     for (i = 0; i < s->nb_streams; i++) {
4130         AVStream *st= s->streams[i];
4131         MOVTrack *track= &mov->tracks[i];
4132         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
4133
4134         track->st  = st;
4135         track->enc = st->codec;
4136         track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
4137         if (track->language < 0)
4138             track->language = 0;
4139         track->mode = mov->mode;
4140         track->tag  = mov_find_codec_tag(s, track);
4141         if (!track->tag) {
4142             av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
4143                    "codec not currently supported in container\n",
4144                    avcodec_get_name(st->codec->codec_id), i);
4145             ret = AVERROR(EINVAL);
4146             goto error;
4147         }
4148         /* If hinting of this track is enabled by a later hint track,
4149          * this is updated. */
4150         track->hint_track = -1;
4151         track->start_dts  = AV_NOPTS_VALUE;
4152         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4153             if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
4154                 track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
4155                 track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
4156                 if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
4157                     av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
4158                     ret = AVERROR(EINVAL);
4159                     goto error;
4160                 }
4161                 track->height = track->tag >> 24 == 'n' ? 486 : 576;
4162             }
4163             if (mov->video_track_timescale) {
4164                 track->timescale = mov->video_track_timescale;
4165             } else {
4166                 track->timescale = st->time_base.den;
4167                 while(track->timescale < 10000)
4168                     track->timescale *= 2;
4169             }
4170             if (st->codec->width > 65535 || st->codec->height > 65535) {
4171                 av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codec->width, st->codec->height);
4172                 ret = AVERROR(EINVAL);
4173                 goto error;
4174             }
4175             if (track->mode == MODE_MOV && track->timescale > 100000)
4176                 av_log(s, AV_LOG_WARNING,
4177                        "WARNING codec timebase is very high. If duration is too long,\n"
4178                        "file may not be playable by quicktime. Specify a shorter timebase\n"
4179                        "or choose different container.\n");
4180         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4181             track->timescale = st->codec->sample_rate;
4182             if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
4183                 av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
4184                 track->audio_vbr = 1;
4185             }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
4186                      st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
4187                      st->codec->codec_id == AV_CODEC_ID_ILBC){
4188                 if (!st->codec->block_align) {
4189                     av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
4190                     ret = AVERROR(EINVAL);
4191                     goto error;
4192                 }
4193                 track->sample_size = st->codec->block_align;
4194             }else if (st->codec->frame_size > 1){ /* assume compressed audio */
4195                 track->audio_vbr = 1;
4196             }else{
4197                 track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
4198             }
4199             if (st->codec->codec_id == AV_CODEC_ID_ILBC ||
4200                 st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
4201                 track->audio_vbr = 1;
4202             }
4203             if (track->mode != MODE_MOV &&
4204                 track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
4205                 av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
4206                        i, track->enc->sample_rate);
4207                 ret = AVERROR(EINVAL);
4208                 goto error;
4209             }
4210         } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4211             track->timescale = st->time_base.den;
4212         } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
4213             track->timescale = st->time_base.den;
4214         } else {
4215             track->timescale = MOV_TIMESCALE;
4216         }
4217         if (!track->height)
4218             track->height = st->codec->height;
4219         /* The ism specific timescale isn't mandatory, but is assumed by
4220          * some tools, such as mp4split. */
4221         if (mov->mode == MODE_ISM)
4222             track->timescale = 10000000;
4223
4224         avpriv_set_pts_info(st, 64, 1, track->timescale);
4225
4226         /* copy extradata if it exists */
4227         if (st->codec->extradata_size) {
4228             if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
4229                 mov_create_dvd_sub_decoder_specific_info(track, st);
4230             else {
4231                 track->vos_len  = st->codec->extradata_size;
4232                 track->vos_data = av_malloc(track->vos_len);
4233                 memcpy(track->vos_data, st->codec->extradata, track->vos_len);
4234             }
4235         }
4236     }
4237
4238     for (i = 0; i < s->nb_streams; i++) {
4239         int j;
4240         AVStream *st= s->streams[i];
4241         MOVTrack *track= &mov->tracks[i];
4242
4243         if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
4244             track->enc->channel_layout != AV_CH_LAYOUT_MONO)
4245             continue;
4246
4247         for (j = 0; j < s->nb_streams; j++) {
4248             AVStream *stj= s->streams[j];
4249             MOVTrack *trackj= &mov->tracks[j];
4250             if (j == i)
4251                 continue;
4252
4253             if (stj->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
4254                 trackj->enc->channel_layout != AV_CH_LAYOUT_MONO ||
4255                 trackj->language != track->language ||
4256                 trackj->tag != track->tag
4257             )
4258                 continue;
4259             track->multichannel_as_mono++;
4260         }
4261     }
4262
4263     enable_tracks(s);
4264
4265
4266     if (mov->reserved_moov_size){
4267         mov->reserved_moov_pos= avio_tell(pb);
4268         if (mov->reserved_moov_size > 0)
4269             avio_skip(pb, mov->reserved_moov_size);
4270     }
4271
4272     if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
4273         /* If no fragmentation options have been set, set a default. */
4274         if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
4275                             FF_MOV_FLAG_FRAG_CUSTOM)) &&
4276             !mov->max_fragment_duration && !mov->max_fragment_size)
4277             mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
4278     } else {
4279         if (mov->flags & FF_MOV_FLAG_FASTSTART)
4280             mov->reserved_moov_pos = avio_tell(pb);
4281         mov_write_mdat_tag(pb, mov);
4282     }
4283
4284     if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
4285         mov->time = ff_iso8601_to_unix_time(t->value);
4286     if (mov->time)
4287         mov->time += 0x7C25B080; // 1970 based -> 1904 based
4288
4289     if (mov->chapter_track)
4290         if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
4291             goto error;
4292
4293     if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
4294         /* Initialize the hint tracks for each audio and video stream */
4295         for (i = 0; i < s->nb_streams; i++) {
4296             AVStream *st = s->streams[i];
4297             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
4298                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
4299                 if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
4300                     goto error;
4301                 hint_track++;
4302             }
4303         }
4304     }
4305
4306     if (mov->nb_meta_tmcd) {
4307         /* Initialize the tmcd tracks */
4308         for (i = 0; i < s->nb_streams; i++) {
4309             AVStream *st = s->streams[i];
4310             t = global_tcr;
4311
4312             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
4313                 if (!t)
4314                     t = av_dict_get(st->metadata, "timecode", NULL, 0);
4315                 if (!t)
4316                     continue;
4317                 if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
4318                     goto error;
4319                 tmcd_track++;
4320             }
4321         }
4322     }
4323
4324     avio_flush(pb);
4325
4326     if (mov->flags & FF_MOV_FLAG_ISML)
4327         mov_write_isml_manifest(pb, mov);
4328
4329     if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
4330         mov_write_moov_tag(pb, mov, s);
4331         mov->fragments++;
4332     }
4333
4334     return 0;
4335  error:
4336     mov_free(s);
4337     return ret;
4338 }
4339
4340 static int get_moov_size(AVFormatContext *s)
4341 {
4342     int ret;
4343     AVIOContext *moov_buf;
4344     MOVMuxContext *mov = s->priv_data;
4345
4346     if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
4347         return ret;
4348     mov_write_moov_tag(moov_buf, mov, s);
4349     return ffio_close_null_buf(moov_buf);
4350 }
4351
4352 /*
4353  * This function gets the moov size if moved to the top of the file: the chunk
4354  * offset table can switch between stco (32-bit entries) to co64 (64-bit
4355  * entries) when the moov is moved to the beginning, so the size of the moov
4356  * would change. It also updates the chunk offset tables.
4357  */
4358 static int compute_moov_size(AVFormatContext *s)
4359 {
4360     int i, moov_size, moov_size2;
4361     MOVMuxContext *mov = s->priv_data;
4362
4363     moov_size = get_moov_size(s);
4364     if (moov_size < 0)
4365         return moov_size;
4366
4367     for (i = 0; i < mov->nb_streams; i++)
4368         mov->tracks[i].data_offset += moov_size;
4369
4370     moov_size2 = get_moov_size(s);
4371     if (moov_size2 < 0)
4372         return moov_size2;
4373
4374     /* if the size changed, we just switched from stco to co64 and need to
4375      * update the offsets */
4376     if (moov_size2 != moov_size)
4377         for (i = 0; i < mov->nb_streams; i++)
4378             mov->tracks[i].data_offset += moov_size2 - moov_size;
4379
4380     return moov_size2;
4381 }
4382
4383 static int shift_data(AVFormatContext *s)
4384 {
4385     int ret = 0, moov_size;
4386     MOVMuxContext *mov = s->priv_data;
4387     int64_t pos, pos_end = avio_tell(s->pb);
4388     uint8_t *buf, *read_buf[2];
4389     int read_buf_id = 0;
4390     int read_size[2];
4391     AVIOContext *read_pb;
4392
4393     moov_size = compute_moov_size(s);
4394     if (moov_size < 0)
4395         return moov_size;
4396
4397     buf = av_malloc(moov_size * 2);
4398     if (!buf)
4399         return AVERROR(ENOMEM);
4400     read_buf[0] = buf;
4401     read_buf[1] = buf + moov_size;
4402
4403     /* Shift the data: the AVIO context of the output can only be used for
4404      * writing, so we re-open the same output, but for reading. It also avoids
4405      * a read/seek/write/seek back and forth. */
4406     avio_flush(s->pb);
4407     ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ);
4408     if (ret < 0) {
4409         av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
4410                "the second pass (faststart)\n", s->filename);
4411         goto end;
4412     }
4413
4414     /* mark the end of the shift to up to the last data we wrote, and get ready
4415      * for writing */
4416     pos_end = avio_tell(s->pb);
4417     avio_seek(s->pb, mov->reserved_moov_pos + moov_size, SEEK_SET);
4418
4419     /* start reading at where the new moov will be placed */
4420     avio_seek(read_pb, mov->reserved_moov_pos, SEEK_SET);
4421     pos = avio_tell(read_pb);
4422
4423 #define READ_BLOCK do {                                                             \
4424     read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size);  \
4425     read_buf_id ^= 1;                                                               \
4426 } while (0)
4427
4428     /* shift data by chunk of at most moov_size */
4429     READ_BLOCK;
4430     do {
4431         int n;
4432         READ_BLOCK;
4433         n = read_size[read_buf_id];
4434         if (n <= 0)
4435             break;
4436         avio_write(s->pb, read_buf[read_buf_id], n);
4437         pos += n;
4438     } while (pos < pos_end);
4439     avio_close(read_pb);
4440
4441 end:
4442     av_free(buf);
4443     return ret;
4444 }
4445
4446 static int mov_write_trailer(AVFormatContext *s)
4447 {
4448     MOVMuxContext *mov = s->priv_data;
4449     AVIOContext *pb = s->pb;
4450     int res = 0;
4451     int i;
4452     int64_t moov_pos;
4453
4454     /*
4455      * Before actually writing the trailer, make sure that there are no
4456      * dangling subtitles, that need a terminating sample.
4457      */
4458     for (i = 0; i < mov->nb_streams; i++) {
4459         MOVTrack *trk = &mov->tracks[i];
4460         if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
4461             !trk->last_sample_is_subtitle_end) {
4462             mov_write_subtitle_end_packet(s, i, trk->track_duration);
4463             trk->last_sample_is_subtitle_end = 1;
4464         }
4465     }
4466
4467     // If there were no chapters when the header was written, but there
4468     // are chapters now, write them in the trailer.  This only works
4469     // when we are not doing fragments.
4470     if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
4471         if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
4472             mov->chapter_track = mov->nb_streams++;
4473             if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
4474                 goto error;
4475         }
4476     }
4477
4478     if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
4479         moov_pos = avio_tell(pb);
4480
4481         /* Write size of mdat tag */
4482         if (mov->mdat_size + 8 <= UINT32_MAX) {
4483             avio_seek(pb, mov->mdat_pos, SEEK_SET);
4484             avio_wb32(pb, mov->mdat_size + 8);
4485         } else {
4486             /* overwrite 'wide' placeholder atom */
4487             avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
4488             /* special value: real atom size will be 64 bit value after
4489              * tag field */
4490             avio_wb32(pb, 1);
4491             ffio_wfourcc(pb, "mdat");
4492             avio_wb64(pb, mov->mdat_size + 16);
4493         }
4494         avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
4495
4496         if (mov->flags & FF_MOV_FLAG_FASTSTART) {
4497             av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
4498             res = shift_data(s);
4499             if (res == 0) {
4500                 avio_seek(s->pb, mov->reserved_moov_pos, SEEK_SET);
4501                 mov_write_moov_tag(pb, mov, s);
4502             }
4503         } else if (mov->reserved_moov_size > 0) {
4504             int64_t size;
4505             mov_write_moov_tag(pb, mov, s);
4506             size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
4507             if (size < 8){
4508                 av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
4509                 return -1;
4510             }
4511             avio_wb32(pb, size);
4512             ffio_wfourcc(pb, "free");
4513             ffio_fill(pb, 0, size - 8);
4514             avio_seek(pb, moov_pos, SEEK_SET);
4515         } else {
4516             mov_write_moov_tag(pb, mov, s);
4517         }
4518     } else {
4519         mov_flush_fragment(s);
4520         mov_write_mfra_tag(pb, mov);
4521     }
4522
4523     for (i = 0; i < mov->nb_streams; i++) {
4524         if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
4525             mov->tracks[i].vc1_info.struct_offset && s->pb->seekable) {
4526             int64_t off = avio_tell(pb);
4527             uint8_t buf[7];
4528             if (mov_write_dvc1_structs(&mov->tracks[i], buf) >= 0) {
4529                 avio_seek(pb, mov->tracks[i].vc1_info.struct_offset, SEEK_SET);
4530                 avio_write(pb, buf, 7);
4531                 avio_seek(pb, off, SEEK_SET);
4532             }
4533         }
4534     }
4535
4536 error:
4537     mov_free(s);
4538
4539     return res;
4540 }
4541
4542 #if CONFIG_MOV_MUXER
4543 MOV_CLASS(mov)
4544 AVOutputFormat ff_mov_muxer = {
4545     .name              = "mov",
4546     .long_name         = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
4547     .extensions        = "mov",
4548     .priv_data_size    = sizeof(MOVMuxContext),
4549     .audio_codec       = AV_CODEC_ID_AAC,
4550     .video_codec       = CONFIG_LIBX264_ENCODER ?
4551                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4552     .write_header      = mov_write_header,
4553     .write_packet      = mov_write_packet,
4554     .write_trailer     = mov_write_trailer,
4555     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4556     .codec_tag         = (const AVCodecTag* const []){
4557         ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
4558     },
4559     .priv_class        = &mov_muxer_class,
4560 };
4561 #endif
4562 #if CONFIG_TGP_MUXER
4563 MOV_CLASS(tgp)
4564 AVOutputFormat ff_tgp_muxer = {
4565     .name              = "3gp",
4566     .long_name         = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
4567     .extensions        = "3gp",
4568     .priv_data_size    = sizeof(MOVMuxContext),
4569     .audio_codec       = AV_CODEC_ID_AMR_NB,
4570     .video_codec       = AV_CODEC_ID_H263,
4571     .write_header      = mov_write_header,
4572     .write_packet      = mov_write_packet,
4573     .write_trailer     = mov_write_trailer,
4574     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4575     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
4576     .priv_class        = &tgp_muxer_class,
4577 };
4578 #endif
4579 #if CONFIG_MP4_MUXER
4580 MOV_CLASS(mp4)
4581 AVOutputFormat ff_mp4_muxer = {
4582     .name              = "mp4",
4583     .long_name         = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
4584     .mime_type         = "application/mp4",
4585     .extensions        = "mp4",
4586     .priv_data_size    = sizeof(MOVMuxContext),
4587     .audio_codec       = AV_CODEC_ID_AAC,
4588     .video_codec       = CONFIG_LIBX264_ENCODER ?
4589                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4590     .write_header      = mov_write_header,
4591     .write_packet      = mov_write_packet,
4592     .write_trailer     = mov_write_trailer,
4593     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4594     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4595     .priv_class        = &mp4_muxer_class,
4596 };
4597 #endif
4598 #if CONFIG_PSP_MUXER
4599 MOV_CLASS(psp)
4600 AVOutputFormat ff_psp_muxer = {
4601     .name              = "psp",
4602     .long_name         = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
4603     .extensions        = "mp4,psp",
4604     .priv_data_size    = sizeof(MOVMuxContext),
4605     .audio_codec       = AV_CODEC_ID_AAC,
4606     .video_codec       = CONFIG_LIBX264_ENCODER ?
4607                          AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
4608     .write_header      = mov_write_header,
4609     .write_packet      = mov_write_packet,
4610     .write_trailer     = mov_write_trailer,
4611     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4612     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4613     .priv_class        = &psp_muxer_class,
4614 };
4615 #endif
4616 #if CONFIG_TG2_MUXER
4617 MOV_CLASS(tg2)
4618 AVOutputFormat ff_tg2_muxer = {
4619     .name              = "3g2",
4620     .long_name         = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
4621     .extensions        = "3g2",
4622     .priv_data_size    = sizeof(MOVMuxContext),
4623     .audio_codec       = AV_CODEC_ID_AMR_NB,
4624     .video_codec       = AV_CODEC_ID_H263,
4625     .write_header      = mov_write_header,
4626     .write_packet      = mov_write_packet,
4627     .write_trailer     = mov_write_trailer,
4628     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4629     .codec_tag         = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
4630     .priv_class        = &tg2_muxer_class,
4631 };
4632 #endif
4633 #if CONFIG_IPOD_MUXER
4634 MOV_CLASS(ipod)
4635 AVOutputFormat ff_ipod_muxer = {
4636     .name              = "ipod",
4637     .long_name         = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
4638     .mime_type         = "application/mp4",
4639     .extensions        = "m4v,m4a",
4640     .priv_data_size    = sizeof(MOVMuxContext),
4641     .audio_codec       = AV_CODEC_ID_AAC,
4642     .video_codec       = AV_CODEC_ID_H264,
4643     .write_header      = mov_write_header,
4644     .write_packet      = mov_write_packet,
4645     .write_trailer     = mov_write_trailer,
4646     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4647     .codec_tag         = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
4648     .priv_class        = &ipod_muxer_class,
4649 };
4650 #endif
4651 #if CONFIG_ISMV_MUXER
4652 MOV_CLASS(ismv)
4653 AVOutputFormat ff_ismv_muxer = {
4654     .name              = "ismv",
4655     .long_name         = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
4656     .mime_type         = "application/mp4",
4657     .extensions        = "ismv,isma",
4658     .priv_data_size    = sizeof(MOVMuxContext),
4659     .audio_codec       = AV_CODEC_ID_AAC,
4660     .video_codec       = AV_CODEC_ID_H264,
4661     .write_header      = mov_write_header,
4662     .write_packet      = mov_write_packet,
4663     .write_trailer     = mov_write_trailer,
4664     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
4665     .codec_tag         = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
4666     .priv_class        = &ismv_muxer_class,
4667 };
4668 #endif
4669 #if CONFIG_F4V_MUXER
4670 MOV_CLASS(f4v)
4671 AVOutputFormat ff_f4v_muxer = {
4672     .name              = "f4v",
4673     .long_name         = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
4674     .mime_type         = "application/f4v",
4675     .extensions        = "f4v",
4676     .priv_data_size    = sizeof(MOVMuxContext),
4677     .audio_codec       = AV_CODEC_ID_AAC,
4678     .video_codec       = AV_CODEC_ID_H264,
4679     .write_header      = mov_write_header,
4680     .write_packet      = mov_write_packet,
4681     .write_trailer     = mov_write_trailer,
4682     .flags             = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
4683     .codec_tag         = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
4684     .priv_class        = &f4v_muxer_class,
4685 };
4686 #endif