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