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