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