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->vos_data, track->vos_len, track->par);
1379 
1380  return update_size(pb, pos);
1381 }
1382 
1383 static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
1384 {
1385  int64_t pos = avio_tell(pb);
1386 
1387  avio_wb32(pb, 0);
1388  ffio_wfourcc(pb, "hvcC");
1389  if (track->tag == MKTAG('h','v','c','1'))
1390  ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
1391  else
1392  ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
1393  return update_size(pb, pos);
1394 }
1395 
1396 /* also used by all avid codecs (dv, imx, meridien) and their variants */
1397 static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
1398 {
1399  int interlaced;
1400  int cid;
1401  int display_width = track->par->width;
1402 
1403  if (track->vos_data && track->vos_len > 0x29) {
1404  if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
1405  /* looks like a DNxHD bit stream */
1406  interlaced = (track->vos_data[5] & 2);
1407  cid = AV_RB32(track->vos_data + 0x28);
1408  } else {
1409  av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
1410  return 0;
1411  }
1412  } else {
1413  av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
1414  return 0;
1415  }
1416 
1417  avio_wb32(pb, 24); /* size */
1418  ffio_wfourcc(pb, "ACLR");
1419  ffio_wfourcc(pb, "ACLR");
1420  ffio_wfourcc(pb, "0001");
1421  if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
1423  avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
1424  } else { /* Full range (0-255) */
1425  avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
1426  }
1427  avio_wb32(pb, 0); /* unknown */
1428 
1429  if (track->tag == MKTAG('A','V','d','h')) {
1430  avio_wb32(pb, 32);
1431  ffio_wfourcc(pb, "ADHR");
1432  ffio_wfourcc(pb, "0001");
1433  avio_wb32(pb, cid);
1434  avio_wb32(pb, 0); /* unknown */
1435  avio_wb32(pb, 1); /* unknown */
1436  avio_wb32(pb, 0); /* unknown */
1437  avio_wb32(pb, 0); /* unknown */
1438  return 0;
1439  }
1440 
1441  avio_wb32(pb, 24); /* size */
1442  ffio_wfourcc(pb, "APRG");
1443  ffio_wfourcc(pb, "APRG");
1444  ffio_wfourcc(pb, "0001");
1445  avio_wb32(pb, 1); /* unknown */
1446  avio_wb32(pb, 0); /* unknown */
1447 
1448  avio_wb32(pb, 120); /* size */
1449  ffio_wfourcc(pb, "ARES");
1450  ffio_wfourcc(pb, "ARES");
1451  ffio_wfourcc(pb, "0001");
1452  avio_wb32(pb, cid); /* dnxhd cid, some id ? */
1453  if ( track->par->sample_aspect_ratio.num > 0
1454  && track->par->sample_aspect_ratio.den > 0)
1455  display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
1456  avio_wb32(pb, display_width);
1457  /* values below are based on samples created with quicktime and avid codecs */
1458  if (interlaced) {
1459  avio_wb32(pb, track->par->height / 2);
1460  avio_wb32(pb, 2); /* unknown */
1461  avio_wb32(pb, 0); /* unknown */
1462  avio_wb32(pb, 4); /* unknown */
1463  } else {
1464  avio_wb32(pb, track->par->height);
1465  avio_wb32(pb, 1); /* unknown */
1466  avio_wb32(pb, 0); /* unknown */
1467  if (track->par->height == 1080)
1468  avio_wb32(pb, 5); /* unknown */
1469  else
1470  avio_wb32(pb, 6); /* unknown */
1471  }
1472  /* padding */
1473  ffio_fill(pb, 0, 10 * 8);
1474 
1475  return 0;
1476 }
1477 
1478 static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
1479 {
1480  avio_wb32(pb, 12);
1481  ffio_wfourcc(pb, "DpxE");
1482  if (track->par->extradata_size >= 12 &&
1483  !memcmp(&track->par->extradata[4], "DpxE", 4)) {
1484  avio_wb32(pb, track->par->extradata[11]);
1485  } else {
1486  avio_wb32(pb, 1);
1487  }
1488  return 0;
1489 }
1490 
1492 {
1493  int tag;
1494 
1495  if (track->par->width == 720) { /* SD */
1496  if (track->par->height == 480) { /* NTSC */
1497  if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
1498  else tag = MKTAG('d','v','c',' ');
1499  }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
1500  else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
1501  else tag = MKTAG('d','v','p','p');
1502  } else if (track->par->height == 720) { /* HD 720 line */
1503  if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
1504  else tag = MKTAG('d','v','h','p');
1505  } else if (track->par->height == 1080) { /* HD 1080 line */
1506  if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
1507  else tag = MKTAG('d','v','h','6');
1508  } else {
1509  av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
1510  return 0;
1511  }
1512 
1513  return tag;
1514 }
1515 
1517 {
1518  AVRational rational_framerate = st->avg_frame_rate;
1519  int rate = 0;
1520  if (rational_framerate.den != 0)
1521  rate = av_q2d(rational_framerate);
1522  return rate;
1523 }
1524 
1526 {
1527  int tag = track->par->codec_tag;
1529  AVStream *st = track->st;
1530  int rate = defined_frame_rate(s, st);
1531 
1532  if (!tag)
1533  tag = MKTAG('m', '2', 'v', '1'); //fallback tag
1534 
1535  if (track->par->format == AV_PIX_FMT_YUV420P) {
1536  if (track->par->width == 1280 && track->par->height == 720) {
1537  if (!interlaced) {
1538  if (rate == 24) tag = MKTAG('x','d','v','4');
1539  else if (rate == 25) tag = MKTAG('x','d','v','5');
1540  else if (rate == 30) tag = MKTAG('x','d','v','1');
1541  else if (rate == 50) tag = MKTAG('x','d','v','a');
1542  else if (rate == 60) tag = MKTAG('x','d','v','9');
1543  }
1544  } else if (track->par->width == 1440 && track->par->height == 1080) {
1545  if (!interlaced) {
1546  if (rate == 24) tag = MKTAG('x','d','v','6');
1547  else if (rate == 25) tag = MKTAG('x','d','v','7');
1548  else if (rate == 30) tag = MKTAG('x','d','v','8');
1549  } else {
1550  if (rate == 25) tag = MKTAG('x','d','v','3');
1551  else if (rate == 30) tag = MKTAG('x','d','v','2');
1552  }
1553  } else if (track->par->width == 1920 && track->par->height == 1080) {
1554  if (!interlaced) {
1555  if (rate == 24) tag = MKTAG('x','d','v','d');
1556  else if (rate == 25) tag = MKTAG('x','d','v','e');
1557  else if (rate == 30) tag = MKTAG('x','d','v','f');
1558  } else {
1559  if (rate == 25) tag = MKTAG('x','d','v','c');
1560  else if (rate == 30) tag = MKTAG('x','d','v','b');
1561  }
1562  }
1563  } else if (track->par->format == AV_PIX_FMT_YUV422P) {
1564  if (track->par->width == 1280 && track->par->height == 720) {
1565  if (!interlaced) {
1566  if (rate == 24) tag = MKTAG('x','d','5','4');
1567  else if (rate == 25) tag = MKTAG('x','d','5','5');
1568  else if (rate == 30) tag = MKTAG('x','d','5','1');
1569  else if (rate == 50) tag = MKTAG('x','d','5','a');
1570  else if (rate == 60) tag = MKTAG('x','d','5','9');
1571  }
1572  } else if (track->par->width == 1920 && track->par->height == 1080) {
1573  if (!interlaced) {
1574  if (rate == 24) tag = MKTAG('x','d','5','d');
1575  else if (rate == 25) tag = MKTAG('x','d','5','e');
1576  else if (rate == 30) tag = MKTAG('x','d','5','f');
1577  } else {
1578  if (rate == 25) tag = MKTAG('x','d','5','c');
1579  else if (rate == 30) tag = MKTAG('x','d','5','b');
1580  }
1581  }
1582  }
1583 
1584  return tag;
1585 }
1586 
1588 {
1589  int tag = track->par->codec_tag;
1591  AVStream *st = track->st;
1592  int rate = defined_frame_rate(s, st);
1593 
1594  if (!tag)
1595  tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
1596 
1597  if (track->par->format == AV_PIX_FMT_YUV420P10) {
1598  if (track->par->width == 960 && track->par->height == 720) {
1599  if (!interlaced) {
1600  if (rate == 24) tag = MKTAG('a','i','5','p');
1601  else if (rate == 25) tag = MKTAG('a','i','5','q');
1602  else if (rate == 30) tag = MKTAG('a','i','5','p');
1603  else if (rate == 50) tag = MKTAG('a','i','5','q');
1604  else if (rate == 60) tag = MKTAG('a','i','5','p');
1605  }
1606  } else if (track->par->width == 1440 && track->par->height == 1080) {
1607  if (!interlaced) {
1608  if (rate == 24) tag = MKTAG('a','i','5','3');
1609  else if (rate == 25) tag = MKTAG('a','i','5','2');
1610  else if (rate == 30) tag = MKTAG('a','i','5','3');
1611  } else {
1612  if (rate == 50) tag = MKTAG('a','i','5','5');
1613  else if (rate == 60) tag = MKTAG('a','i','5','6');
1614  }
1615  }
1616  } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
1617  if (track->par->width == 1280 && track->par->height == 720) {
1618  if (!interlaced) {
1619  if (rate == 24) tag = MKTAG('a','i','1','p');
1620  else if (rate == 25) tag = MKTAG('a','i','1','q');
1621  else if (rate == 30) tag = MKTAG('a','i','1','p');
1622  else if (rate == 50) tag = MKTAG('a','i','1','q');
1623  else if (rate == 60) tag = MKTAG('a','i','1','p');
1624  }
1625  } else if (track->par->width == 1920 && track->par->height == 1080) {
1626  if (!interlaced) {
1627  if (rate == 24) tag = MKTAG('a','i','1','3');
1628  else if (rate == 25) tag = MKTAG('a','i','1','2');
1629  else if (rate == 30) tag = MKTAG('a','i','1','3');
1630  } else {
1631  if (rate == 25) tag = MKTAG('a','i','1','5');
1632  else if (rate == 50) tag = MKTAG('a','i','1','5');
1633  else if (rate == 60) tag = MKTAG('a','i','1','6');
1634  }
1635  } else if ( track->par->width == 4096 && track->par->height == 2160
1636  || track->par->width == 3840 && track->par->height == 2160
1637  || track->par->width == 2048 && track->par->height == 1080) {
1638  tag = MKTAG('a','i','v','x');
1639  }
1640  }
1641 
1642  return tag;
1643 }
1644 
1645 static const struct {
1647  uint32_t tag;
1648  unsigned bps;
1649 } mov_pix_fmt_tags[] = {
1650  { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
1651  { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
1652  { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
1653  { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
1654  { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
1655  { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
1656  { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
1657  { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
1658  { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
1659  { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
1660  { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
1661  { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
1662  { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
1663  { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
1664  { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
1665 };
1666 
1668 {
1669  int tag = MKTAG('A','V','d','n');
1670  if (track->par->profile != FF_PROFILE_UNKNOWN &&
1671  track->par->profile != FF_PROFILE_DNXHD)
1672  tag = MKTAG('A','V','d','h');
1673  return tag;
1674 }
1675 
1677 {
1678  int tag = track->par->codec_tag;
1679  int i;
1680  enum AVPixelFormat pix_fmt;
1681 
1682  for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
1683  if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
1684  tag = mov_pix_fmt_tags[i].tag;
1686  if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
1687  break;
1688  }
1689  }
1690 
1692  track->par->bits_per_coded_sample);
1693  if (tag == MKTAG('r','a','w',' ') &&
1694  track->par->format != pix_fmt &&
1695  track->par->format != AV_PIX_FMT_GRAY8 &&
1696  track->par->format != AV_PIX_FMT_NONE)
1697  av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
1698  av_get_pix_fmt_name(track->par->format));
1699  return tag;
1700 }
1701 
1702 static unsigned int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
1703 {
1704  unsigned int tag = track->par->codec_tag;
1705 
1706  // "rtp " is used to distinguish internally created RTP-hint tracks
1707  // (with rtp_ctx) from other tracks.
1708  if (tag == MKTAG('r','t','p',' '))
1709  tag = 0;
1710  if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
1711  (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
1712  track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
1713  track->par->codec_id == AV_CODEC_ID_H263 ||
1714  track->par->codec_id == AV_CODEC_ID_H264 ||
1715  track->par->codec_id == AV_CODEC_ID_DNXHD ||
1716  track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
1717  av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
1718  if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
1719  tag = mov_get_dv_codec_tag(s, track);
1720  else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
1721  tag = mov_get_rawvideo_codec_tag(s, track);
1722  else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1724  else if (track->par->codec_id == AV_CODEC_ID_H264)
1725  tag = mov_get_h264_codec_tag(s, track);
1726  else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
1727  tag = mov_get_dnxhd_codec_tag(s, track);
1728  else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
1730  if (!tag) { // if no mac fcc found, try with Microsoft tags
1732  if (tag)
1733  av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
1734  "the file may be unplayable!\n");
1735  }
1736  } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
1738  if (!tag) { // if no mac fcc found, try with Microsoft tags
1739  int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
1740  if (ms_tag) {
1741  tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
1742  av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
1743  "the file may be unplayable!\n");
1744  }
1745  }
1746  } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
1748  }
1749 
1750  return tag;
1751 }
1752 
1754  { AV_CODEC_ID_MJPEG, 0xD },
1755  { AV_CODEC_ID_PNG, 0xE },
1756  { AV_CODEC_ID_BMP, 0x1B },
1757  { AV_CODEC_ID_NONE, 0 },
1758 };
1759 
1760 static unsigned int validate_codec_tag(const AVCodecTag *const *tags,
1761  unsigned int tag, int codec_id)
1762 {
1763  int i;
1764 
1765  /**
1766  * Check that tag + id is in the table
1767  */
1768  for (i = 0; tags && tags[i]; i++) {
1769  const AVCodecTag *codec_tags = tags[i];
1770  while (codec_tags->id != AV_CODEC_ID_NONE) {
1771  if (ff_toupper4(codec_tags->tag) == ff_toupper4(tag) &&
1772  codec_tags->id == codec_id)
1773  return codec_tags->tag;
1774  codec_tags++;
1775  }
1776  }
1777  return 0;
1778 }
1779 
1780 static unsigned int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
1781 {
1782  if (is_cover_image(track->st))
1784 
1785  if (track->mode == MODE_IPOD)
1786  if (!av_match_ext(s->url, "m4a") &&
1787  !av_match_ext(s->url, "m4v") &&
1788  !av_match_ext(s->url, "m4b"))
1789  av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
1790  "Quicktime/Ipod might not play the file\n");
1791 
1792  if (track->mode == MODE_MOV) {
1793  return mov_get_codec_tag(s, track);
1794  } else
1795  return validate_codec_tag(s->oformat->codec_tag, track->par->codec_tag,
1796  track->par->codec_id);
1797 }
1798 
1799 /** Write uuid atom.
1800  * Needed to make file play in iPods running newest firmware
1801  * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
1802  */
1804 {
1805  avio_wb32(pb, 28);
1806  ffio_wfourcc(pb, "uuid");
1807  avio_wb32(pb, 0x6b6840f2);
1808  avio_wb32(pb, 0x5f244fc5);
1809  avio_wb32(pb, 0xba39a51b);
1810  avio_wb32(pb, 0xcf0323f3);
1811  avio_wb32(pb, 0x0);
1812  return 28;
1813 }
1814 
1815 static const uint16_t fiel_data[] = {
1816  0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
1817 };
1818 
1819 static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
1820 {
1821  unsigned mov_field_order = 0;
1822  if (field_order < FF_ARRAY_ELEMS(fiel_data))
1823  mov_field_order = fiel_data[field_order];
1824  else
1825  return 0;
1826  avio_wb32(pb, 10);
1827  ffio_wfourcc(pb, "fiel");
1828  avio_wb16(pb, mov_field_order);
1829  return 10;
1830 }
1831 
1833 {
1834  MOVMuxContext *mov = s->priv_data;
1835  int ret = AVERROR_BUG;
1836  int64_t pos = avio_tell(pb);
1837  avio_wb32(pb, 0); /* size */
1838  avio_wl32(pb, track->tag); // store it byteswapped
1839  avio_wb32(pb, 0); /* Reserved */
1840  avio_wb16(pb, 0); /* Reserved */
1841  avio_wb16(pb, 1); /* Data-reference index */
1842 
1843  if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
1844  mov_write_esds_tag(pb, track);
1845  else if (track->par->codec_id == AV_CODEC_ID_TTML) {
1846  switch (track->par->codec_tag) {
1847  case MOV_ISMV_TTML_TAG:
1848  // ISMV dfxp requires no extradata.
1849  break;
1850  case MOV_MP4_TTML_TAG:
1851  // As specified in 14496-30, XMLSubtitleSampleEntry
1852  // Namespace
1853  avio_put_str(pb, "http://www.w3.org/ns/ttml");
1854  // Empty schema_location
1855  avio_w8(pb, 0);
1856  // Empty auxiliary_mime_types
1857  avio_w8(pb, 0);
1858  break;
1859  default:
1861  "Unknown codec tag '%s' utilized for TTML stream with "
1862  "index %d (track id %d)!\n",
1863  av_fourcc2str(track->par->codec_tag), track->st->index,
1864  track->track_id);
1865  return AVERROR(EINVAL);
1866  }
1867  } else if (track->par->extradata_size)
1868  avio_write(pb, track->par->extradata, track->par->extradata_size);
1869 
1870  if (mov->write_btrt &&
1871  ((ret = mov_write_btrt_tag(pb, track)) < 0))
1872  return ret;
1873 
1874  return update_size(pb, pos);
1875 }
1876 
1878 {
1879  int8_t stereo_mode;
1880 
1881  if (stereo_3d->flags != 0) {
1882  av_log(s, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
1883  return 0;
1884  }
1885 
1886  switch (stereo_3d->type) {
1887  case AV_STEREO3D_2D:
1888  stereo_mode = 0;
1889  break;
1890  case AV_STEREO3D_TOPBOTTOM:
1891  stereo_mode = 1;
1892  break;
1894  stereo_mode = 2;
1895  break;
1896  default:
1897  av_log(s, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
1898  return 0;
1899  }
1900  avio_wb32(pb, 13); /* size */
1901  ffio_wfourcc(pb, "st3d");
1902  avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1903  avio_w8(pb, stereo_mode);
1904  return 13;
1905 }
1906 
1908 {
1909  int64_t sv3d_pos, svhd_pos, proj_pos;
1910  const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
1911 
1912  if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
1913  spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
1914  spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
1915  av_log(s, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
1916  return 0;
1917  }
1918 
1919  sv3d_pos = avio_tell(pb);
1920  avio_wb32(pb, 0); /* size */
1921  ffio_wfourcc(pb, "sv3d");
1922 
1923  svhd_pos = avio_tell(pb);
1924  avio_wb32(pb, 0); /* size */
1925  ffio_wfourcc(pb, "svhd");
1926  avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1927  avio_put_str(pb, metadata_source);
1928  update_size(pb, svhd_pos);
1929 
1930  proj_pos = avio_tell(pb);
1931  avio_wb32(pb, 0); /* size */
1932  ffio_wfourcc(pb, "proj");
1933 
1934  avio_wb32(pb, 24); /* size */
1935  ffio_wfourcc(pb, "prhd");
1936  avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1937  avio_wb32(pb, spherical_mapping->yaw);
1938  avio_wb32(pb, spherical_mapping->pitch);
1939  avio_wb32(pb, spherical_mapping->roll);
1940 
1941  switch (spherical_mapping->projection) {
1944  avio_wb32(pb, 28); /* size */
1945  ffio_wfourcc(pb, "equi");
1946  avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1947  avio_wb32(pb, spherical_mapping->bound_top);
1948  avio_wb32(pb, spherical_mapping->bound_bottom);
1949  avio_wb32(pb, spherical_mapping->bound_left);
1950  avio_wb32(pb, spherical_mapping->bound_right);
1951  break;
1952  case AV_SPHERICAL_CUBEMAP:
1953  avio_wb32(pb, 20); /* size */
1954  ffio_wfourcc(pb, "cbmp");
1955  avio_wb32(pb, 0); /* version = 0 & flags = 0 */
1956  avio_wb32(pb, 0); /* layout */
1957  avio_wb32(pb, spherical_mapping->padding); /* padding */
1958  break;
1959  }
1960  update_size(pb, proj_pos);
1961 
1962  return update_size(pb, sv3d_pos);
1963 }
1964 
1966 {
1967  uint8_t buf[ISOM_DVCC_DVVC_SIZE];
1968 
1969  avio_wb32(pb, 32); /* size = 8 + 24 */
1970  if (dovi->dv_profile > 10)
1971  ffio_wfourcc(pb, "dvwC");
1972  else if (dovi->dv_profile > 7)
1973  ffio_wfourcc(pb, "dvvC");
1974  else
1975  ffio_wfourcc(pb, "dvcC");
1976 
1977  ff_isom_put_dvcc_dvvc(s, buf, dovi);
1978  avio_write(pb, buf, sizeof(buf));
1979 
1980  return 32; /* 8 + 24 */
1981 }
1982 
1983 static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
1984 {
1985  avio_wb32(pb, 40);
1986  ffio_wfourcc(pb, "clap");
1987  avio_wb32(pb, track->par->width); /* apertureWidth_N */
1988  avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
1989  avio_wb32(pb, track->height); /* apertureHeight_N */
1990  avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
1991  avio_wb32(pb, 0); /* horizOff_N (= 0) */
1992  avio_wb32(pb, 1); /* horizOff_D (= 1) */
1993  avio_wb32(pb, 0); /* vertOff_N (= 0) */
1994  avio_wb32(pb, 1); /* vertOff_D (= 1) */
1995  return 40;
1996 }
1997 
1998 static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
1999 {
2000  AVRational sar;
2001  av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
2002  track->par->sample_aspect_ratio.den, INT_MAX);
2003 
2004  avio_wb32(pb, 16);
2005  ffio_wfourcc(pb, "pasp");
2006  avio_wb32(pb, sar.num);
2007  avio_wb32(pb, sar.den);
2008  return 16;
2009 }
2010 
2011 static int mov_write_gama_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track, double gamma)
2012 {
2013  uint32_t gama = 0;
2014  if (gamma <= 0.0) {
2015  gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
2016  }
2017  av_log(s, AV_LOG_DEBUG, "gamma value %g\n", gamma);
2018 
2019  if (gamma > 1e-6) {
2020  gama = (uint32_t)lrint((double)(1<<16) * gamma);
2021  av_log(s, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
2022 
2023  av_assert0(track->mode == MODE_MOV);
2024  avio_wb32(pb, 12);
2025  ffio_wfourcc(pb, "gama");
2026  avio_wb32(pb, gama);
2027  return 12;
2028  } else {
2029  av_log(s, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
2030  }
2031  return 0;
2032 }
2033 
2034 static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track, int prefer_icc)
2035 {
2036  int64_t pos = avio_tell(pb);
2037 
2038  // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
2039  // Ref (MP4): ISO/IEC 14496-12:2012
2040 
2041  const uint8_t *icc_profile;
2042  size_t icc_profile_size;
2043 
2044  if (prefer_icc) {
2045  icc_profile = av_stream_get_side_data(track->st, AV_PKT_DATA_ICC_PROFILE, &icc_profile_size);
2046 
2047  if (icc_profile) {
2048  avio_wb32(pb, 12 + icc_profile_size);
2049  ffio_wfourcc(pb, "colr");
2050  ffio_wfourcc(pb, "prof");
2051  avio_write(pb, icc_profile, icc_profile_size);
2052  return 12 + icc_profile_size;
2053  }
2054  else {
2055  av_log(NULL, AV_LOG_INFO, "no ICC profile found, will write nclx/nclc colour info instead\n");
2056  }
2057  }
2058 
2059  /* We should only ever be called for MOV, MP4 and AVIF. */
2060  av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4 ||
2061  track->mode == MODE_AVIF);
2062 
2063  avio_wb32(pb, 0); /* size */
2064  ffio_wfourcc(pb, "colr");
2065  if (track->mode == MODE_MP4 || track->mode == MODE_AVIF)
2066  ffio_wfourcc(pb, "nclx");
2067  else
2068  ffio_wfourcc(pb, "nclc");
2069  // Do not try to guess the color info if it is AVCOL_PRI_UNSPECIFIED.
2070  // e.g., Dolby Vision for Apple devices should be set to AVCOL_PRI_UNSPECIFIED. See
2071  // https://developer.apple.com/av-foundation/High-Dynamic-Range-Metadata-for-Apple-Devices.pdf
2072  avio_wb16(pb, track->par->color_primaries);
2073  avio_wb16(pb, track->par->color_trc);
2074  avio_wb16(pb, track->par->color_space);
2075  if (track->mode == MODE_MP4 || track->mode == MODE_AVIF) {
2076  int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
2077  avio_w8(pb, full_range << 7);
2078  }
2079 
2080  return update_size(pb, pos);
2081 }
2082 
2083 static int mov_write_clli_tag(AVIOContext *pb, MOVTrack *track)
2084 {
2085  const uint8_t *side_data;
2086  const AVContentLightMetadata *content_light_metadata;
2087 
2089  if (!side_data) {
2090  return 0;
2091  }
2092  content_light_metadata = (const AVContentLightMetadata*)side_data;
2093 
2094  avio_wb32(pb, 12); // size
2095  ffio_wfourcc(pb, "clli");
2096  avio_wb16(pb, content_light_metadata->MaxCLL);
2097  avio_wb16(pb, content_light_metadata->MaxFALL);
2098  return 12;
2099 }
2100 
2101 static inline int64_t rescale_mdcv(AVRational q, int b)
2102 {
2103  return av_rescale(q.num, b, q.den);
2104 }
2105 
2106 static int mov_write_mdcv_tag(AVIOContext *pb, MOVTrack *track)
2107 {
2108  const int chroma_den = 50000;
2109  const int luma_den = 10000;
2110  const uint8_t *side_data;
2111  const AVMasteringDisplayMetadata *metadata;
2112 
2114  metadata = (const AVMasteringDisplayMetadata*)side_data;
2115  if (!metadata || !metadata->has_primaries || !metadata->has_luminance) {
2116  return 0;
2117  }
2118 
2119  avio_wb32(pb, 32); // size
2120  ffio_wfourcc(pb, "mdcv");
2121  avio_wb16(pb, rescale_mdcv(metadata->display_primaries[1][0], chroma_den));
2122  avio_wb16(pb, rescale_mdcv(metadata->display_primaries[1][1], chroma_den));
2123  avio_wb16(pb, rescale_mdcv(metadata->display_primaries[2][0], chroma_den));
2124  avio_wb16(pb, rescale_mdcv(metadata->display_primaries[2][1], chroma_den));
2125  avio_wb16(pb, rescale_mdcv(metadata->display_primaries[0][0], chroma_den));
2126  avio_wb16(pb, rescale_mdcv(metadata->display_primaries[0][1], chroma_den));
2127  avio_wb16(pb, rescale_mdcv(metadata->white_point[0], chroma_den));
2128  avio_wb16(pb, rescale_mdcv(metadata->white_point[1], chroma_den));
2129  avio_wb32(pb, rescale_mdcv(metadata->max_luminance, luma_den));
2130  avio_wb32(pb, rescale_mdcv(metadata->min_luminance, luma_den));
2131  return 32;
2132 }
2133 
2134 static void find_compressor(char * compressor_name, int len, MOVTrack *track)
2135 {
2136  AVDictionaryEntry *encoder;
2137  int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
2138  || (track->par->width == 1440 && track->par->height == 1080)
2139  || (track->par->width == 1920 && track->par->height == 1080);
2140 
2141  if ((track->mode == MODE_AVIF ||
2142  track->mode == MODE_MOV ||
2143  track->mode == MODE_MP4) &&
2144  (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
2145  av_strlcpy(compressor_name, encoder->value, 32);
2146  } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
2148  AVStream *st = track->st;
2149  int rate = defined_frame_rate(NULL, st);
2150  av_strlcatf(compressor_name, len, "XDCAM");
2151  if (track->par->format == AV_PIX_FMT_YUV422P) {
2152  av_strlcatf(compressor_name, len, " HD422");
2153  } else if(track->par->width == 1440) {
2154  av_strlcatf(compressor_name, len, " HD");
2155  } else
2156  av_strlcatf(compressor_name, len, " EX");
2157 
2158  av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
2159 
2160  av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
2161  }
2162 }
2163 
2165 {
2166  int64_t pos = avio_tell(pb);
2167  // Write sane defaults:
2168  // all_ref_pics_intra = 0 : all samples can use any type of reference.
2169  // intra_pred_used = 1 : intra prediction may or may not be used.
2170  // max_ref_per_pic = 15 : reserved value to indicate that any number of
2171  // reference images can be used.
2172  uint8_t ccstValue = (0 << 7) | /* all_ref_pics_intra */
2173  (1 << 6) | /* intra_pred_used */
2174  (15 << 2); /* max_ref_per_pic */
2175  avio_wb32(pb, 0); /* size */
2176  ffio_wfourcc(pb, "ccst");
2177  avio_wb32(pb, 0); /* Version & flags */
2178  avio_w8(pb, ccstValue);
2179  avio_wb24(pb, 0); /* reserved */
2180  return update_size(pb, pos);
2181 }
2182 
2183 static int mov_write_aux_tag(AVIOContext *pb, const char *aux_type)
2184 {
2185  int64_t pos = avio_tell(pb);
2186  avio_wb32(pb, 0); /* size */
2187  ffio_wfourcc(pb, aux_type);
2188  avio_wb32(pb, 0); /* Version & flags */
2189  avio_write(pb, "urn:mpeg:mpegB:cicp:systems:auxiliary:alpha\0", 44);
2190  return update_size(pb, pos);
2191 }
2192 
2194 {
2195  int ret = AVERROR_BUG;
2196  int64_t pos = avio_tell(pb);
2197  char compressor_name[32] = { 0 };
2198  int avid = 0;
2199 
2200  int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
2201  || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
2202  || track->par->codec_id == AV_CODEC_ID_V308
2203  || track->par->codec_id == AV_CODEC_ID_V408
2204  || track->par->codec_id == AV_CODEC_ID_V410
2205  || track->par->codec_id == AV_CODEC_ID_V210);
2206 
2207  avio_wb32(pb, 0); /* size */
2208  if (mov->encryption_scheme != MOV_ENC_NONE) {
2209  ffio_wfourcc(pb, "encv");
2210  } else {
2211  avio_wl32(pb, track->tag); // store it byteswapped
2212  }
2213  avio_wb32(pb, 0); /* Reserved */
2214  avio_wb16(pb, 0); /* Reserved */
2215  avio_wb16(pb, 1); /* Data-reference index */
2216 
2217  if (uncompressed_ycbcr) {
2218  avio_wb16(pb, 2); /* Codec stream version */
2219  } else {
2220  avio_wb16(pb, 0); /* Codec stream version */
2221  }
2222  avio_wb16(pb, 0); /* Codec stream revision (=0) */
2223  if (track->mode == MODE_MOV) {
2224  ffio_wfourcc(pb, "FFMP"); /* Vendor */
2225  if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
2226  avio_wb32(pb, 0); /* Temporal Quality */
2227  avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
2228  } else {
2229  avio_wb32(pb, 0x200); /* Temporal Quality = normal */
2230  avio_wb32(pb, 0x200); /* Spatial Quality = normal */
2231  }
2232  } else {
2233  ffio_fill(pb, 0, 3 * 4); /* Reserved */
2234  }
2235  avio_wb16(pb, track->par->width); /* Video width */
2236  avio_wb16(pb, track->height); /* Video height */
2237  avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
2238  avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
2239  avio_wb32(pb, 0); /* Data size (= 0) */
2240  avio_wb16(pb, 1); /* Frame count (= 1) */
2241 
2242  find_compressor(compressor_name, 32, track);
2243  avio_w8(pb, strlen(compressor_name));
2244  avio_write(pb, compressor_name, 31);
2245 
2246  if (track->mode == MODE_MOV &&
2247  (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
2248  avio_wb16(pb, 0x18);
2249  else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
2250  avio_wb16(pb, track->par->bits_per_coded_sample |
2251  (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
2252  else
2253  avio_wb16(pb, 0x18); /* Reserved */
2254 
2255  if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
2256  int pal_size, i;
2257  avio_wb16(pb, 0); /* Color table ID */
2258  avio_wb32(pb, 0); /* Color table seed */
2259  avio_wb16(pb, 0x8000); /* Color table flags */
2260  if (track->par->bits_per_coded_sample < 0 || track->par->bits_per_coded_sample > 8)
2261  return AVERROR(EINVAL);
2262  pal_size = 1 << track->par->bits_per_coded_sample;
2263  avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
2264  for (i = 0; i < pal_size; i++) {
2265  uint32_t rgb = track->palette[i];
2266  uint16_t r = (rgb >> 16) & 0xff;
2267  uint16_t g = (rgb >> 8) & 0xff;
2268  uint16_t b = rgb & 0xff;
2269  avio_wb16(pb, 0);
2270  avio_wb16(pb, (r << 8) | r);
2271  avio_wb16(pb, (g << 8) | g);
2272  avio_wb16(pb, (b << 8) | b);
2273  }
2274  } else
2275  avio_wb16(pb, 0xffff); /* Reserved */
2276 
2277  if (track->tag == MKTAG('m','p','4','v'))
2278  mov_write_esds_tag(pb, track);
2279  else if (track->par->codec_id == AV_CODEC_ID_H263)
2280  mov_write_d263_tag(pb);
2281  else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
2282  track->par->codec_id == AV_CODEC_ID_SVQ3) {
2283  mov_write_extradata_tag(pb, track);
2284  avio_wb32(pb, 0);
2285  } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
2286  mov_write_avid_tag(pb, track);
2287  avid = 1;
2288  } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
2289  mov_write_hvcc_tag(pb, track);
2290  else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
2291  mov_write_avcc_tag(pb, track);
2292  if (track->mode == MODE_IPOD)
2294  } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
2295  mov_write_vpcc_tag(mov->fc, pb, track);
2296  } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
2297  mov_write_av1c_tag(pb, track);
2298  } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
2299  mov_write_dvc1_tag(pb, track);
2300  else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
2301  track->par->codec_id == AV_CODEC_ID_VP6A) {
2302  /* Don't write any potential extradata here - the cropping
2303  * is signalled via the normal width/height fields. */
2304  } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
2305  if (track->par->codec_tag == MKTAG('R','1','0','k'))
2306  mov_write_dpxe_tag(pb, track);
2307  } else if (track->vos_len > 0)
2308  mov_write_glbl_tag(pb, track);
2309 
2310  if (track->par->codec_id != AV_CODEC_ID_H264 &&
2311  track->par->codec_id != AV_CODEC_ID_MPEG4 &&
2312  track->par->codec_id != AV_CODEC_ID_DNXHD) {
2313  int field_order = track->par->field_order;
2314 
2315  if (field_order != AV_FIELD_UNKNOWN)
2316  mov_write_fiel_tag(pb, track, field_order);
2317  }
2318 
2319  if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
2320  if (track->mode == MODE_MOV)
2321  mov_write_gama_tag(s, pb, track, mov->gamma);
2322  else
2323  av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
2324  }
2325  if (track->mode == MODE_MOV || track->mode == MODE_MP4 || track->mode == MODE_AVIF) {
2326  int has_color_info = track->par->color_primaries != AVCOL_PRI_UNSPECIFIED &&
2327  track->par->color_trc != AVCOL_TRC_UNSPECIFIED &&
2329  if (has_color_info || mov->flags & FF_MOV_FLAG_WRITE_COLR ||
2331  int prefer_icc = mov->flags & FF_MOV_FLAG_PREFER_ICC || !has_color_info;
2332  mov_write_colr_tag(pb, track, prefer_icc);
2333  } else if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
2334  av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
2335  }
2336  }
2337  if (track->mode == MODE_MOV || track->mode == MODE_MP4) {
2338  mov_write_clli_tag(pb, track);
2339  mov_write_mdcv_tag(pb, track);
2340  }
2341 
2342  if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
2347 
2348  if (stereo_3d)
2349  mov_write_st3d_tag(s, pb, stereo_3d);
2350  if (spherical_mapping)
2351  mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
2352  if (dovi)
2353  mov_write_dvcc_dvvc_tag(s, pb, dovi);
2354  }
2355 
2356  if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
2357  mov_write_pasp_tag(pb, track);
2358  }
2359 
2360  if (uncompressed_ycbcr){
2361  mov_write_clap_tag(pb, track);
2362  }
2363 
2364  if (mov->encryption_scheme != MOV_ENC_NONE) {
2365  ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
2366  }
2367 
2368  if (mov->write_btrt &&
2369  ((ret = mov_write_btrt_tag(pb, track)) < 0))
2370  return ret;
2371 
2372  /* extra padding for avid stsd */
2373  /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
2374  if (avid)
2375  avio_wb32(pb, 0);
2376 
2377  if (track->mode == MODE_AVIF) {
2378  mov_write_ccst_tag(pb);
2379  if (s->nb_streams > 0 && track == &mov->tracks[1])
2380  mov_write_aux_tag(pb, "auxi");
2381  }
2382 
2383  return update_size(pb, pos);
2384 }
2385 
2386 static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
2387 {
2388  int64_t pos = avio_tell(pb);
2389  avio_wb32(pb, 0); /* size */
2390  ffio_wfourcc(pb, "rtp ");
2391  avio_wb32(pb, 0); /* Reserved */
2392  avio_wb16(pb, 0); /* Reserved */
2393  avio_wb16(pb, 1); /* Data-reference index */
2394 
2395  avio_wb16(pb, 1); /* Hint track version */
2396  avio_wb16(pb, 1); /* Highest compatible version */
2397  avio_wb32(pb, track->max_packet_size); /* Max packet size */
2398 
2399  avio_wb32(pb, 12); /* size */
2400  ffio_wfourcc(pb, "tims");
2401  avio_wb32(pb, track->timescale);
2402 
2403  return update_size(pb, pos);
2404 }
2405 
2406 static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
2407 {
2408  uint64_t str_size =strlen(reel_name);
2409  int64_t pos = avio_tell(pb);
2410 
2411  if (str_size >= UINT16_MAX){
2412  av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
2413  avio_wb16(pb, 0);
2414  return AVERROR(EINVAL);
2415  }
2416 
2417  avio_wb32(pb, 0); /* size */
2418  ffio_wfourcc(pb, "name"); /* Data format */
2419  avio_wb16(pb, str_size); /* string size */
2420  avio_wb16(pb, track->language); /* langcode */
2421  avio_write(pb, reel_name, str_size); /* reel name */
2422  return update_size(pb,pos);
2423 }
2424 
2425 static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
2426 {
2427  int64_t pos = avio_tell(pb);
2428 #if 1
2429  int frame_duration;
2430  int nb_frames;
2431  AVDictionaryEntry *t = NULL;
2432 
2433  if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
2434  av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
2435  return AVERROR(EINVAL);
2436  } else {
2437  frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
2438  nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
2439  }
2440 
2441  if (nb_frames > 255) {
2442  av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
2443  return AVERROR(EINVAL);
2444  }
2445 
2446  avio_wb32(pb, 0); /* size */
2447  ffio_wfourcc(pb, "tmcd"); /* Data format */
2448  avio_wb32(pb, 0); /* Reserved */
2449  avio_wb32(pb, 1); /* Data reference index */
2450  avio_wb32(pb, 0); /* Flags */
2451  avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
2452  avio_wb32(pb, track->timescale); /* Timescale */
2453  avio_wb32(pb, frame_duration); /* Frame duration */
2454  avio_w8(pb, nb_frames); /* Number of frames */
2455  avio_w8(pb, 0); /* Reserved */
2456 
2457  t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
2458  if (t && utf8len(t->value) && track->mode != MODE_MP4)
2459  mov_write_source_reference_tag(pb, track, t->value);
2460  else
2461  avio_wb16(pb, 0); /* zero size */
2462 #else
2463 
2464  avio_wb32(pb, 0); /* size */
2465  ffio_wfourcc(pb, "tmcd"); /* Data format */
2466  avio_wb32(pb, 0); /* Reserved */
2467  avio_wb32(pb, 1); /* Data reference index */
2468  if (track->par->extradata_size)
2469  avio_write(pb, track->par->extradata, track->par->extradata_size);
2470 #endif
2471  return update_size(pb, pos);
2472 }
2473 
2474 static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
2475 {
2476  int64_t pos = avio_tell(pb);
2477  avio_wb32(pb, 0); /* size */
2478  ffio_wfourcc(pb, "gpmd");
2479  avio_wb32(pb, 0); /* Reserved */
2480  avio_wb16(pb, 0); /* Reserved */
2481  avio_wb16(pb, 1); /* Data-reference index */
2482  avio_wb32(pb, 0); /* Reserved */
2483  return update_size(pb, pos);
2484 }
2485 
2487 {
2488  int64_t pos = avio_tell(pb);
2489  int ret = 0;
2490  avio_wb32(pb, 0); /* size */
2491  ffio_wfourcc(pb, "stsd");
2492  avio_wb32(pb, 0); /* version & flags */
2493  avio_wb32(pb, 1); /* entry count */
2494  if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
2495  ret = mov_write_video_tag(s, pb, mov, track);
2496  else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
2497  ret = mov_write_audio_tag(s, pb, mov, track);
2498  else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
2499  ret = mov_write_subtitle_tag(s, pb, track);
2500  else if (track->par->codec_tag == MKTAG('r','t','p',' '))
2501  ret = mov_write_rtp_tag(pb, track);
2502  else if (track->par->codec_tag == MKTAG('t','m','c','d'))
2503  ret = mov_write_tmcd_tag(pb, track);
2504  else if (track->par->codec_tag == MKTAG('g','p','m','d'))
2505  ret = mov_write_gpmd_tag(pb, track);
2506 
2507  if (ret < 0)
2508  return ret;
2509 
2510  return update_size(pb, pos);
2511 }
2512 
2514 {
2515  MOVMuxContext *mov = s->priv_data;
2516  MOVCtts *ctts_entries;
2517  uint32_t entries = 0;
2518  uint32_t atom_size;
2519  int i;
2520 
2521  ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
2522  if (!ctts_entries)
2523  return AVERROR(ENOMEM);
2524  ctts_entries[0].count = 1;
2525  ctts_entries[0].duration = track->cluster[0].cts;
2526  for (i = 1; i < track->entry; i++) {
2527  if (track->cluster[i].cts == ctts_entries[entries].duration) {
2528  ctts_entries[entries].count++; /* compress */
2529  } else {
2530  entries++;
2531  ctts_entries[entries].duration = track->cluster[i].cts;
2532  ctts_entries[entries].count = 1;
2533  }
2534  }
2535  entries++; /* last one */
2536  atom_size = 16 + (entries * 8);
2537  avio_wb32(pb, atom_size); /* size */
2538  ffio_wfourcc(pb, "ctts");
2540  avio_w8(pb, 1); /* version */
2541  else
2542  avio_w8(pb, 0); /* version */
2543  avio_wb24(pb, 0); /* flags */
2544  avio_wb32(pb, entries); /* entry count */
2545  for (i = 0; i < entries; i++) {
2546  avio_wb32(pb, ctts_entries[i].count);
2547  avio_wb32(pb, ctts_entries[i].duration);
2548  }
2549  av_free(ctts_entries);
2550  return atom_size;
2551 }
2552 
2553 /* Time to sample atom */
2554 static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
2555 {
2556  MOVStts *stts_entries = NULL;
2557  uint32_t entries = -1;
2558  uint32_t atom_size;
2559  int i;
2560 
2561  if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
2562  stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
2563  if (!stts_entries)
2564  return AVERROR(ENOMEM);
2565  stts_entries[0].count = track->sample_count;
2566  stts_entries[0].duration = 1;
2567  entries = 1;
2568  } else {
2569  if (track->entry) {
2570  stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
2571  if (!stts_entries)
2572  return AVERROR(ENOMEM);
2573  }
2574  for (i = 0; i < track->entry; i++) {
2575  int duration = get_cluster_duration(track, i);
2576  if (i && duration == stts_entries[entries].duration) {
2577  stts_entries[entries].count++; /* compress */
2578  } else {
2579  entries++;
2580  stts_entries[entries].duration = duration;
2581  stts_entries[entries].count = 1;
2582  }
2583  }
2584  entries++; /* last one */
2585  }
2586  atom_size = 16 + (entries * 8);
2587  avio_wb32(pb, atom_size); /* size */
2588  ffio_wfourcc(pb, "stts");
2589  avio_wb32(pb, 0); /* version & flags */
2590  avio_wb32(pb, entries); /* entry count */
2591  for (i = 0; i < entries; i++) {
2592  avio_wb32(pb, stts_entries[i].count);
2593  avio_wb32(pb, stts_entries[i].duration);
2594  }
2595  av_free(stts_entries);
2596  return atom_size;
2597 }
2598 
2600 {
2601  avio_wb32(pb, 28); /* size */
2602  ffio_wfourcc(pb, "dref");
2603  avio_wb32(pb, 0); /* version & flags */
2604  avio_wb32(pb, 1); /* entry count */
2605 
2606  avio_wb32(pb, 0xc); /* size */
2607  //FIXME add the alis and rsrc atom
2608  ffio_wfourcc(pb, "url ");
2609  avio_wb32(pb, 1); /* version & flags */
2610 
2611  return 28;
2612 }
2613 
2615 {
2616  struct sgpd_entry {
2617  int count;
2618  int16_t roll_distance;
2619  int group_description_index;
2620  };
2621 
2622  struct sgpd_entry *sgpd_entries = NULL;
2623  int entries = -1;
2624  int group = 0;
2625  int i, j;
2626 
2627  const int OPUS_SEEK_PREROLL_MS = 80;
2628  int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
2629  (AVRational){1, 1000},
2630  (AVRational){1, 48000});
2631 
2632  if (!track->entry)
2633  return 0;
2634 
2635  sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
2636  if (!sgpd_entries)
2637  return AVERROR(ENOMEM);
2638 
2640 
2641  if (track->par->codec_id == AV_CODEC_ID_OPUS) {
2642  for (i = 0; i < track->entry; i++) {
2643  int roll_samples_remaining = roll_samples;
2644  int distance = 0;
2645  for (j = i - 1; j >= 0; j--) {
2646  roll_samples_remaining -= get_cluster_duration(track, j);
2647  distance++;
2648  if (roll_samples_remaining <= 0)
2649  break;
2650  }
2651  /* We don't have enough preceeding samples to compute a valid
2652  roll_distance here, so this sample can't be independently
2653  decoded. */
2654  if (roll_samples_remaining > 0)
2655  distance = 0;
2656  /* Verify distance is a maximum of 32 (2.5ms) packets. */
2657  if (distance > 32)
2658  return AVERROR_INVALIDDATA;
2659  if (i && distance == sgpd_entries[entries].roll_distance) {
2660  sgpd_entries[entries].count++;
2661  } else {
2662  entries++;
2663  sgpd_entries[entries].count = 1;
2664  sgpd_entries[entries].roll_distance = distance;
2665  sgpd_entries[entries].group_description_index = distance ? ++group : 0;
2666  }
2667  }
2668  } else {
2669  entries++;
2670  sgpd_entries[entries].count = track->sample_count;
2671  sgpd_entries[entries].roll_distance = 1;
2672  sgpd_entries[entries].group_description_index = ++group;
2673  }
2674  entries++;
2675 
2676  if (!group) {
2677  av_free(sgpd_entries);
2678  return 0;
2679  }
2680 
2681  /* Write sgpd tag */
2682  avio_wb32(pb, 24 + (group * 2)); /* size */
2683  ffio_wfourcc(pb, "sgpd");
2684  avio_wb32(pb, 1 << 24); /* fullbox */
2685  ffio_wfourcc(pb, "roll");
2686  avio_wb32(pb, 2); /* default_length */
2687  avio_wb32(pb, group); /* entry_count */
2688  for (i = 0; i < entries; i++) {
2689  if (sgpd_entries[i].group_description_index) {
2690  avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
2691  }
2692  }
2693 
2694  /* Write sbgp tag */
2695  avio_wb32(pb, 20 + (entries * 8)); /* size */
2696  ffio_wfourcc(pb, "sbgp");
2697  avio_wb32(pb, 0); /* fullbox */
2698  ffio_wfourcc(pb, "roll");
2699  avio_wb32(pb, entries); /* entry_count */
2700  for (i = 0; i < entries; i++) {
2701  avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
2702  avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
2703  }
2704 
2705  av_free(sgpd_entries);
2706  return 0;
2707 }
2708 
2710 {
2711  int64_t pos = avio_tell(pb);
2712  int ret = 0;
2713 
2714  avio_wb32(pb, 0); /* size */
2715  ffio_wfourcc(pb, "stbl");
2716  if ((ret = mov_write_stsd_tag(s, pb, mov, track)) < 0)
2717  return ret;
2718  mov_write_stts_tag(pb, track);
2719  if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
2720  track->par->codec_id == AV_CODEC_ID_TRUEHD ||
2722  track->par->codec_tag == MKTAG('r','t','p',' ')) &&
2723  track->has_keyframes && track->has_keyframes < track->entry)
2724  mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
2725  if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
2726  mov_write_sdtp_tag(pb, track);
2727  if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
2729  if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
2730  track->flags & MOV_TRACK_CTTS && track->entry) {
2731 
2732  if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
2733  return ret;
2734  }
2735  mov_write_stsc_tag(pb, track);
2736  mov_write_stsz_tag(pb, track);
2737  mov_write_stco_tag(pb, track);
2738  if (track->cenc.aes_ctr) {
2739  ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
2740  }
2741  if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
2742  mov_preroll_write_stbl_atoms(pb, track);
2743  }
2744  return update_size(pb, pos);
2745 }
2746 
2748 {
2749  int64_t pos = avio_tell(pb);
2750  avio_wb32(pb, 0); /* size */
2751  ffio_wfourcc(pb, "dinf");
2752  mov_write_dref_tag(pb);
2753  return update_size(pb, pos);
2754 }
2755 
2757 {
2758  avio_wb32(pb, 12);
2759  ffio_wfourcc(pb, "nmhd");
2760  avio_wb32(pb, 0);
2761  return 12;
2762 }
2763 
2765 {
2766  avio_wb32(pb, 12);
2767  ffio_wfourcc(pb, "sthd");
2768  avio_wb32(pb, 0);
2769  return 12;
2770 }
2771 
2772 static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
2773 {
2774  int64_t pos = avio_tell(pb);
2775  const char *font = "Lucida Grande";
2776  avio_wb32(pb, 0); /* size */
2777  ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
2778  avio_wb32(pb, 0); /* version & flags */
2779  avio_wb16(pb, 0); /* text font */
2780  avio_wb16(pb, 0); /* text face */
2781  avio_wb16(pb, 12); /* text size */
2782  avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
2783  avio_wb16(pb, 0x0000); /* text color (red) */
2784  avio_wb16(pb, 0x0000); /* text color (green) */
2785  avio_wb16(pb, 0x0000); /* text color (blue) */
2786  avio_wb16(pb, 0xffff); /* background color (red) */
2787  avio_wb16(pb, 0xffff); /* background color (green) */
2788  avio_wb16(pb, 0xffff); /* background color (blue) */
2789  avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
2790  avio_write(pb, font, strlen(font)); /* font name */
2791  return update_size(pb, pos);
2792 }
2793 
2794 static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
2795 {
2796  int64_t pos = avio_tell(pb);
2797  avio_wb32(pb, 0); /* size */
2798  ffio_wfourcc(pb, "gmhd");
2799  avio_wb32(pb, 0x18); /* gmin size */
2800  ffio_wfourcc(pb, "gmin");/* generic media info */
2801  avio_wb32(pb, 0); /* version & flags */
2802  avio_wb16(pb, 0x40); /* graphics mode = */
2803  avio_wb16(pb, 0x8000); /* opColor (r?) */
2804  avio_wb16(pb, 0x8000); /* opColor (g?) */
2805  avio_wb16(pb, 0x8000); /* opColor (b?) */
2806  avio_wb16(pb, 0); /* balance */
2807  avio_wb16(pb, 0); /* reserved */
2808 
2809  /*
2810  * This special text atom is required for
2811  * Apple Quicktime chapters. The contents
2812  * don't appear to be documented, so the
2813  * bytes are copied verbatim.
2814  */
2815  if (track->tag != MKTAG('c','6','0','8')) {
2816  avio_wb32(pb, 0x2C); /* size */
2817  ffio_wfourcc(pb, "text");
2818  avio_wb16(pb, 0x01);
2819  avio_wb32(pb, 0x00);
2820  avio_wb32(pb, 0x00);
2821  avio_wb32(pb, 0x00);
2822  avio_wb32(pb, 0x01);
2823  avio_wb32(pb, 0x00);
2824  avio_wb32(pb, 0x00);
2825  avio_wb32(pb, 0x00);
2826  avio_wb32(pb, 0x00004000);
2827  avio_wb16(pb, 0x0000);
2828  }
2829 
2830  if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2831  int64_t tmcd_pos = avio_tell(pb);
2832  avio_wb32(pb, 0); /* size */
2833  ffio_wfourcc(pb, "tmcd");
2834  mov_write_tcmi_tag(pb, track);
2835  update_size(pb, tmcd_pos);
2836  } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2837  int64_t gpmd_pos = avio_tell(pb);
2838  avio_wb32(pb, 0); /* size */
2839  ffio_wfourcc(pb, "gpmd");
2840  avio_wb32(pb, 0); /* version */
2841  update_size(pb, gpmd_pos);
2842  }
2843  return update_size(pb, pos);
2844 }
2845 
2847 {
2848  avio_wb32(pb, 16); /* size */
2849  ffio_wfourcc(pb, "smhd");
2850  avio_wb32(pb, 0); /* version & flags */
2851  avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
2852  avio_wb16(pb, 0); /* reserved */
2853  return 16;
2854 }
2855 
2857 {
2858  avio_wb32(pb, 0x14); /* size (always 0x14) */
2859  ffio_wfourcc(pb, "vmhd");
2860  avio_wb32(pb, 0x01); /* version & flags */
2861  avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
2862  return 0x14;
2863 }
2864 
2865 static int is_clcp_track(MOVTrack *track)
2866 {
2867  return track->tag == MKTAG('c','7','0','8') ||
2868  track->tag == MKTAG('c','6','0','8');
2869 }
2870 
2872 {
2873  MOVMuxContext *mov = s->priv_data;
2874  const char *hdlr, *descr = NULL, *hdlr_type = NULL;
2875  int64_t pos = avio_tell(pb);
2876  size_t descr_len;
2877 
2878  hdlr = "dhlr";
2879  hdlr_type = "url ";
2880  descr = "DataHandler";
2881 
2882  if (track) {
2883  hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
2884  if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
2885  if (track->mode == MODE_AVIF) {
2886  hdlr_type = (track == &mov->tracks[0]) ? "pict" : "auxv";
2887  descr = "PictureHandler";
2888  } else {
2889  hdlr_type = "vide";
2890  descr = "VideoHandler";
2891  }
2892  } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
2893  hdlr_type = "soun";
2894  descr = "SoundHandler";
2895  } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2896  if (is_clcp_track(track)) {
2897  hdlr_type = "clcp";
2898  descr = "ClosedCaptionHandler";
2899  } else {
2900  if (track->tag == MKTAG('t','x','3','g')) {
2901  hdlr_type = "sbtl";
2902  } else if (track->tag == MKTAG('m','p','4','s')) {
2903  hdlr_type = "subp";
2904  } else if (track->tag == MOV_MP4_TTML_TAG) {
2905  hdlr_type = "subt";
2906  } else {
2907  hdlr_type = "text";
2908  }
2909  descr = "SubtitleHandler";
2910  }
2911  } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
2912  hdlr_type = "hint";
2913  descr = "HintHandler";
2914  } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
2915  hdlr_type = "tmcd";
2916  descr = "TimeCodeHandler";
2917  } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
2918  hdlr_type = "meta";
2919  descr = "GoPro MET"; // GoPro Metadata
2920  } else {
2922  "Unknown hdlr_type for %s, writing dummy values\n",
2923  av_fourcc2str(track->par->codec_tag));
2924  }
2925  if (track->st) {
2926  // hdlr.name is used by some players to identify the content title
2927  // of the track. So if an alternate handler description is
2928  // specified, use it.
2929  AVDictionaryEntry *t;
2930  t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
2931  if (t && utf8len(t->value))
2932  descr = t->value;
2933  }
2934  }
2935 
2936  if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
2937  descr = "";
2938 
2939  avio_wb32(pb, 0); /* size */
2940  ffio_wfourcc(pb, "hdlr");
2941  avio_wb32(pb, 0); /* Version & flags */
2942  avio_write(pb, hdlr, 4); /* handler */
2943  ffio_wfourcc(pb, hdlr_type); /* handler type */
2944  avio_wb32(pb, 0); /* reserved */
2945  avio_wb32(pb, 0); /* reserved */
2946  avio_wb32(pb, 0); /* reserved */
2947  descr_len = strlen(descr);
2948  if (!track || track->mode == MODE_MOV)
2949  avio_w8(pb, descr_len); /* pascal string */
2950  avio_write(pb, descr, descr_len); /* handler description */
2951  if (track && track->mode != MODE_MOV)
2952  avio_w8(pb, 0); /* c string */
2953  return update_size(pb, pos);
2954 }
2955 
2956 static int mov_write_pitm_tag(AVIOContext *pb, int item_id)
2957 {
2958  int64_t pos = avio_tell(pb);
2959  avio_wb32(pb, 0); /* size */
2960  ffio_wfourcc(pb, "pitm");
2961  avio_wb32(pb, 0); /* Version & flags */
2962  avio_wb16(pb, item_id); /* item_id */
2963  return update_size(pb, pos);
2964 }
2965 
2967 {
2968  int64_t pos = avio_tell(pb);
2969  avio_wb32(pb, 0); /* size */
2970  ffio_wfourcc(pb, "iloc");
2971  avio_wb32(pb, 0); /* Version & flags */
2972  avio_w8(pb, (4 << 4) + 4); /* offset_size(4) and length_size(4) */
2973  avio_w8(pb, 0); /* base_offset_size(4) and reserved(4) */
2974  avio_wb16(pb, s->nb_streams); /* item_count */
2975 
2976  for (int i = 0; i < s->nb_streams; i++) {
2977  avio_wb16(pb, i + 1); /* item_id */
2978  avio_wb16(pb, 0); /* data_reference_index */
2979  avio_wb16(pb, 1); /* extent_count */
2980  mov->avif_extent_pos[i] = avio_tell(pb);
2981  avio_wb32(pb, 0); /* extent_offset (written later) */
2982  // For animated AVIF, we simply write the first packet's size.
2983  avio_wb32(pb, mov->avif_extent_length[i]); /* extent_length */
2984  }
2985 
2986  return update_size(pb, pos);
2987 }
2988 
2990 {
2991  int64_t iinf_pos = avio_tell(pb);
2992  avio_wb32(pb, 0); /* size */
2993  ffio_wfourcc(pb, "iinf");
2994  avio_wb32(pb, 0); /* Version & flags */
2995  avio_wb16(pb, s->nb_streams); /* entry_count */
2996 
2997  for (int i = 0; i < s->nb_streams; i++) {
2998  int64_t infe_pos = avio_tell(pb);
2999  avio_wb32(pb, 0); /* size */
3000  ffio_wfourcc(pb, "infe");
3001  avio_w8(pb, 0x2); /* Version */
3002  avio_wb24(pb, 0); /* flags */
3003  avio_wb16(pb, i + 1); /* item_id */
3004  avio_wb16(pb, 0); /* item_protection_index */
3005  avio_write(pb, "av01", 4); /* item_type */
3006  avio_write(pb, !i ? "Color\0" : "Alpha\0", 6); /* item_name */
3007  update_size(pb, infe_pos);
3008  }
3009 
3010  return update_size(pb, iinf_pos);
3011 }
3012 
3013 
3015 {
3016  int64_t auxl_pos;
3017  int64_t iref_pos = avio_tell(pb);
3018  avio_wb32(pb, 0); /* size */
3019  ffio_wfourcc(pb, "iref");
3020  avio_wb32(pb, 0); /* Version & flags */
3021 
3022  auxl_pos = avio_tell(pb);
3023  avio_wb32(pb, 0); /* size */
3024  ffio_wfourcc(pb, "auxl");
3025  avio_wb16(pb, 2); /* from_item_ID */
3026  avio_wb16(pb, 1); /* reference_count */
3027  avio_wb16(pb, 1); /* to_item_ID */
3028  update_size(pb, auxl_pos);
3029 
3030  return update_size(pb, iref_pos);
3031 }
3032 
3034  int stream_index)
3035 {
3036  int64_t pos = avio_tell(pb);
3037  avio_wb32(pb, 0); /* size */
3038  ffio_wfourcc(pb, "ispe");
3039  avio_wb32(pb, 0); /* Version & flags */
3040  avio_wb32(pb, s->streams[stream_index]->codecpar->width); /* image_width */
3041  avio_wb32(pb, s->streams[stream_index]->codecpar->height); /* image_height */
3042  return update_size(pb, pos);
3043 }
3044 
3046  int stream_index)
3047 {
3048  int64_t pos = avio_tell(pb);
3049  const AVPixFmtDescriptor *pixdesc =
3050  av_pix_fmt_desc_get(s->streams[stream_index]->codecpar->format);
3051  avio_wb32(pb, 0); /* size */
3052  ffio_wfourcc(pb, "pixi");
3053  avio_wb32(pb, 0); /* Version & flags */
3054  avio_w8(pb, pixdesc->nb_components); /* num_channels */
3055  for (int i = 0; i < pixdesc->nb_components; ++i) {
3056  avio_w8(pb, pixdesc->comp[i].depth); /* bits_per_channel */
3057  }
3058  return update_size(pb, pos);
3059 }
3060 
3062 {
3063  int64_t pos = avio_tell(pb);
3064  avio_wb32(pb, 0); /* size */
3065  ffio_wfourcc(pb, "ipco");
3066  for (int i = 0; i < s->nb_streams; i++) {
3067  mov_write_ispe_tag(pb, mov, s, i);
3068  mov_write_pixi_tag(pb, mov, s, i);
3069  mov_write_av1c_tag(pb, &mov->tracks[i]);
3070  if (!i)
3071  mov_write_colr_tag(pb, &mov->tracks[0], 0);
3072  else
3073  mov_write_aux_tag(pb, "auxC");
3074  }
3075  return update_size(pb, pos);
3076 }
3077 
3079 {
3080  int64_t pos = avio_tell(pb);
3081  avio_wb32(pb, 0); /* size */
3082  ffio_wfourcc(pb, "ipma");
3083  avio_wb32(pb, 0); /* Version & flags */
3084  avio_wb32(pb, s->nb_streams); /* entry_count */
3085 
3086  for (int i = 0, index = 1; i < s->nb_streams; i++) {
3087  avio_wb16(pb, i + 1); /* item_ID */
3088  avio_w8(pb, 4); /* association_count */
3089 
3090  // ispe association.
3091  avio_w8(pb, index++); /* essential and property_index */
3092  // pixi association.
3093  avio_w8(pb, index++); /* essential and property_index */
3094  // av1C association.
3095  avio_w8(pb, 0x80 | index++); /* essential and property_index */
3096  // colr/auxC association.
3097  avio_w8(pb, index++); /* essential and property_index */
3098  }
3099  return update_size(pb, pos);
3100 }
3101 
3103 {
3104  int64_t pos = avio_tell(pb);
3105  avio_wb32(pb, 0); /* size */
3106  ffio_wfourcc(pb, "iprp");
3107  mov_write_ipco_tag(pb, mov, s);
3108  mov_write_ipma_tag(pb, mov, s);
3109  return update_size(pb, pos);
3110 }
3111 
3113 {
3114  /* This atom must be present, but leaving the values at zero
3115  * seems harmless. */
3116  avio_wb32(pb, 28); /* size */
3117  ffio_wfourcc(pb, "hmhd");
3118  avio_wb32(pb, 0); /* version, flags */
3119  avio_wb16(pb, 0); /* maxPDUsize */
3120  avio_wb16(pb, 0); /* avgPDUsize */
3121  avio_wb32(pb, 0); /* maxbitrate */
3122  avio_wb32(pb, 0); /* avgbitrate */
3123  avio_wb32(pb, 0); /* reserved */
3124  return 28;
3125 }
3126 
3128 {
3129  int64_t pos = avio_tell(pb);
3130  int ret;
3131 
3132  avio_wb32(pb, 0); /* size */
3133  ffio_wfourcc(pb, "minf");
3134  if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
3135  mov_write_vmhd_tag(pb);
3136  else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
3137  mov_write_smhd_tag(pb);
3138  else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3139  if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
3140  mov_write_gmhd_tag(pb, track);
3141  } else if (track->tag == MOV_MP4_TTML_TAG) {
3142  mov_write_sthd_tag(pb);
3143  } else {
3144  mov_write_nmhd_tag(pb);
3145  }
3146  } else if (track->tag == MKTAG('r','t','p',' ')) {
3147  mov_write_hmhd_tag(pb);
3148  } else if (track->tag == MKTAG('t','m','c','d')) {
3149  if (track->mode != MODE_MOV)
3150  mov_write_nmhd_tag(pb);
3151  else
3152  mov_write_gmhd_tag(pb, track);
3153  } else if (track->tag == MKTAG('g','p','m','d')) {
3154  mov_write_gmhd_tag(pb, track);
3155  }
3156  if (track->mode == MODE_MOV) /* ISO 14496-12 8.4.3.1 specifies hdlr only within mdia or meta boxes */
3157  mov_write_hdlr_tag(s, pb, NULL);
3158  mov_write_dinf_tag(pb);
3159  if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
3160  return ret;
3161  return update_size(pb, pos);
3162 }
3163 
3164 static void get_pts_range(MOVMuxContext *mov, MOVTrack *track,
3165  int64_t *start, int64_t *end)
3166 {
3167  if (track->tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd) {
3168  // tmcd tracks gets track_duration set in mov_write_moov_tag from
3169  // another track's duration, while the end_pts may be left at zero.
3170  // Calculate the pts duration for that track instead.
3171  get_pts_range(mov, &mov->tracks[track->src_track], start, end);
3172  *start = av_rescale(*start, track->timescale,
3173  mov->tracks[track->src_track].timescale);
3174  *end = av_rescale(*end, track->timescale,
3175  mov->tracks[track->src_track].timescale);
3176  return;
3177  }
3178  if (track->end_pts != AV_NOPTS_VALUE &&
3179  track->start_dts != AV_NOPTS_VALUE &&
3180  track->start_cts != AV_NOPTS_VALUE) {
3181  *start = track->start_dts + track->start_cts;
3182  *end = track->end_pts;
3183  return;
3184  }
3185  *start = 0;
3186  *end = track->track_duration;
3187 }
3188 
3190 {
3191  int64_t start, end;
3192  get_pts_range(mov, track, &start, &end);
3193  return end - start;
3194 }
3195 
3196 // Calculate the actual duration of the track, after edits.
3197 // If it starts with a pts < 0, that is removed by the edit list.
3198 // If it starts with a pts > 0, the edit list adds a delay before that.
3199 // Thus, with edit lists enabled, the post-edit output of the file is
3200 // starting with pts=0.
3201 static int64_t calc_pts_duration(MOVMuxContext *mov, MOVTrack *track)
3202 {
3203  int64_t start, end;
3204  get_pts_range(mov, track, &start, &end);
3205  if (mov->use_editlist != 0)
3206  start = 0;
3207  return end - start;
3208 }
3209 
3211  MOVTrack *track)
3212 {
3213  int64_t duration = calc_samples_pts_duration(mov, track);
3214  int version = duration < INT32_MAX ? 0 : 1;
3215 
3216  if (track->mode == MODE_ISM)
3217  version = 1;
3218 
3219  (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
3220  ffio_wfourcc(pb, "mdhd");
3221  avio_w8(pb, version);
3222  avio_wb24(pb, 0); /* flags */
3223  if (version == 1) {
3224  avio_wb64(pb, track->time);
3225  avio_wb64(pb, track->time);
3226  } else {
3227  avio_wb32(pb, track->time); /* creation time */
3228  avio_wb32(pb, track->time); /* modification time */
3229  }
3230  avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
3231  if (!track->entry && mov->mode == MODE_ISM)
3232  (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
3233  else if (!track->entry)
3234  (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
3235  else
3236  (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration); /* duration */
3237  avio_wb16(pb, track->language); /* language */
3238  avio_wb16(pb, 0); /* reserved (quality) */
3239 
3240  if (version != 0 && track->mode == MODE_MOV) {
3242  "FATAL error, file duration too long for timebase, this file will not be\n"
3243  "playable with QuickTime. Choose a different timebase with "
3244  "-video_track_timescale or a different container format\n");
3245  }
3246 
3247  return 32;
3248 }
3249 
3251  MOVMuxContext *mov, MOVTrack *track)
3252 {
3253  int64_t pos = avio_tell(pb);
3254  int ret;
3255 
3256  avio_wb32(pb, 0); /* size */
3257  ffio_wfourcc(pb, "mdia");
3258  mov_write_mdhd_tag(pb, mov, track);
3259  mov_write_hdlr_tag(s, pb, track);
3260  if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
3261  return ret;
3262  return update_size(pb, pos);
3263 }
3264 
3265 /* transformation matrix
3266  |a b u|
3267  |c d v|
3268  |tx ty w| */
3269 static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
3270  int16_t d, int16_t tx, int16_t ty)
3271 {
3272  avio_wb32(pb, a << 16); /* 16.16 format */
3273  avio_wb32(pb, b << 16); /* 16.16 format */
3274  avio_wb32(pb, 0); /* u in 2.30 format */
3275  avio_wb32(pb, c << 16); /* 16.16 format */
3276  avio_wb32(pb, d << 16); /* 16.16 format */
3277  avio_wb32(pb, 0); /* v in 2.30 format */
3278  avio_wb32(pb, tx << 16); /* 16.16 format */
3279  avio_wb32(pb, ty << 16); /* 16.16 format */
3280  avio_wb32(pb, 1 << 30); /* w in 2.30 format */
3281 }
3282 
3284  MOVTrack *track, AVStream *st)
3285 {
3286  int64_t duration = av_rescale_rnd(calc_pts_duration(mov, track),
3287  mov->movie_timescale, track->timescale,
3288  AV_ROUND_UP);
3289  int version = duration < INT32_MAX ? 0 : 1;
3291  int group = 0;
3292 
3293  uint32_t *display_matrix = NULL;
3294  size_t display_matrix_size;
3295  int i;
3296 
3297  if (st) {
3298  if (mov->per_stream_grouping)
3299  group = st->index;
3300  else
3301  group = st->codecpar->codec_type;
3302 
3303  display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
3304  &display_matrix_size);
3305  if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
3306  display_matrix = NULL;
3307  }
3308 
3309  if (track->flags & MOV_TRACK_ENABLED)
3311 
3312  if (track->mode == MODE_ISM)
3313  version = 1;
3314 
3315  (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
3316  ffio_wfourcc(pb, "tkhd");
3317  avio_w8(pb, version);
3318  avio_wb24(pb, flags);
3319  if (version == 1) {
3320  avio_wb64(pb, track->time);
3321  avio_wb64(pb, track->time);
3322  } else {
3323  avio_wb32(pb, track->time); /* creation time */
3324  avio_wb32(pb, track->time); /* modification time */
3325  }
3326  avio_wb32(pb, track->track_id); /* track-id */
3327  avio_wb32(pb, 0); /* reserved */
3328  if (!track->entry && mov->mode == MODE_ISM)
3329  (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
3330  else if (!track->entry)
3331  (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
3332  else
3333  (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
3334 
3335  avio_wb32(pb, 0); /* reserved */
3336  avio_wb32(pb, 0); /* reserved */
3337  avio_wb16(pb, 0); /* layer */
3338  avio_wb16(pb, group); /* alternate group) */
3339  /* Volume, only for audio */
3340  if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
3341  avio_wb16(pb, 0x0100);
3342  else
3343  avio_wb16(pb, 0);
3344  avio_wb16(pb, 0); /* reserved */
3345 
3346  /* Matrix structure */
3347  if (display_matrix) {
3348  for (i = 0; i < 9; i++)
3349  avio_wb32(pb, display_matrix[i]);
3350  } else {
3351  write_matrix(pb, 1, 0, 0, 1, 0, 0);
3352  }
3353  /* Track width and height, for visual only */
3354  if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
3355  track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
3356  int64_t track_width_1616;
3357  if (track->mode == MODE_MOV || track->mode == MODE_AVIF) {
3358  track_width_1616 = track->par->width * 0x10000ULL;
3359  } else {
3360  track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
3361  track->par->width * 0x10000LL,
3362  st->sample_aspect_ratio.den);
3363  if (!track_width_1616 ||
3364  track->height != track->par->height ||
3365  track_width_1616 > UINT32_MAX)
3366  track_width_1616 = track->par->width * 0x10000ULL;
3367  }
3368  if (track_width_1616 > UINT32_MAX) {
3369  av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
3370  track_width_1616 = 0;
3371  }
3372  avio_wb32(pb, track_width_1616);
3373  if (track->height > 0xFFFF) {
3374  av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
3375  avio_wb32(pb, 0);
3376  } else
3377  avio_wb32(pb, track->height * 0x10000U);
3378  } else {
3379  avio_wb32(pb, 0);
3380  avio_wb32(pb, 0);
3381  }
3382  return 0x5c;
3383 }
3384 
3385 static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
3386 {
3388  track->par->sample_aspect_ratio.den);
3389 
3390  int64_t pos = avio_tell(pb);
3391 
3392  avio_wb32(pb, 0); /* size */
3393  ffio_wfourcc(pb, "tapt");
3394 
3395  avio_wb32(pb, 20);
3396  ffio_wfourcc(pb, "clef");
3397  avio_wb32(pb, 0);
3398  avio_wb32(pb, width << 16);
3399  avio_wb32(pb, track->par->height << 16);
3400 
3401  avio_wb32(pb, 20);
3402  ffio_wfourcc(pb, "prof");
3403  avio_wb32(pb, 0);
3404  avio_wb32(pb, width << 16);
3405  avio_wb32(pb, track->par->height << 16);
3406 
3407  avio_wb32(pb, 20);
3408  ffio_wfourcc(pb, "enof");
3409  avio_wb32(pb, 0);
3410  avio_wb32(pb, track->par->width << 16);
3411  avio_wb32(pb, track->par->height << 16);
3412 
3413  return update_size(pb, pos);
3414 }
3415 
3416 // This box seems important for the psp playback ... without it the movie seems to hang
3418  MOVTrack *track)
3419 {
3420  int64_t duration = av_rescale_rnd(calc_samples_pts_duration(mov, track),
3421  mov->movie_timescale, track->timescale,
3422  AV_ROUND_UP);
3423  int version = duration < INT32_MAX ? 0 : 1;
3424  int entry_size, entry_count, size;
3425  int64_t delay, start_ct = track->start_cts;
3426  int64_t start_dts = track->start_dts;
3427 
3428  if (track->entry) {
3429  if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
3430 
3431  av_log(mov->fc, AV_LOG_DEBUG,
3432  "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
3433  track->cluster[0].dts, track->cluster[0].cts,
3434  start_dts, start_ct, track->track_id);
3435  start_dts = track->cluster[0].dts;
3436  start_ct = track->cluster[0].cts;
3437  }
3438  }
3439 
3440  delay = av_rescale_rnd(start_dts + start_ct, mov->movie_timescale,
3441  track->timescale, AV_ROUND_DOWN);
3442  version |= delay < INT32_MAX ? 0 : 1;
3443 
3444  entry_size = (version == 1) ? 20 : 12;
3445  entry_count = 1 + (delay > 0);
3446  size = 24 + entry_count * entry_size;
3447 
3448  /* write the atom data */
3449  avio_wb32(pb, size);
3450  ffio_wfourcc(pb, "edts");
3451  avio_wb32(pb, size - 8);
3452  ffio_wfourcc(pb, "elst");
3453  avio_w8(pb, version);
3454  avio_wb24(pb, 0); /* flags */
3455 
3456  avio_wb32(pb, entry_count);
3457  if (delay > 0) { /* add an empty edit to delay presentation */
3458  /* In the positive delay case, the delay includes the cts
3459  * offset, and the second edit list entry below trims out
3460  * the same amount from the actual content. This makes sure
3461  * that the offset last sample is included in the edit
3462  * list duration as well. */
3463  if (version == 1) {
3464  avio_wb64(pb, delay);
3465  avio_wb64(pb, -1);
3466  } else {
3467  avio_wb32(pb, delay);
3468  avio_wb32(pb, -1);
3469  }
3470  avio_wb32(pb, 0x00010000);
3471  } else {
3472  /* Avoid accidentally ending up with start_ct = -1 which has got a
3473  * special meaning. Normally start_ct should end up positive or zero
3474  * here, but use FFMIN in case dts is a small positive integer
3475  * rounded to 0 when represented in movie timescale units. */
3476  av_assert0(av_rescale_rnd(start_dts, mov->movie_timescale, track->timescale, AV_ROUND_DOWN) <= 0);
3477  start_ct = -FFMIN(start_dts, 0);
3478  /* Note, this delay is calculated from the pts of the first sample,
3479  * ensuring that we don't reduce the duration for cases with
3480  * dts<0 pts=0. */
3481  duration += delay;
3482  }
3483 
3484  /* For fragmented files, we don't know the full length yet. Setting
3485  * duration to 0 allows us to only specify the offset, including
3486  * the rest of the content (from all future fragments) without specifying
3487  * an explicit duration. */
3488  if (mov->flags & FF_MOV_FLAG_FRAGMENT)
3489  duration = 0;
3490 
3491  /* duration */
3492  if (version == 1) {
3493  avio_wb64(pb, duration);
3494  avio_wb64(pb, start_ct);
3495  } else {
3496  avio_wb32(pb, duration);
3497  avio_wb32(pb, start_ct);
3498  }
3499  avio_wb32(pb, 0x00010000);
3500  return size;
3501 }
3502 
3503 static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
3504 {
3505  avio_wb32(pb, 20); // size
3506  ffio_wfourcc(pb, "tref");
3507  avio_wb32(pb, 12); // size (subatom)
3508  avio_wl32(pb, track->tref_tag);
3509  avio_wb32(pb, track->tref_id);
3510  return 20;
3511 }
3512 
3513 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
3515 {
3516  avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
3517  ffio_wfourcc(pb, "uuid");
3518  ffio_wfourcc(pb, "USMT");
3519  avio_wb32(pb, 0x21d24fce);
3520  avio_wb32(pb, 0xbb88695c);
3521  avio_wb32(pb, 0xfac9c740);
3522  avio_wb32(pb, 0x1c); // another size here!
3523  ffio_wfourcc(pb, "MTDT");
3524  avio_wb32(pb, 0x00010012);
3525  avio_wb32(pb, 0x0a);
3526  avio_wb32(pb, 0x55c40000);
3527  avio_wb32(pb, 0x1);
3528  avio_wb32(pb, 0x0);
3529  return 0x34;
3530 }
3531 
3532 static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
3533 {
3534  AVFormatContext *ctx = track->rtp_ctx;
3535  char buf[1000] = "";
3536  int len;
3537 
3538  ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
3539  NULL, NULL, 0, 0, ctx);
3540  av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
3541  len = strlen(buf);
3542 
3543  avio_wb32(pb, len + 24);
3544  ffio_wfourcc(pb, "udta");
3545  avio_wb32(pb, len + 16);
3546  ffio_wfourcc(pb, "hnti");
3547  avio_wb32(pb, len + 8);
3548  ffio_wfourcc(pb, "sdp ");
3549  avio_write(pb, buf, len);
3550  return len + 24;
3551 }
3552 
3554  const char *tag, const char *str)
3555 {
3556  int64_t pos = avio_tell(pb);
3558  if (!t || !utf8len(t->value))
3559  return 0;
3560 
3561  avio_wb32(pb, 0); /* size */
3562  ffio_wfourcc(pb, tag); /* type */
3563  avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
3564  return update_size(pb, pos);
3565 }
3566 
3567 static int mov_write_track_kind(AVIOContext *pb, const char *scheme_uri,
3568  const char *value)
3569 {
3570  int64_t pos = avio_tell(pb);
3571 
3572  /* Box|FullBox basics */
3573  avio_wb32(pb, 0); /* size placeholder */
3574  ffio_wfourcc(pb, (const unsigned char *)"kind");
3575  avio_w8(pb, 0); /* version = 0 */
3576  avio_wb24(pb, 0); /* flags = 0 */
3577 
3578  /* Required null-terminated scheme URI */
3579  avio_write(pb, (const unsigned char *)scheme_uri,
3580  strlen(scheme_uri));
3581  avio_w8(pb, 0);
3582 
3583  /* Optional value string */
3584  if (value && value[0])
3585  avio_write(pb, (const unsigned char *)value,
3586  strlen(value));
3587 
3588  avio_w8(pb, 0);
3589 
3590  return update_size(pb, pos);
3591 }
3592 
3594 {
3595  int ret = AVERROR_BUG;
3596 
3597  for (int i = 0; ff_mov_track_kind_table[i].scheme_uri; i++) {
3599 
3600  for (int j = 0; map.value_maps[j].disposition; j++) {
3601  const struct MP4TrackKindValueMapping value_map = map.value_maps[j];
3602  if (!(st->disposition & value_map.disposition))
3603  continue;
3604 
3605  if ((ret = mov_write_track_kind(pb, map.scheme_uri, value_map.value)) < 0)
3606  return ret;
3607  }
3608  }
3609 
3610  return 0;
3611 }
3612 
3614  AVStream *st)
3615 {
3616  AVIOContext *pb_buf;
3617  int ret, size;
3618  uint8_t *buf;
3619 
3620  if (!st)
3621  return 0;
3622 
3623  ret = avio_open_dyn_buf(&pb_buf);
3624  if (ret < 0)
3625  return ret;
3626 
3627  if (mov->mode & (MODE_MP4|MODE_MOV))
3628  mov_write_track_metadata(pb_buf, st, "name", "title");
3629 
3630  if (mov->mode & MODE_MP4) {
3631  if ((ret = mov_write_track_kinds(pb_buf, st)) < 0)
3632  return ret;
3633  }
3634 
3635  if ((size = avio_get_dyn_buf(pb_buf, &buf)) > 0) {
3636  avio_wb32(pb, size + 8);
3637  ffio_wfourcc(pb, "udta");
3638  avio_write(pb, buf, size);
3639  }
3640  ffio_free_dyn_buf(&pb_buf);
3641 
3642  return 0;
3643 }
3644 
3646  MOVTrack *track, AVStream *st)
3647 {
3648  int64_t pos = avio_tell(pb);
3649  int entry_backup = track->entry;
3650  int chunk_backup = track->chunkCount;
3651  int ret;
3652 
3653  /* If we want to have an empty moov, but some samples already have been
3654  * buffered (delay_moov), pretend that no samples have been written yet. */
3655  if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
3656  track->chunkCount = track->entry = 0;
3657 
3658  avio_wb32(pb, 0); /* size */
3659  ffio_wfourcc(pb, "trak");
3660  mov_write_tkhd_tag(pb, mov, track, st);
3661 
3662  av_assert2(mov->use_editlist >= 0);
3663 
3664  if (track->start_dts != AV_NOPTS_VALUE) {
3665  if (mov->use_editlist)
3666  mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
3667  else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
3668  av_log(mov->fc, AV_LOG_WARNING,
3669  "Not writing any edit list even though one would have been required\n");
3670  }
3671 
3672  if (track->tref_tag)
3673  mov_write_tref_tag(pb, track);
3674 
3675  if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
3676  return ret;
3677  if (track->mode == MODE_PSP)
3678  mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
3679  if (track->tag == MKTAG('r','t','p',' '))
3680  mov_write_udta_sdp(pb, track);
3681  if (track->mode == MODE_MOV) {
3682  if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
3683  double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
3684  if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
3685  mov_write_tapt_tag(pb, track);
3686  }
3687  }
3688  if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
3689  mov_write_tapt_tag(pb, track);
3690  }
3691  }
3692  mov_write_track_udta_tag(pb, mov, st);
3693  track->entry = entry_backup;
3694  track->chunkCount = chunk_backup;
3695  return update_size(pb, pos);
3696 }
3697 
3699 {
3700  int i, has_audio = 0, has_video = 0;
3701  int64_t pos = avio_tell(pb);
3702  int audio_profile = mov->iods_audio_profile;
3703  int video_profile = mov->iods_video_profile;
3704  for (i = 0; i < mov->nb_streams; i++) {
3705  if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3706  has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
3707  has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
3708  }
3709  }
3710  if (audio_profile < 0)
3711  audio_profile = 0xFF - has_audio;
3712  if (video_profile < 0)
3713  video_profile = 0xFF - has_video;
3714  avio_wb32(pb, 0x0); /* size */
3715  ffio_wfourcc(pb, "iods");
3716  avio_wb32(pb, 0); /* version & flags */
3717  put_descr(pb, 0x10, 7);
3718  avio_wb16(pb, 0x004f);
3719  avio_w8(pb, 0xff);
3720  avio_w8(pb, 0xff);
3721  avio_w8(pb, audio_profile);
3722  avio_w8(pb, video_profile);
3723  avio_w8(pb, 0xff);
3724  return update_size(pb, pos);
3725 }
3726 
3727 static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
3728 {
3729  avio_wb32(pb, 0x20); /* size */
3730  ffio_wfourcc(pb, "trex");
3731  avio_wb32(pb, 0); /* version & flags */
3732  avio_wb32(pb, track->track_id); /* track ID */
3733  avio_wb32(pb, 1); /* default sample description index */
3734  avio_wb32(pb, 0); /* default sample duration */
3735  avio_wb32(pb, 0); /* default sample size */
3736  avio_wb32(pb, 0); /* default sample flags */
3737  return 0;
3738 }
3739 
3741 {
3742  int64_t pos = avio_tell(pb);
3743  int i;
3744  avio_wb32(pb, 0x0); /* size */
3745  ffio_wfourcc(pb, "mvex");
3746  for (i = 0; i < mov->nb_streams; i++)
3747  mov_write_trex_tag(pb, &mov->tracks[i]);
3748  return update_size(pb, pos);
3749 }
3750 
3752 {
3753  int max_track_id = 1, i;
3754  int64_t max_track_len = 0;
3755  int version;
3756  int timescale;
3757 
3758  for (i = 0; i < mov->nb_streams; i++) {
3759  if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
3760  int64_t max_track_len_temp = av_rescale_rnd(
3761  calc_pts_duration(mov, &mov->tracks[i]),
3762  mov->movie_timescale,
3763  mov->tracks[i].timescale,
3764  AV_ROUND_UP);
3765  if (max_track_len < max_track_len_temp)
3766  max_track_len = max_track_len_temp;
3767  if (max_track_id < mov->tracks[i].track_id)
3768  max_track_id = mov->tracks[i].track_id;
3769  }
3770  }
3771  /* If using delay_moov, make sure the output is the same as if no
3772  * samples had been written yet. */
3773  if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
3774  max_track_len = 0;
3775  max_track_id = 1;
3776  }
3777 
3778  version = max_track_len < UINT32_MAX ? 0 : 1;
3779  avio_wb32(pb, version == 1 ? 120 : 108); /* size */
3780 
3781  ffio_wfourcc(pb, "mvhd");
3782  avio_w8(pb, version);
3783  avio_wb24(pb, 0); /* flags */
3784  if (version == 1) {
3785  avio_wb64(pb, mov->time);
3786  avio_wb64(pb, mov->time);
3787  } else {
3788  avio_wb32(pb, mov->time); /* creation time */
3789  avio_wb32(pb, mov->time); /* modification time */
3790  }
3791 
3792  timescale = mov->movie_timescale;
3793  if (mov->mode == MODE_AVIF && !timescale)
3794  timescale = mov->tracks[0].timescale;
3795 
3796  avio_wb32(pb, timescale);
3797  (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
3798 
3799  avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
3800  avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
3801  ffio_fill(pb, 0, 2 + 2 * 4); /* reserved */
3802 
3803  /* Matrix structure */
3804  write_matrix(pb, 1, 0, 0, 1, 0, 0);
3805 
3806  avio_wb32(pb, 0); /* reserved (preview time) */
3807  avio_wb32(pb, 0); /* reserved (preview duration) */
3808  avio_wb32(pb, 0); /* reserved (poster time) */
3809  avio_wb32(pb, 0); /* reserved (selection time) */
3810  avio_wb32(pb, 0); /* reserved (selection duration) */
3811  avio_wb32(pb, 0); /* reserved (current time) */
3812  avio_wb32(pb, max_track_id + 1); /* Next track id */
3813  return 0x6c;
3814 }
3815 
3817  AVFormatContext *s)
3818 {
3819  avio_wb32(pb, 33); /* size */
3820  ffio_wfourcc(pb, "hdlr");
3821  avio_wb32(pb, 0);
3822  avio_wb32(pb, 0);
3823  ffio_wfourcc(pb, "mdir");
3824  ffio_wfourcc(pb, "appl");
3825  avio_wb32(pb, 0);
3826  avio_wb32(pb, 0);
3827  avio_w8(pb, 0);
3828  return 33;
3829 }
3830 
3831 /* helper function to write a data tag with the specified string as data */
3832 static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
3833 {
3834  size_t data_len = strlen(data);
3835  if (long_style) {
3836  int size = 16 + data_len;
3837  avio_wb32(pb, size); /* size */
3838  ffio_wfourcc(pb, "data");
3839  avio_wb32(pb, 1);
3840  avio_wb32(pb, 0);
3841  avio_write(pb, data, data_len);
3842  return size;
3843  } else {
3844  avio_wb16(pb, data_len); /* string length */
3845  if (!lang)
3846  lang = ff_mov_iso639_to_lang("und", 1);
3847  avio_wb16(pb, lang);
3848  avio_write(pb, data, data_len);
3849  return data_len + 4;
3850  }
3851 }
3852 
3853 static int mov_write_string_tag(AVIOContext *pb, const char *name,
3854  const char *value, int lang, int long_style)
3855 {
3856  int size = 0;
3857  if (value && value[0]) {
3858  int64_t pos = avio_tell(pb);
3859  avio_wb32(pb, 0); /* size */
3860  ffio_wfourcc(pb, name);
3861  mov_write_string_data_tag(pb, value, lang, long_style);
3862  size = update_size(pb, pos);
3863  }
3864  return size;
3865 }
3866 
3868  const char *tag, int *lang)
3869 {
3870  int l, len, len2;
3871  AVDictionaryEntry *t, *t2 = NULL;
3872  char tag2[16];
3873 
3874  *lang = 0;
3875 
3876  if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
3877  return NULL;
3878 
3879  len = strlen(t->key);
3880  snprintf(tag2, sizeof(tag2), "%s-", tag);
3881  while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
3882  len2 = strlen(t2->key);
3883  if (len2 == len + 4 && !strcmp(t->value, t2->value)
3884  && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
3885  *lang = l;
3886  return t;
3887  }
3888  }
3889  return t;
3890 }
3891 
3893  const char *name, const char *tag,
3894  int long_style)
3895 {
3896  int lang;
3897  AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
3898  if (!t)
3899  return 0;
3900  return mov_write_string_tag(pb, name, t->value, lang, long_style);
3901 }
3902 
3903 /* iTunes bpm number */
3905 {
3906  AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
3907  int size = 0, tmpo = t ? atoi(t->value) : 0;
3908  if (tmpo) {
3909  size = 26;
3910  avio_wb32(pb, size);
3911  ffio_wfourcc(pb, "tmpo");
3912  avio_wb32(pb, size-8); /* size */
3913  ffio_wfourcc(pb, "data");
3914  avio_wb32(pb, 0x15); //type specifier
3915  avio_wb32(pb, 0);
3916  avio_wb16(pb, tmpo); // data
3917  }
3918  return size;
3919 }
3920 
3921 /* 3GPP TS 26.244 */
3923 {
3924  int lang;
3925  int64_t pos = avio_tell(pb);
3926  double latitude, longitude, altitude;
3927  int32_t latitude_fix, longitude_fix, altitude_fix;
3928  AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
3929  const char *ptr, *place = "";
3930  char *end;
3931  static const char *astronomical_body = "earth";
3932  if (!t)
3933  return 0;
3934 
3935  ptr = t->value;
3936  longitude = strtod(ptr, &end);
3937  if (end == ptr) {
3938  av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3939  return 0;
3940  }
3941  ptr = end;
3942  latitude = strtod(ptr, &end);
3943  if (end == ptr) {
3944  av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
3945  return 0;
3946  }
3947  ptr = end;
3948  altitude = strtod(ptr, &end);
3949  /* If no altitude was present, the default 0 should be fine */
3950  if (*end == '/')
3951  place = end + 1;
3952 
3953  latitude_fix = (int32_t) ((1 << 16) * latitude);
3954  longitude_fix = (int32_t) ((1 << 16) * longitude);
3955  altitude_fix = (int32_t) ((1 << 16) * altitude);
3956 
3957  avio_wb32(pb, 0); /* size */
3958  ffio_wfourcc(pb, "loci"); /* type */
3959  avio_wb32(pb, 0); /* version + flags */
3960  avio_wb16(pb, lang);
3961  avio_write(pb, place, strlen(place) + 1);
3962  avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
3963  avio_wb32(pb, latitude_fix);
3964  avio_wb32(pb, longitude_fix);
3965  avio_wb32(pb, altitude_fix);
3966  avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
3967  avio_w8(pb, 0); /* additional notes, null terminated string */
3968 
3969  return update_size(pb, pos);
3970 }
3971 
3972 /* iTunes track or disc number */
3974  AVFormatContext *s, int disc)
3975 {
3976  AVDictionaryEntry *t = av_dict_get(s->metadata,
3977  disc ? "disc" : "track",
3978  NULL, 0);
3979  int size = 0, track = t ? atoi(t->value) : 0;
3980  if (track) {
3981  int tracks = 0;
3982  char *slash = strchr(t->value, '/');
3983  if (slash)
3984  tracks = atoi(slash + 1);
3985  avio_wb32(pb, 32); /* size */
3986  ffio_wfourcc(pb, disc ? "disk" : "trkn");
3987  avio_wb32(pb, 24); /* size */
3988  ffio_wfourcc(pb, "data");
3989  avio_wb32(pb, 0); // 8 bytes empty
3990  avio_wb32(pb, 0);
3991  avio_wb16(pb, 0); // empty
3992  avio_wb16(pb, track); // track / disc number
3993  avio_wb16(pb, tracks); // total track / disc number
3994  avio_wb16(pb, 0); // empty
3995  size = 32;
3996  }
3997  return size;
3998 }
3999 
4001  const char *name, const char *tag,
4002  int len)
4003 {
4004  AVDictionaryEntry *t = NULL;
4005  uint8_t num;
4006  int size = 24 + len;
4007 
4008  if (len != 1 && len != 4)
4009  return -1;
4010 
4011  if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
4012  return 0;
4013  num = atoi(t->value);
4014 
4015  avio_wb32(pb, size);
4016  ffio_wfourcc(pb, name);
4017  avio_wb32(pb, size - 8);
4018  ffio_wfourcc(pb, "data");
4019  avio_wb32(pb, 0x15);
4020  avio_wb32(pb, 0);
4021  if (len==4) avio_wb32(pb, num);
4022  else avio_w8 (pb, num);
4023 
4024  return size;
4025 }
4026 
4028 {
4029  MOVMuxContext *mov = s->priv_data;
4030  int64_t pos = 0;
4031  int i;
4032 
4033  for (i = 0; i < s->nb_streams; i++) {
4034  MOVTrack *trk = &mov->tracks[i];
4035 
4036  if (!is_cover_image(trk->st) || trk->cover_image->size <= 0)
4037  continue;
4038 
4039  if (!pos) {
4040  pos = avio_tell(pb);
4041  avio_wb32(pb, 0);
4042  ffio_wfourcc(pb, "covr");
4043  }
4044  avio_wb32(pb, 16 + trk->cover_image->size);
4045  ffio_wfourcc(pb, "data");
4046  avio_wb32(pb, trk->tag);
4047  avio_wb32(pb , 0);
4048  avio_write(pb, trk->cover_image->data, trk->cover_image->size);
4049  }
4050 
4051  return pos ? update_size(pb, pos) : 0;
4052 }
4053 
4054 /* iTunes meta data list */
4056  AVFormatContext *s)
4057 {
4058  int64_t pos = avio_tell(pb);
4059  avio_wb32(pb, 0); /* size */
4060  ffio_wfourcc(pb, "ilst");
4061  mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
4062  mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
4063  mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
4064  mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
4065  mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
4066  mov_write_string_metadata(s, pb, "\251day", "date" , 1);
4067  if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
4068  if (!(s->flags & AVFMT_FLAG_BITEXACT))
4069  mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
4070  }
4071  mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
4072  mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
4073  mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
4074  mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
4075  mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
4076  mov_write_string_metadata(s, pb, "desc", "description",1);
4077  mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
4078  mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
4079  mov_write_string_metadata(s, pb, "tven", "episode_id",1);
4080  mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
4081  mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
4082  mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
4083  mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
4084  mov_write_int8_metadata (s, pb, "stik", "media_type",1);
4085  mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
4086  mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
4087  mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
4088  mov_write_covr(pb, s);
4089  mov_write_trkn_tag(pb, mov, s, 0); // track number
4090  mov_write_trkn_tag(pb, mov, s, 1); // disc number
4091  mov_write_tmpo_tag(pb, s);
4092  return update_size(pb, pos);
4093 }
4094 
4096  AVFormatContext *s)
4097 {
4098  avio_wb32(pb, 33); /* size */
4099  ffio_wfourcc(pb, "hdlr");
4100  avio_wb32(pb, 0);
4101  avio_wb32(pb, 0);
4102  ffio_wfourcc(pb, "mdta");
4103  avio_wb32(pb, 0);
4104  avio_wb32(pb, 0);
4105  avio_wb32(pb, 0);
4106  avio_w8(pb, 0);
4107  return 33;
4108 }
4109 
4111  AVFormatContext *s)
4112 {
4113  const AVDictionaryEntry *t = NULL;
4114  int64_t pos = avio_tell(pb);
4115  int64_t curpos, entry_pos;
4116  int count = 0;
4117 
4118  avio_wb32(pb, 0); /* size */
4119  ffio_wfourcc(pb, "keys");
4120  avio_wb32(pb, 0);
4121  entry_pos = avio_tell(pb);
4122  avio_wb32(pb, 0); /* entry count */
4123 
4124  while (t = av_dict_iterate(s->metadata, t)) {
4125  size_t key_len = strlen(t->key);
4126  avio_wb32(pb, key_len + 8);
4127  ffio_wfourcc(pb, "mdta");
4128  avio_write(pb, t->key, key_len);
4129  count += 1;
4130  }
4131  curpos = avio_tell(pb);
4132  avio_seek(pb, entry_pos, SEEK_SET);
4133  avio_wb32(pb, count); // rewrite entry count
4134  avio_seek(pb, curpos, SEEK_SET);
4135 
4136  return update_size(pb, pos);
4137 }
4138 
4140  AVFormatContext *s)
4141 {
4142  const AVDictionaryEntry *t = NULL;
4143  int64_t pos = avio_tell(pb);
4144  int count = 1; /* keys are 1-index based */
4145 
4146  avio_wb32(pb, 0); /* size */
4147  ffio_wfourcc(pb, "ilst");
4148 
4149  while (t = av_dict_iterate(s->metadata, t)) {
4150  int64_t entry_pos = avio_tell(pb);
4151  avio_wb32(pb, 0); /* size */
4152  avio_wb32(pb, count); /* key */
4153  mov_write_string_data_tag(pb, t->value, 0, 1);
4154  update_size(pb, entry_pos);
4155  count += 1;
4156  }
4157  return update_size(pb, pos);
4158 }
4159 
4160 /* meta data tags */
4162  AVFormatContext *s)
4163 {
4164  int size = 0;
4165  int64_t pos = avio_tell(pb);
4166  avio_wb32(pb, 0); /* size */
4167  ffio_wfourcc(pb, "meta");
4168  avio_wb32(pb, 0);
4169  if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
4170  mov_write_mdta_hdlr_tag(pb, mov, s);
4171  mov_write_mdta_keys_tag(pb, mov, s);
4172  mov_write_mdta_ilst_tag(pb, mov, s);
4173  } else if (mov->mode == MODE_AVIF) {
4174  mov_write_hdlr_tag(s, pb, &mov->tracks[0]);
4175  // We always write the primary item id as 1 since only one track is
4176  // supported for AVIF.
4177  mov_write_pitm_tag(pb, 1);
4178  mov_write_iloc_tag(pb, mov, s);
4179  mov_write_iinf_tag(pb, mov, s);
4180  if (s->nb_streams > 1)
4181  mov_write_iref_tag(pb, mov, s);
4182  mov_write_iprp_tag(pb, mov, s);
4183  } else {
4184  /* iTunes metadata tag */
4185  mov_write_itunes_hdlr_tag(pb, mov, s);
4186  mov_write_ilst_tag(pb, mov, s);
4187  }
4188  size = update_size(pb, pos);
4189  return size;
4190 }
4191 
4193  const char *name, const char *key)
4194 {
4195  int len;
4196  AVDictionaryEntry *t;
4197 
4198  if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
4199  return 0;
4200 
4201  len = strlen(t->value);
4202  if (len > 0) {
4203  int size = len + 8;
4204  avio_wb32(pb, size);
4205  ffio_wfourcc(pb, name);
4206  avio_write(pb, t->value, len);
4207  return size;
4208  }
4209  return 0;
4210 }
4211 
4212 static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
4213 {
4214  int val;
4215  while (*b) {
4216  GET_UTF8(val, *b++, return -1;)
4217  avio_wb16(pb, val);
4218  }
4219  avio_wb16(pb, 0x00);
4220  return 0;
4221 }
4222 
4223 static uint16_t language_code(const char *str)
4224 {
4225  return (((str[0] - 0x60) & 0x1F) << 10) +
4226  (((str[1] - 0x60) & 0x1F) << 5) +
4227  (( str[2] - 0x60) & 0x1F);
4228 }
4229 
4231  const char *tag, const char *str)
4232 {