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