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