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