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