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