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