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