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