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