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