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