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