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