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