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