You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6355 lines
230KB

  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. #include <stdint.h>
  24. #include <inttypes.h>
  25. #include "movenc.h"
  26. #include "avformat.h"
  27. #include "avio_internal.h"
  28. #include "riff.h"
  29. #include "avio.h"
  30. #include "isom.h"
  31. #include "avc.h"
  32. #include "libavcodec/ac3_parser.h"
  33. #include "libavcodec/dnxhddata.h"
  34. #include "libavcodec/get_bits.h"
  35. #include "libavcodec/put_bits.h"
  36. #include "libavcodec/vc1_common.h"
  37. #include "libavcodec/raw.h"
  38. #include "internal.h"
  39. #include "libavutil/avstring.h"
  40. #include "libavutil/intfloat.h"
  41. #include "libavutil/mathematics.h"
  42. #include "libavutil/libm.h"
  43. #include "libavutil/opt.h"
  44. #include "libavutil/dict.h"
  45. #include "libavutil/pixdesc.h"
  46. #include "libavutil/timecode.h"
  47. #include "libavutil/color_utils.h"
  48. #include "hevc.h"
  49. #include "rtpenc.h"
  50. #include "mov_chan.h"
  51. #include "vpcc.h"
  52. static const AVOption options[] = {
  53. { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  54. { "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" },
  55. { "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 },
  56. { "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" },
  57. { "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" },
  58. { "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" },
  59. { "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" },
  60. { "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" },
  61. { "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" },
  62. { "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" },
  63. { "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" },
  64. { "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" },
  65. { "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" },
  66. { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  67. { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  68. { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  69. { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  70. { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  71. { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  72. FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
  73. { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  74. { "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},
  75. { "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},
  76. { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
  77. { "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},
  78. { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
  79. { "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},
  80. { "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},
  81. { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
  82. { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
  83. { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
  84. { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM},
  85. { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
  86. { "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
  87. { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
  88. { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
  89. { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  90. { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
  91. { NULL },
  92. };
  93. #define MOV_CLASS(flavor)\
  94. static const AVClass flavor ## _muxer_class = {\
  95. .class_name = #flavor " muxer",\
  96. .item_name = av_default_item_name,\
  97. .option = options,\
  98. .version = LIBAVUTIL_VERSION_INT,\
  99. };
  100. static int get_moov_size(AVFormatContext *s);
  101. static int utf8len(const uint8_t *b)
  102. {
  103. int len = 0;
  104. int val;
  105. while (*b) {
  106. GET_UTF8(val, *b++, return -1;)
  107. len++;
  108. }
  109. return len;
  110. }
  111. //FIXME support 64 bit variant with wide placeholders
  112. static int64_t update_size(AVIOContext *pb, int64_t pos)
  113. {
  114. int64_t curpos = avio_tell(pb);
  115. avio_seek(pb, pos, SEEK_SET);
  116. avio_wb32(pb, curpos - pos); /* rewrite size */
  117. avio_seek(pb, curpos, SEEK_SET);
  118. return curpos - pos;
  119. }
  120. static int co64_required(const MOVTrack *track)
  121. {
  122. if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
  123. return 1;
  124. return 0;
  125. }
  126. /* Chunk offset atom */
  127. static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
  128. {
  129. int i;
  130. int mode64 = co64_required(track); // use 32 bit size variant if possible
  131. int64_t pos = avio_tell(pb);
  132. avio_wb32(pb, 0); /* size */
  133. if (mode64)
  134. ffio_wfourcc(pb, "co64");
  135. else
  136. ffio_wfourcc(pb, "stco");
  137. avio_wb32(pb, 0); /* version & flags */
  138. avio_wb32(pb, track->chunkCount); /* entry count */
  139. for (i = 0; i < track->entry; i++) {
  140. if (!track->cluster[i].chunkNum)
  141. continue;
  142. if (mode64 == 1)
  143. avio_wb64(pb, track->cluster[i].pos + track->data_offset);
  144. else
  145. avio_wb32(pb, track->cluster[i].pos + track->data_offset);
  146. }
  147. return update_size(pb, pos);
  148. }
  149. /* Sample size atom */
  150. static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
  151. {
  152. int equalChunks = 1;
  153. int i, j, entries = 0, tst = -1, oldtst = -1;
  154. int64_t pos = avio_tell(pb);
  155. avio_wb32(pb, 0); /* size */
  156. ffio_wfourcc(pb, "stsz");
  157. avio_wb32(pb, 0); /* version & flags */
  158. for (i = 0; i < track->entry; i++) {
  159. tst = track->cluster[i].size / track->cluster[i].entries;
  160. if (oldtst != -1 && tst != oldtst)
  161. equalChunks = 0;
  162. oldtst = tst;
  163. entries += track->cluster[i].entries;
  164. }
  165. if (equalChunks && track->entry) {
  166. int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
  167. sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
  168. avio_wb32(pb, sSize); // sample size
  169. avio_wb32(pb, entries); // sample count
  170. } else {
  171. avio_wb32(pb, 0); // sample size
  172. avio_wb32(pb, entries); // sample count
  173. for (i = 0; i < track->entry; i++) {
  174. for (j = 0; j < track->cluster[i].entries; j++) {
  175. avio_wb32(pb, track->cluster[i].size /
  176. track->cluster[i].entries);
  177. }
  178. }
  179. }
  180. return update_size(pb, pos);
  181. }
  182. /* Sample to chunk atom */
  183. static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
  184. {
  185. int index = 0, oldval = -1, i;
  186. int64_t entryPos, curpos;
  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. return update_size(pb, pos);
  207. }
  208. /* Sync sample atom */
  209. static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
  210. {
  211. int64_t curpos, entryPos;
  212. int i, index = 0;
  213. int64_t pos = avio_tell(pb);
  214. avio_wb32(pb, 0); // size
  215. ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
  216. avio_wb32(pb, 0); // version & flags
  217. entryPos = avio_tell(pb);
  218. avio_wb32(pb, track->entry); // entry count
  219. for (i = 0; i < track->entry; i++) {
  220. if (track->cluster[i].flags & flag) {
  221. avio_wb32(pb, i + 1);
  222. index++;
  223. }
  224. }
  225. curpos = avio_tell(pb);
  226. avio_seek(pb, entryPos, SEEK_SET);
  227. avio_wb32(pb, index); // rewrite size
  228. avio_seek(pb, curpos, SEEK_SET);
  229. return update_size(pb, pos);
  230. }
  231. static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
  232. {
  233. avio_wb32(pb, 0x11); /* size */
  234. if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
  235. else ffio_wfourcc(pb, "damr");
  236. ffio_wfourcc(pb, "FFMP");
  237. avio_w8(pb, 0); /* decoder version */
  238. avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
  239. avio_w8(pb, 0x00); /* Mode change period (no restriction) */
  240. avio_w8(pb, 0x01); /* Frames per sample */
  241. return 0x11;
  242. }
  243. static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
  244. {
  245. GetBitContext gbc;
  246. PutBitContext pbc;
  247. uint8_t buf[3];
  248. int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
  249. if (track->vos_len < 7)
  250. return -1;
  251. avio_wb32(pb, 11);
  252. ffio_wfourcc(pb, "dac3");
  253. init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
  254. fscod = get_bits(&gbc, 2);
  255. frmsizecod = get_bits(&gbc, 6);
  256. bsid = get_bits(&gbc, 5);
  257. bsmod = get_bits(&gbc, 3);
  258. acmod = get_bits(&gbc, 3);
  259. if (acmod == 2) {
  260. skip_bits(&gbc, 2); // dsurmod
  261. } else {
  262. if ((acmod & 1) && acmod != 1)
  263. skip_bits(&gbc, 2); // cmixlev
  264. if (acmod & 4)
  265. skip_bits(&gbc, 2); // surmixlev
  266. }
  267. lfeon = get_bits1(&gbc);
  268. init_put_bits(&pbc, buf, sizeof(buf));
  269. put_bits(&pbc, 2, fscod);
  270. put_bits(&pbc, 5, bsid);
  271. put_bits(&pbc, 3, bsmod);
  272. put_bits(&pbc, 3, acmod);
  273. put_bits(&pbc, 1, lfeon);
  274. put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
  275. put_bits(&pbc, 5, 0); // reserved
  276. flush_put_bits(&pbc);
  277. avio_write(pb, buf, sizeof(buf));
  278. return 11;
  279. }
  280. struct eac3_info {
  281. AVPacket pkt;
  282. uint8_t ec3_done;
  283. uint8_t num_blocks;
  284. /* Layout of the EC3SpecificBox */
  285. /* maximum bitrate */
  286. uint16_t data_rate;
  287. /* number of independent substreams */
  288. uint8_t num_ind_sub;
  289. struct {
  290. /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
  291. uint8_t fscod;
  292. /* bit stream identification 5 bits */
  293. uint8_t bsid;
  294. /* one bit reserved */
  295. /* audio service mixing (not supported yet) 1 bit */
  296. /* bit stream mode 3 bits */
  297. uint8_t bsmod;
  298. /* audio coding mode 3 bits */
  299. uint8_t acmod;
  300. /* sub woofer on 1 bit */
  301. uint8_t lfeon;
  302. /* 3 bits reserved */
  303. /* number of dependent substreams associated with this substream 4 bits */
  304. uint8_t num_dep_sub;
  305. /* channel locations of the dependent substream(s), if any, 9 bits */
  306. uint16_t chan_loc;
  307. /* if there is no dependent substream, then one bit reserved instead */
  308. } substream[1]; /* TODO: support 8 independent substreams */
  309. };
  310. #if CONFIG_AC3_PARSER
  311. static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
  312. {
  313. GetBitContext gbc;
  314. AC3HeaderInfo tmp, *hdr = &tmp;
  315. struct eac3_info *info;
  316. int num_blocks;
  317. if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
  318. return AVERROR(ENOMEM);
  319. info = track->eac3_priv;
  320. init_get_bits(&gbc, pkt->data, pkt->size * 8);
  321. if (avpriv_ac3_parse_header(&gbc, &hdr) < 0) {
  322. /* drop the packets until we see a good one */
  323. if (!track->entry) {
  324. av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
  325. return 0;
  326. }
  327. return AVERROR_INVALIDDATA;
  328. }
  329. info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
  330. num_blocks = hdr->num_blocks;
  331. if (!info->ec3_done) {
  332. /* AC-3 substream must be the first one */
  333. if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
  334. return AVERROR(EINVAL);
  335. /* this should always be the case, given that our AC-3 parser
  336. * concatenates dependent frames to their independent parent */
  337. if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
  338. /* substream ids must be incremental */
  339. if (hdr->substreamid > info->num_ind_sub + 1)
  340. return AVERROR(EINVAL);
  341. if (hdr->substreamid == info->num_ind_sub + 1) {
  342. //info->num_ind_sub++;
  343. avpriv_request_sample(mov->fc, "Multiple independent substreams");
  344. return AVERROR_PATCHWELCOME;
  345. } else if (hdr->substreamid < info->num_ind_sub ||
  346. hdr->substreamid == 0 && info->substream[0].bsid) {
  347. info->ec3_done = 1;
  348. goto concatenate;
  349. }
  350. } else {
  351. if (hdr->substreamid != 0) {
  352. avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams");
  353. return AVERROR_PATCHWELCOME;
  354. }
  355. }
  356. /* fill the info needed for the "dec3" atom */
  357. info->substream[hdr->substreamid].fscod = hdr->sr_code;
  358. info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
  359. info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
  360. info->substream[hdr->substreamid].acmod = hdr->channel_mode;
  361. info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
  362. /* Parse dependent substream(s), if any */
  363. if (pkt->size != hdr->frame_size) {
  364. int cumul_size = hdr->frame_size;
  365. int parent = hdr->substreamid;
  366. while (cumul_size != pkt->size) {
  367. int i;
  368. init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
  369. if (avpriv_ac3_parse_header(&gbc, &hdr) < 0)
  370. return AVERROR_INVALIDDATA;
  371. if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
  372. return AVERROR(EINVAL);
  373. cumul_size += hdr->frame_size;
  374. info->substream[parent].num_dep_sub++;
  375. /* header is parsed up to lfeon, but custom channel map may be needed */
  376. /* skip bsid */
  377. skip_bits(&gbc, 5);
  378. /* skip volume control params */
  379. for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
  380. skip_bits(&gbc, 5); // skip dialog normalization
  381. if (get_bits1(&gbc)) {
  382. skip_bits(&gbc, 8); // skip compression gain word
  383. }
  384. }
  385. /* get the dependent stream channel map, if exists */
  386. if (get_bits1(&gbc))
  387. info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
  388. else
  389. info->substream[parent].chan_loc |= hdr->channel_mode;
  390. }
  391. }
  392. }
  393. concatenate:
  394. if (!info->num_blocks && num_blocks == 6)
  395. return pkt->size;
  396. else if (info->num_blocks + num_blocks > 6)
  397. return AVERROR_INVALIDDATA;
  398. if (!info->num_blocks) {
  399. int ret;
  400. if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
  401. return ret;
  402. info->num_blocks = num_blocks;
  403. return 0;
  404. } else {
  405. int ret;
  406. if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
  407. return ret;
  408. memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
  409. info->num_blocks += num_blocks;
  410. info->pkt.duration += pkt->duration;
  411. if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
  412. return ret;
  413. if (info->num_blocks != 6)
  414. return 0;
  415. av_packet_unref(pkt);
  416. if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
  417. return ret;
  418. av_packet_unref(&info->pkt);
  419. info->num_blocks = 0;
  420. }
  421. return pkt->size;
  422. }
  423. #endif
  424. static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
  425. {
  426. PutBitContext pbc;
  427. uint8_t *buf;
  428. struct eac3_info *info;
  429. int size, i;
  430. if (!track->eac3_priv)
  431. return AVERROR(EINVAL);
  432. info = track->eac3_priv;
  433. size = 2 + 4 * (info->num_ind_sub + 1);
  434. buf = av_malloc(size);
  435. if (!buf) {
  436. size = AVERROR(ENOMEM);
  437. goto end;
  438. }
  439. init_put_bits(&pbc, buf, size);
  440. put_bits(&pbc, 13, info->data_rate);
  441. put_bits(&pbc, 3, info->num_ind_sub);
  442. for (i = 0; i <= info->num_ind_sub; i++) {
  443. put_bits(&pbc, 2, info->substream[i].fscod);
  444. put_bits(&pbc, 5, info->substream[i].bsid);
  445. put_bits(&pbc, 1, 0); /* reserved */
  446. put_bits(&pbc, 1, 0); /* asvc */
  447. put_bits(&pbc, 3, info->substream[i].bsmod);
  448. put_bits(&pbc, 3, info->substream[i].acmod);
  449. put_bits(&pbc, 1, info->substream[i].lfeon);
  450. put_bits(&pbc, 5, 0); /* reserved */
  451. put_bits(&pbc, 4, info->substream[i].num_dep_sub);
  452. if (!info->substream[i].num_dep_sub) {
  453. put_bits(&pbc, 1, 0); /* reserved */
  454. size--;
  455. } else {
  456. put_bits(&pbc, 9, info->substream[i].chan_loc);
  457. }
  458. }
  459. flush_put_bits(&pbc);
  460. avio_wb32(pb, size + 8);
  461. ffio_wfourcc(pb, "dec3");
  462. avio_write(pb, buf, size);
  463. av_free(buf);
  464. end:
  465. av_packet_unref(&info->pkt);
  466. av_freep(&track->eac3_priv);
  467. return size;
  468. }
  469. /**
  470. * This function writes extradata "as is".
  471. * Extradata must be formatted like a valid atom (with size and tag).
  472. */
  473. static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
  474. {
  475. avio_write(pb, track->par->extradata, track->par->extradata_size);
  476. return track->par->extradata_size;
  477. }
  478. static int mov_write_enda_tag(AVIOContext *pb)
  479. {
  480. avio_wb32(pb, 10);
  481. ffio_wfourcc(pb, "enda");
  482. avio_wb16(pb, 1); /* little endian */
  483. return 10;
  484. }
  485. static int mov_write_enda_tag_be(AVIOContext *pb)
  486. {
  487. avio_wb32(pb, 10);
  488. ffio_wfourcc(pb, "enda");
  489. avio_wb16(pb, 0); /* big endian */
  490. return 10;
  491. }
  492. static void put_descr(AVIOContext *pb, int tag, unsigned int size)
  493. {
  494. int i = 3;
  495. avio_w8(pb, tag);
  496. for (; i > 0; i--)
  497. avio_w8(pb, (size >> (7 * i)) | 0x80);
  498. avio_w8(pb, size & 0x7F);
  499. }
  500. static unsigned compute_avg_bitrate(MOVTrack *track)
  501. {
  502. uint64_t size = 0;
  503. int i;
  504. if (!track->track_duration)
  505. return 0;
  506. for (i = 0; i < track->entry; i++)
  507. size += track->cluster[i].size;
  508. return size * 8 * track->timescale / track->track_duration;
  509. }
  510. static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
  511. {
  512. AVCPBProperties *props;
  513. int64_t pos = avio_tell(pb);
  514. int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
  515. unsigned avg_bitrate;
  516. avio_wb32(pb, 0); // size
  517. ffio_wfourcc(pb, "esds");
  518. avio_wb32(pb, 0); // Version
  519. // ES descriptor
  520. put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
  521. avio_wb16(pb, track->track_id);
  522. avio_w8(pb, 0x00); // flags (= no flags)
  523. // DecoderConfig descriptor
  524. put_descr(pb, 0x04, 13 + decoder_specific_info_len);
  525. // Object type indication
  526. if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
  527. track->par->codec_id == AV_CODEC_ID_MP3) &&
  528. track->par->sample_rate > 24000)
  529. avio_w8(pb, 0x6B); // 11172-3
  530. else
  531. avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
  532. // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
  533. // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
  534. if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  535. avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
  536. else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  537. avio_w8(pb, 0x15); // flags (= Audiostream)
  538. else
  539. avio_w8(pb, 0x11); // flags (= Visualstream)
  540. props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
  541. NULL);
  542. avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
  543. avg_bitrate = compute_avg_bitrate(track);
  544. avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
  545. avio_wb32(pb, avg_bitrate);
  546. if (track->vos_len) {
  547. // DecoderSpecific info descriptor
  548. put_descr(pb, 0x05, track->vos_len);
  549. avio_write(pb, track->vos_data, track->vos_len);
  550. }
  551. // SL descriptor
  552. put_descr(pb, 0x06, 1);
  553. avio_w8(pb, 0x02);
  554. return update_size(pb, pos);
  555. }
  556. static int mov_pcm_le_gt16(enum AVCodecID codec_id)
  557. {
  558. return codec_id == AV_CODEC_ID_PCM_S24LE ||
  559. codec_id == AV_CODEC_ID_PCM_S32LE ||
  560. codec_id == AV_CODEC_ID_PCM_F32LE ||
  561. codec_id == AV_CODEC_ID_PCM_F64LE;
  562. }
  563. static int mov_pcm_be_gt16(enum AVCodecID codec_id)
  564. {
  565. return codec_id == AV_CODEC_ID_PCM_S24BE ||
  566. codec_id == AV_CODEC_ID_PCM_S32BE ||
  567. codec_id == AV_CODEC_ID_PCM_F32BE ||
  568. codec_id == AV_CODEC_ID_PCM_F64BE;
  569. }
  570. static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  571. {
  572. int ret;
  573. int64_t pos = avio_tell(pb);
  574. avio_wb32(pb, 0);
  575. avio_wl32(pb, track->tag); // store it byteswapped
  576. track->par->codec_tag = av_bswap16(track->tag >> 16);
  577. if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
  578. return ret;
  579. return update_size(pb, pos);
  580. }
  581. static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  582. {
  583. int ret;
  584. int64_t pos = avio_tell(pb);
  585. avio_wb32(pb, 0);
  586. ffio_wfourcc(pb, "wfex");
  587. if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
  588. return ret;
  589. return update_size(pb, pos);
  590. }
  591. static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  592. {
  593. uint32_t layout_tag, bitmap;
  594. int64_t pos = avio_tell(pb);
  595. layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
  596. track->par->channel_layout,
  597. &bitmap);
  598. if (!layout_tag) {
  599. av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
  600. "lack of channel information\n");
  601. return 0;
  602. }
  603. if (track->multichannel_as_mono)
  604. return 0;
  605. avio_wb32(pb, 0); // Size
  606. ffio_wfourcc(pb, "chan"); // Type
  607. avio_w8(pb, 0); // Version
  608. avio_wb24(pb, 0); // Flags
  609. avio_wb32(pb, layout_tag); // mChannelLayoutTag
  610. avio_wb32(pb, bitmap); // mChannelBitmap
  611. avio_wb32(pb, 0); // mNumberChannelDescriptions
  612. return update_size(pb, pos);
  613. }
  614. static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  615. {
  616. int64_t pos = avio_tell(pb);
  617. avio_wb32(pb, 0); /* size */
  618. ffio_wfourcc(pb, "wave");
  619. if (track->par->codec_id != AV_CODEC_ID_QDM2) {
  620. avio_wb32(pb, 12); /* size */
  621. ffio_wfourcc(pb, "frma");
  622. avio_wl32(pb, track->tag);
  623. }
  624. if (track->par->codec_id == AV_CODEC_ID_AAC) {
  625. /* useless atom needed by mplayer, ipod, not needed by quicktime */
  626. avio_wb32(pb, 12); /* size */
  627. ffio_wfourcc(pb, "mp4a");
  628. avio_wb32(pb, 0);
  629. mov_write_esds_tag(pb, track);
  630. } else if (mov_pcm_le_gt16(track->par->codec_id)) {
  631. mov_write_enda_tag(pb);
  632. } else if (mov_pcm_be_gt16(track->par->codec_id)) {
  633. mov_write_enda_tag_be(pb);
  634. } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
  635. mov_write_amr_tag(pb, track);
  636. } else if (track->par->codec_id == AV_CODEC_ID_AC3) {
  637. mov_write_ac3_tag(pb, track);
  638. } else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
  639. mov_write_eac3_tag(pb, track);
  640. } else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
  641. track->par->codec_id == AV_CODEC_ID_QDM2) {
  642. mov_write_extradata_tag(pb, track);
  643. } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
  644. track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
  645. mov_write_ms_tag(s, pb, track);
  646. }
  647. avio_wb32(pb, 8); /* size */
  648. avio_wb32(pb, 0); /* null tag */
  649. return update_size(pb, pos);
  650. }
  651. static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
  652. {
  653. uint8_t *unescaped;
  654. const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
  655. int unescaped_size, seq_found = 0;
  656. int level = 0, interlace = 0;
  657. int packet_seq = track->vc1_info.packet_seq;
  658. int packet_entry = track->vc1_info.packet_entry;
  659. int slices = track->vc1_info.slices;
  660. PutBitContext pbc;
  661. if (track->start_dts == AV_NOPTS_VALUE) {
  662. /* No packets written yet, vc1_info isn't authoritative yet. */
  663. /* Assume inline sequence and entry headers. */
  664. packet_seq = packet_entry = 1;
  665. av_log(NULL, AV_LOG_WARNING,
  666. "moov atom written before any packets, unable to write correct "
  667. "dvc1 atom. Set the delay_moov flag to fix this.\n");
  668. }
  669. unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
  670. if (!unescaped)
  671. return AVERROR(ENOMEM);
  672. start = find_next_marker(track->vos_data, end);
  673. for (next = start; next < end; start = next) {
  674. GetBitContext gb;
  675. int size;
  676. next = find_next_marker(start + 4, end);
  677. size = next - start - 4;
  678. if (size <= 0)
  679. continue;
  680. unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
  681. init_get_bits(&gb, unescaped, 8 * unescaped_size);
  682. if (AV_RB32(start) == VC1_CODE_SEQHDR) {
  683. int profile = get_bits(&gb, 2);
  684. if (profile != PROFILE_ADVANCED) {
  685. av_free(unescaped);
  686. return AVERROR(ENOSYS);
  687. }
  688. seq_found = 1;
  689. level = get_bits(&gb, 3);
  690. /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
  691. * width, height */
  692. skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
  693. skip_bits(&gb, 1); /* broadcast */
  694. interlace = get_bits1(&gb);
  695. skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
  696. }
  697. }
  698. if (!seq_found) {
  699. av_free(unescaped);
  700. return AVERROR(ENOSYS);
  701. }
  702. init_put_bits(&pbc, buf, 7);
  703. /* VC1DecSpecStruc */
  704. put_bits(&pbc, 4, 12); /* profile - advanced */
  705. put_bits(&pbc, 3, level);
  706. put_bits(&pbc, 1, 0); /* reserved */
  707. /* VC1AdvDecSpecStruc */
  708. put_bits(&pbc, 3, level);
  709. put_bits(&pbc, 1, 0); /* cbr */
  710. put_bits(&pbc, 6, 0); /* reserved */
  711. put_bits(&pbc, 1, !interlace); /* no interlace */
  712. put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
  713. put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
  714. put_bits(&pbc, 1, !slices); /* no slice code */
  715. put_bits(&pbc, 1, 0); /* no bframe */
  716. put_bits(&pbc, 1, 0); /* reserved */
  717. /* framerate */
  718. if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
  719. put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
  720. else
  721. put_bits32(&pbc, 0xffffffff);
  722. flush_put_bits(&pbc);
  723. av_free(unescaped);
  724. return 0;
  725. }
  726. static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
  727. {
  728. uint8_t buf[7] = { 0 };
  729. int ret;
  730. if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
  731. return ret;
  732. avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
  733. ffio_wfourcc(pb, "dvc1");
  734. avio_write(pb, buf, sizeof(buf));
  735. avio_write(pb, track->vos_data, track->vos_len);
  736. return 0;
  737. }
  738. static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
  739. {
  740. avio_wb32(pb, track->vos_len + 8);
  741. ffio_wfourcc(pb, "glbl");
  742. avio_write(pb, track->vos_data, track->vos_len);
  743. return 8 + track->vos_len;
  744. }
  745. /**
  746. * Compute flags for 'lpcm' tag.
  747. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  748. */
  749. static int mov_get_lpcm_flags(enum AVCodecID codec_id)
  750. {
  751. switch (codec_id) {
  752. case AV_CODEC_ID_PCM_F32BE:
  753. case AV_CODEC_ID_PCM_F64BE:
  754. return 11;
  755. case AV_CODEC_ID_PCM_F32LE:
  756. case AV_CODEC_ID_PCM_F64LE:
  757. return 9;
  758. case AV_CODEC_ID_PCM_U8:
  759. return 10;
  760. case AV_CODEC_ID_PCM_S16BE:
  761. case AV_CODEC_ID_PCM_S24BE:
  762. case AV_CODEC_ID_PCM_S32BE:
  763. return 14;
  764. case AV_CODEC_ID_PCM_S8:
  765. case AV_CODEC_ID_PCM_S16LE:
  766. case AV_CODEC_ID_PCM_S24LE:
  767. case AV_CODEC_ID_PCM_S32LE:
  768. return 12;
  769. default:
  770. return 0;
  771. }
  772. }
  773. static int get_cluster_duration(MOVTrack *track, int cluster_idx)
  774. {
  775. int64_t next_dts;
  776. if (cluster_idx >= track->entry)
  777. return 0;
  778. if (cluster_idx + 1 == track->entry)
  779. next_dts = track->track_duration + track->start_dts;
  780. else
  781. next_dts = track->cluster[cluster_idx + 1].dts;
  782. next_dts -= track->cluster[cluster_idx].dts;
  783. av_assert0(next_dts >= 0);
  784. av_assert0(next_dts <= INT_MAX);
  785. return next_dts;
  786. }
  787. static int get_samples_per_packet(MOVTrack *track)
  788. {
  789. int i, first_duration;
  790. // return track->par->frame_size;
  791. /* use 1 for raw PCM */
  792. if (!track->audio_vbr)
  793. return 1;
  794. /* check to see if duration is constant for all clusters */
  795. if (!track->entry)
  796. return 0;
  797. first_duration = get_cluster_duration(track, 0);
  798. for (i = 1; i < track->entry; i++) {
  799. if (get_cluster_duration(track, i) != first_duration)
  800. return 0;
  801. }
  802. return first_duration;
  803. }
  804. static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  805. {
  806. int64_t pos = avio_tell(pb);
  807. int version = 0;
  808. uint32_t tag = track->tag;
  809. if (track->mode == MODE_MOV) {
  810. if (track->timescale > UINT16_MAX) {
  811. if (mov_get_lpcm_flags(track->par->codec_id))
  812. tag = AV_RL32("lpcm");
  813. version = 2;
  814. } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
  815. mov_pcm_be_gt16(track->par->codec_id) ||
  816. track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
  817. track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  818. track->par->codec_id == AV_CODEC_ID_QDM2) {
  819. version = 1;
  820. }
  821. }
  822. avio_wb32(pb, 0); /* size */
  823. if (mov->encryption_scheme != MOV_ENC_NONE) {
  824. ffio_wfourcc(pb, "enca");
  825. } else {
  826. avio_wl32(pb, tag); // store it byteswapped
  827. }
  828. avio_wb32(pb, 0); /* Reserved */
  829. avio_wb16(pb, 0); /* Reserved */
  830. avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
  831. /* SoundDescription */
  832. avio_wb16(pb, version); /* Version */
  833. avio_wb16(pb, 0); /* Revision level */
  834. avio_wb32(pb, 0); /* Reserved */
  835. if (version == 2) {
  836. avio_wb16(pb, 3);
  837. avio_wb16(pb, 16);
  838. avio_wb16(pb, 0xfffe);
  839. avio_wb16(pb, 0);
  840. avio_wb32(pb, 0x00010000);
  841. avio_wb32(pb, 72);
  842. avio_wb64(pb, av_double2int(track->par->sample_rate));
  843. avio_wb32(pb, track->par->channels);
  844. avio_wb32(pb, 0x7F000000);
  845. avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
  846. avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
  847. avio_wb32(pb, track->sample_size);
  848. avio_wb32(pb, get_samples_per_packet(track));
  849. } else {
  850. if (track->mode == MODE_MOV) {
  851. avio_wb16(pb, track->par->channels);
  852. if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
  853. track->par->codec_id == AV_CODEC_ID_PCM_S8)
  854. avio_wb16(pb, 8); /* bits per sample */
  855. else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
  856. avio_wb16(pb, track->par->bits_per_coded_sample);
  857. else
  858. avio_wb16(pb, 16);
  859. avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
  860. } else { /* reserved for mp4/3gp */
  861. avio_wb16(pb, 2);
  862. avio_wb16(pb, 16);
  863. avio_wb16(pb, 0);
  864. }
  865. avio_wb16(pb, 0); /* packet size (= 0) */
  866. avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
  867. track->par->sample_rate : 0);
  868. avio_wb16(pb, 0); /* Reserved */
  869. }
  870. if (version == 1) { /* SoundDescription V1 extended info */
  871. if (mov_pcm_le_gt16(track->par->codec_id) ||
  872. mov_pcm_be_gt16(track->par->codec_id))
  873. avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
  874. else
  875. avio_wb32(pb, track->par->frame_size); /* Samples per packet */
  876. avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
  877. avio_wb32(pb, track->sample_size); /* Bytes per frame */
  878. avio_wb32(pb, 2); /* Bytes per sample */
  879. }
  880. if (track->mode == MODE_MOV &&
  881. (track->par->codec_id == AV_CODEC_ID_AAC ||
  882. track->par->codec_id == AV_CODEC_ID_AC3 ||
  883. track->par->codec_id == AV_CODEC_ID_EAC3 ||
  884. track->par->codec_id == AV_CODEC_ID_AMR_NB ||
  885. track->par->codec_id == AV_CODEC_ID_ALAC ||
  886. track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
  887. track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  888. track->par->codec_id == AV_CODEC_ID_QDM2 ||
  889. (mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
  890. (mov_pcm_be_gt16(track->par->codec_id) && version==1)))
  891. mov_write_wave_tag(s, pb, track);
  892. else if (track->tag == MKTAG('m','p','4','a'))
  893. mov_write_esds_tag(pb, track);
  894. else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
  895. mov_write_amr_tag(pb, track);
  896. else if (track->par->codec_id == AV_CODEC_ID_AC3)
  897. mov_write_ac3_tag(pb, track);
  898. else if (track->par->codec_id == AV_CODEC_ID_EAC3)
  899. mov_write_eac3_tag(pb, track);
  900. else if (track->par->codec_id == AV_CODEC_ID_ALAC)
  901. mov_write_extradata_tag(pb, track);
  902. else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
  903. mov_write_wfex_tag(s, pb, track);
  904. else if (track->vos_len > 0)
  905. mov_write_glbl_tag(pb, track);
  906. if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  907. mov_write_chan_tag(s, pb, track);
  908. if (mov->encryption_scheme != MOV_ENC_NONE) {
  909. ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
  910. }
  911. return update_size(pb, pos);
  912. }
  913. static int mov_write_d263_tag(AVIOContext *pb)
  914. {
  915. avio_wb32(pb, 0xf); /* size */
  916. ffio_wfourcc(pb, "d263");
  917. ffio_wfourcc(pb, "FFMP");
  918. avio_w8(pb, 0); /* decoder version */
  919. /* FIXME use AVCodecContext level/profile, when encoder will set values */
  920. avio_w8(pb, 0xa); /* level */
  921. avio_w8(pb, 0); /* profile */
  922. return 0xf;
  923. }
  924. static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
  925. {
  926. int64_t pos = avio_tell(pb);
  927. avio_wb32(pb, 0);
  928. ffio_wfourcc(pb, "avcC");
  929. ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
  930. return update_size(pb, pos);
  931. }
  932. static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  933. {
  934. int64_t pos = avio_tell(pb);
  935. avio_wb32(pb, 0);
  936. ffio_wfourcc(pb, "vpcC");
  937. avio_wb32(pb, 0); /* version & flags */
  938. ff_isom_write_vpcc(s, pb, track->par);
  939. return update_size(pb, pos);
  940. }
  941. static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
  942. {
  943. int64_t pos = avio_tell(pb);
  944. avio_wb32(pb, 0);
  945. ffio_wfourcc(pb, "hvcC");
  946. ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
  947. return update_size(pb, pos);
  948. }
  949. /* also used by all avid codecs (dv, imx, meridien) and their variants */
  950. static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
  951. {
  952. int i;
  953. int interlaced;
  954. int cid;
  955. int display_width = track->par->width;
  956. if (track->vos_data && track->vos_len > 0x29) {
  957. if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
  958. /* looks like a DNxHD bit stream */
  959. interlaced = (track->vos_data[5] & 2);
  960. cid = AV_RB32(track->vos_data + 0x28);
  961. } else {
  962. av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
  963. return 0;
  964. }
  965. } else {
  966. av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
  967. return 0;
  968. }
  969. avio_wb32(pb, 24); /* size */
  970. ffio_wfourcc(pb, "ACLR");
  971. ffio_wfourcc(pb, "ACLR");
  972. ffio_wfourcc(pb, "0001");
  973. if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
  974. track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
  975. avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
  976. } else { /* Full range (0-255) */
  977. avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
  978. }
  979. avio_wb32(pb, 0); /* unknown */
  980. if (track->tag == MKTAG('A','V','d','h')) {
  981. avio_wb32(pb, 32);
  982. ffio_wfourcc(pb, "ADHR");
  983. ffio_wfourcc(pb, "0001");
  984. avio_wb32(pb, cid);
  985. avio_wb32(pb, 0); /* unknown */
  986. avio_wb32(pb, 1); /* unknown */
  987. avio_wb32(pb, 0); /* unknown */
  988. avio_wb32(pb, 0); /* unknown */
  989. return 0;
  990. }
  991. avio_wb32(pb, 24); /* size */
  992. ffio_wfourcc(pb, "APRG");
  993. ffio_wfourcc(pb, "APRG");
  994. ffio_wfourcc(pb, "0001");
  995. avio_wb32(pb, 1); /* unknown */
  996. avio_wb32(pb, 0); /* unknown */
  997. avio_wb32(pb, 120); /* size */
  998. ffio_wfourcc(pb, "ARES");
  999. ffio_wfourcc(pb, "ARES");
  1000. ffio_wfourcc(pb, "0001");
  1001. avio_wb32(pb, cid); /* dnxhd cid, some id ? */
  1002. if ( track->par->sample_aspect_ratio.num > 0
  1003. && track->par->sample_aspect_ratio.den > 0)
  1004. display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
  1005. avio_wb32(pb, display_width);
  1006. /* values below are based on samples created with quicktime and avid codecs */
  1007. if (interlaced) {
  1008. avio_wb32(pb, track->par->height / 2);
  1009. avio_wb32(pb, 2); /* unknown */
  1010. avio_wb32(pb, 0); /* unknown */
  1011. avio_wb32(pb, 4); /* unknown */
  1012. } else {
  1013. avio_wb32(pb, track->par->height);
  1014. avio_wb32(pb, 1); /* unknown */
  1015. avio_wb32(pb, 0); /* unknown */
  1016. if (track->par->height == 1080)
  1017. avio_wb32(pb, 5); /* unknown */
  1018. else
  1019. avio_wb32(pb, 6); /* unknown */
  1020. }
  1021. /* padding */
  1022. for (i = 0; i < 10; i++)
  1023. avio_wb64(pb, 0);
  1024. return 0;
  1025. }
  1026. static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
  1027. {
  1028. avio_wb32(pb, 12);
  1029. ffio_wfourcc(pb, "DpxE");
  1030. if (track->par->extradata_size >= 12 &&
  1031. !memcmp(&track->par->extradata[4], "DpxE", 4)) {
  1032. avio_wb32(pb, track->par->extradata[11]);
  1033. } else {
  1034. avio_wb32(pb, 1);
  1035. }
  1036. return 0;
  1037. }
  1038. static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
  1039. {
  1040. int tag = track->par->codec_tag;
  1041. if (!ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id))
  1042. return 0;
  1043. if (track->par->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
  1044. else if (track->par->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
  1045. else if (track->par->codec_id == AV_CODEC_ID_VP9) tag = MKTAG('v','p','0','9');
  1046. else if (track->par->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
  1047. else if (track->par->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
  1048. else if (track->par->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
  1049. else if (track->par->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
  1050. else if (track->par->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
  1051. else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
  1052. else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
  1053. else if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
  1054. return tag;
  1055. }
  1056. static const AVCodecTag codec_ipod_tags[] = {
  1057. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  1058. { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
  1059. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  1060. { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
  1061. { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
  1062. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
  1063. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
  1064. { AV_CODEC_ID_NONE, 0 },
  1065. };
  1066. static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
  1067. {
  1068. int tag = track->par->codec_tag;
  1069. // keep original tag for subs, ipod supports both formats
  1070. if (!(track->par->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1071. (tag == MKTAG('t', 'x', '3', 'g') ||
  1072. tag == MKTAG('t', 'e', 'x', 't'))))
  1073. tag = ff_codec_get_tag(codec_ipod_tags, track->par->codec_id);
  1074. if (!av_match_ext(s->filename, "m4a") &&
  1075. !av_match_ext(s->filename, "m4b") &&
  1076. !av_match_ext(s->filename, "m4v"))
  1077. av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
  1078. "Quicktime/Ipod might not play the file\n");
  1079. return tag;
  1080. }
  1081. static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
  1082. {
  1083. int tag;
  1084. if (track->par->width == 720) { /* SD */
  1085. if (track->par->height == 480) { /* NTSC */
  1086. if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
  1087. else tag = MKTAG('d','v','c',' ');
  1088. }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
  1089. else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
  1090. else tag = MKTAG('d','v','p','p');
  1091. } else if (track->par->height == 720) { /* HD 720 line */
  1092. if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
  1093. else tag = MKTAG('d','v','h','p');
  1094. } else if (track->par->height == 1080) { /* HD 1080 line */
  1095. if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
  1096. else tag = MKTAG('d','v','h','6');
  1097. } else {
  1098. av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
  1099. return 0;
  1100. }
  1101. return tag;
  1102. }
  1103. static AVRational find_fps(AVFormatContext *s, AVStream *st)
  1104. {
  1105. AVRational rate = st->avg_frame_rate;
  1106. #if FF_API_LAVF_AVCTX
  1107. FF_DISABLE_DEPRECATION_WARNINGS
  1108. rate = av_inv_q(st->codec->time_base);
  1109. if (av_timecode_check_frame_rate(rate) < 0) {
  1110. av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
  1111. rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
  1112. rate = st->avg_frame_rate;
  1113. }
  1114. FF_ENABLE_DEPRECATION_WARNINGS
  1115. #endif
  1116. return rate;
  1117. }
  1118. static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
  1119. {
  1120. int tag = track->par->codec_tag;
  1121. int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
  1122. AVStream *st = track->st;
  1123. int rate = av_q2d(find_fps(s, st));
  1124. if (!tag)
  1125. tag = MKTAG('m', '2', 'v', '1'); //fallback tag
  1126. if (track->par->format == AV_PIX_FMT_YUV420P) {
  1127. if (track->par->width == 1280 && track->par->height == 720) {
  1128. if (!interlaced) {
  1129. if (rate == 24) tag = MKTAG('x','d','v','4');
  1130. else if (rate == 25) tag = MKTAG('x','d','v','5');
  1131. else if (rate == 30) tag = MKTAG('x','d','v','1');
  1132. else if (rate == 50) tag = MKTAG('x','d','v','a');
  1133. else if (rate == 60) tag = MKTAG('x','d','v','9');
  1134. }
  1135. } else if (track->par->width == 1440 && track->par->height == 1080) {
  1136. if (!interlaced) {
  1137. if (rate == 24) tag = MKTAG('x','d','v','6');
  1138. else if (rate == 25) tag = MKTAG('x','d','v','7');
  1139. else if (rate == 30) tag = MKTAG('x','d','v','8');
  1140. } else {
  1141. if (rate == 25) tag = MKTAG('x','d','v','3');
  1142. else if (rate == 30) tag = MKTAG('x','d','v','2');
  1143. }
  1144. } else if (track->par->width == 1920 && track->par->height == 1080) {
  1145. if (!interlaced) {
  1146. if (rate == 24) tag = MKTAG('x','d','v','d');
  1147. else if (rate == 25) tag = MKTAG('x','d','v','e');
  1148. else if (rate == 30) tag = MKTAG('x','d','v','f');
  1149. } else {
  1150. if (rate == 25) tag = MKTAG('x','d','v','c');
  1151. else if (rate == 30) tag = MKTAG('x','d','v','b');
  1152. }
  1153. }
  1154. } else if (track->par->format == AV_PIX_FMT_YUV422P) {
  1155. if (track->par->width == 1280 && track->par->height == 720) {
  1156. if (!interlaced) {
  1157. if (rate == 24) tag = MKTAG('x','d','5','4');
  1158. else if (rate == 25) tag = MKTAG('x','d','5','5');
  1159. else if (rate == 30) tag = MKTAG('x','d','5','1');
  1160. else if (rate == 50) tag = MKTAG('x','d','5','a');
  1161. else if (rate == 60) tag = MKTAG('x','d','5','9');
  1162. }
  1163. } else if (track->par->width == 1920 && track->par->height == 1080) {
  1164. if (!interlaced) {
  1165. if (rate == 24) tag = MKTAG('x','d','5','d');
  1166. else if (rate == 25) tag = MKTAG('x','d','5','e');
  1167. else if (rate == 30) tag = MKTAG('x','d','5','f');
  1168. } else {
  1169. if (rate == 25) tag = MKTAG('x','d','5','c');
  1170. else if (rate == 30) tag = MKTAG('x','d','5','b');
  1171. }
  1172. }
  1173. }
  1174. return tag;
  1175. }
  1176. static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
  1177. {
  1178. int tag = track->par->codec_tag;
  1179. int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
  1180. AVStream *st = track->st;
  1181. int rate = av_q2d(find_fps(s, st));
  1182. if (!tag)
  1183. tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
  1184. if (track->par->format == AV_PIX_FMT_YUV420P10) {
  1185. if (track->par->width == 960 && track->par->height == 720) {
  1186. if (!interlaced) {
  1187. if (rate == 24) tag = MKTAG('a','i','5','p');
  1188. else if (rate == 25) tag = MKTAG('a','i','5','q');
  1189. else if (rate == 30) tag = MKTAG('a','i','5','p');
  1190. else if (rate == 50) tag = MKTAG('a','i','5','q');
  1191. else if (rate == 60) tag = MKTAG('a','i','5','p');
  1192. }
  1193. } else if (track->par->width == 1440 && track->par->height == 1080) {
  1194. if (!interlaced) {
  1195. if (rate == 24) tag = MKTAG('a','i','5','3');
  1196. else if (rate == 25) tag = MKTAG('a','i','5','2');
  1197. else if (rate == 30) tag = MKTAG('a','i','5','3');
  1198. } else {
  1199. if (rate == 50) tag = MKTAG('a','i','5','5');
  1200. else if (rate == 60) tag = MKTAG('a','i','5','6');
  1201. }
  1202. }
  1203. } else if (track->par->format == AV_PIX_FMT_YUV422P10) {
  1204. if (track->par->width == 1280 && track->par->height == 720) {
  1205. if (!interlaced) {
  1206. if (rate == 24) tag = MKTAG('a','i','1','p');
  1207. else if (rate == 25) tag = MKTAG('a','i','1','q');
  1208. else if (rate == 30) tag = MKTAG('a','i','1','p');
  1209. else if (rate == 50) tag = MKTAG('a','i','1','q');
  1210. else if (rate == 60) tag = MKTAG('a','i','1','p');
  1211. }
  1212. } else if (track->par->width == 1920 && track->par->height == 1080) {
  1213. if (!interlaced) {
  1214. if (rate == 24) tag = MKTAG('a','i','1','3');
  1215. else if (rate == 25) tag = MKTAG('a','i','1','2');
  1216. else if (rate == 30) tag = MKTAG('a','i','1','3');
  1217. } else {
  1218. if (rate == 25) tag = MKTAG('a','i','1','5');
  1219. else if (rate == 50) tag = MKTAG('a','i','1','5');
  1220. else if (rate == 60) tag = MKTAG('a','i','1','6');
  1221. }
  1222. } else if ( track->par->width == 4096 && track->par->height == 2160
  1223. || track->par->width == 3840 && track->par->height == 2160
  1224. || track->par->width == 2048 && track->par->height == 1080) {
  1225. tag = MKTAG('a','i','v','x');
  1226. }
  1227. }
  1228. return tag;
  1229. }
  1230. static const struct {
  1231. enum AVPixelFormat pix_fmt;
  1232. uint32_t tag;
  1233. unsigned bps;
  1234. } mov_pix_fmt_tags[] = {
  1235. { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
  1236. { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
  1237. { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
  1238. { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
  1239. { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
  1240. { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
  1241. { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
  1242. { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
  1243. { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
  1244. { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
  1245. { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
  1246. { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
  1247. { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
  1248. { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
  1249. { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
  1250. };
  1251. static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
  1252. {
  1253. int tag = MKTAG('A','V','d','n');
  1254. if (track->par->profile != FF_PROFILE_UNKNOWN &&
  1255. track->par->profile != FF_PROFILE_DNXHD)
  1256. tag = MKTAG('A','V','d','h');
  1257. return tag;
  1258. }
  1259. static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
  1260. {
  1261. int tag = track->par->codec_tag;
  1262. int i;
  1263. enum AVPixelFormat pix_fmt;
  1264. for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
  1265. if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
  1266. tag = mov_pix_fmt_tags[i].tag;
  1267. track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
  1268. if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
  1269. break;
  1270. }
  1271. }
  1272. pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
  1273. track->par->bits_per_coded_sample);
  1274. if (tag == MKTAG('r','a','w',' ') &&
  1275. track->par->format != pix_fmt &&
  1276. track->par->format != AV_PIX_FMT_NONE)
  1277. av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
  1278. av_get_pix_fmt_name(track->par->format));
  1279. return tag;
  1280. }
  1281. static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
  1282. {
  1283. int tag = track->par->codec_tag;
  1284. if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
  1285. (track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
  1286. track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
  1287. track->par->codec_id == AV_CODEC_ID_H263 ||
  1288. track->par->codec_id == AV_CODEC_ID_H264 ||
  1289. track->par->codec_id == AV_CODEC_ID_DNXHD ||
  1290. track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
  1291. av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
  1292. if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
  1293. tag = mov_get_dv_codec_tag(s, track);
  1294. else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
  1295. tag = mov_get_rawvideo_codec_tag(s, track);
  1296. else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
  1297. tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
  1298. else if (track->par->codec_id == AV_CODEC_ID_H264)
  1299. tag = mov_get_h264_codec_tag(s, track);
  1300. else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
  1301. tag = mov_get_dnxhd_codec_tag(s, track);
  1302. else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  1303. tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
  1304. if (!tag) { // if no mac fcc found, try with Microsoft tags
  1305. tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
  1306. if (tag)
  1307. av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
  1308. "the file may be unplayable!\n");
  1309. }
  1310. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  1311. tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
  1312. if (!tag) { // if no mac fcc found, try with Microsoft tags
  1313. int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
  1314. if (ms_tag) {
  1315. tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
  1316. av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
  1317. "the file may be unplayable!\n");
  1318. }
  1319. }
  1320. } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
  1321. tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
  1322. }
  1323. return tag;
  1324. }
  1325. static const AVCodecTag codec_3gp_tags[] = {
  1326. { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
  1327. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  1328. { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
  1329. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  1330. { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
  1331. { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
  1332. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
  1333. { AV_CODEC_ID_NONE, 0 },
  1334. };
  1335. static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
  1336. { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
  1337. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  1338. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  1339. { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
  1340. { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
  1341. { AV_CODEC_ID_NONE, 0 },
  1342. };
  1343. static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
  1344. {
  1345. int tag;
  1346. if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
  1347. tag = mp4_get_codec_tag(s, track);
  1348. else if (track->mode == MODE_ISM) {
  1349. tag = mp4_get_codec_tag(s, track);
  1350. if (!tag && track->par->codec_id == AV_CODEC_ID_WMAPRO)
  1351. tag = MKTAG('w', 'm', 'a', ' ');
  1352. } else if (track->mode == MODE_IPOD)
  1353. tag = ipod_get_codec_tag(s, track);
  1354. else if (track->mode & MODE_3GP)
  1355. tag = ff_codec_get_tag(codec_3gp_tags, track->par->codec_id);
  1356. else if (track->mode == MODE_F4V)
  1357. tag = ff_codec_get_tag(codec_f4v_tags, track->par->codec_id);
  1358. else
  1359. tag = mov_get_codec_tag(s, track);
  1360. return tag;
  1361. }
  1362. /** Write uuid atom.
  1363. * Needed to make file play in iPods running newest firmware
  1364. * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
  1365. */
  1366. static int mov_write_uuid_tag_ipod(AVIOContext *pb)
  1367. {
  1368. avio_wb32(pb, 28);
  1369. ffio_wfourcc(pb, "uuid");
  1370. avio_wb32(pb, 0x6b6840f2);
  1371. avio_wb32(pb, 0x5f244fc5);
  1372. avio_wb32(pb, 0xba39a51b);
  1373. avio_wb32(pb, 0xcf0323f3);
  1374. avio_wb32(pb, 0x0);
  1375. return 28;
  1376. }
  1377. static const uint16_t fiel_data[] = {
  1378. 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
  1379. };
  1380. static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
  1381. {
  1382. unsigned mov_field_order = 0;
  1383. if (field_order < FF_ARRAY_ELEMS(fiel_data))
  1384. mov_field_order = fiel_data[field_order];
  1385. else
  1386. return 0;
  1387. avio_wb32(pb, 10);
  1388. ffio_wfourcc(pb, "fiel");
  1389. avio_wb16(pb, mov_field_order);
  1390. return 10;
  1391. }
  1392. static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
  1393. {
  1394. int64_t pos = avio_tell(pb);
  1395. avio_wb32(pb, 0); /* size */
  1396. avio_wl32(pb, track->tag); // store it byteswapped
  1397. avio_wb32(pb, 0); /* Reserved */
  1398. avio_wb16(pb, 0); /* Reserved */
  1399. avio_wb16(pb, 1); /* Data-reference index */
  1400. if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  1401. mov_write_esds_tag(pb, track);
  1402. else if (track->par->extradata_size)
  1403. avio_write(pb, track->par->extradata, track->par->extradata_size);
  1404. return update_size(pb, pos);
  1405. }
  1406. static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
  1407. {
  1408. AVRational sar;
  1409. av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
  1410. track->par->sample_aspect_ratio.den, INT_MAX);
  1411. avio_wb32(pb, 16);
  1412. ffio_wfourcc(pb, "pasp");
  1413. avio_wb32(pb, sar.num);
  1414. avio_wb32(pb, sar.den);
  1415. return 16;
  1416. }
  1417. static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
  1418. {
  1419. uint32_t gama = 0;
  1420. if (gamma <= 0.0)
  1421. {
  1422. gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
  1423. }
  1424. av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
  1425. if (gamma > 1e-6) {
  1426. gama = (uint32_t)lrint((double)(1<<16) * gamma);
  1427. av_log(pb, AV_LOG_DEBUG, "writing gama value %d\n", gama);
  1428. av_assert0(track->mode == MODE_MOV);
  1429. avio_wb32(pb, 12);
  1430. ffio_wfourcc(pb, "gama");
  1431. avio_wb32(pb, gama);
  1432. return 12;
  1433. }
  1434. else {
  1435. av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
  1436. }
  1437. return 0;
  1438. }
  1439. static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
  1440. {
  1441. // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
  1442. // Ref (MP4): ISO/IEC 14496-12:2012
  1443. if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
  1444. track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
  1445. track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
  1446. if ((track->par->width >= 1920 && track->par->height >= 1080)
  1447. || (track->par->width == 1280 && track->par->height == 720)) {
  1448. av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
  1449. track->par->color_primaries = AVCOL_PRI_BT709;
  1450. } else if (track->par->width == 720 && track->height == 576) {
  1451. av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
  1452. track->par->color_primaries = AVCOL_PRI_BT470BG;
  1453. } else if (track->par->width == 720 &&
  1454. (track->height == 486 || track->height == 480)) {
  1455. av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
  1456. track->par->color_primaries = AVCOL_PRI_SMPTE170M;
  1457. } else {
  1458. av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
  1459. }
  1460. switch (track->par->color_primaries) {
  1461. case AVCOL_PRI_BT709:
  1462. track->par->color_trc = AVCOL_TRC_BT709;
  1463. track->par->color_space = AVCOL_SPC_BT709;
  1464. break;
  1465. case AVCOL_PRI_SMPTE170M:
  1466. case AVCOL_PRI_BT470BG:
  1467. track->par->color_trc = AVCOL_TRC_BT709;
  1468. track->par->color_space = AVCOL_SPC_SMPTE170M;
  1469. break;
  1470. }
  1471. }
  1472. /* We should only ever be called by MOV or MP4. */
  1473. av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
  1474. avio_wb32(pb, 18 + (track->mode == MODE_MP4));
  1475. ffio_wfourcc(pb, "colr");
  1476. if (track->mode == MODE_MP4)
  1477. ffio_wfourcc(pb, "nclx");
  1478. else
  1479. ffio_wfourcc(pb, "nclc");
  1480. switch (track->par->color_primaries) {
  1481. case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
  1482. case AVCOL_PRI_SMPTE170M:
  1483. case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
  1484. case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
  1485. default: avio_wb16(pb, 2);
  1486. }
  1487. switch (track->par->color_trc) {
  1488. case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
  1489. case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
  1490. case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
  1491. default: avio_wb16(pb, 2);
  1492. }
  1493. switch (track->par->color_space) {
  1494. case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
  1495. case AVCOL_SPC_BT470BG:
  1496. case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
  1497. case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
  1498. default: avio_wb16(pb, 2);
  1499. }
  1500. if (track->mode == MODE_MP4) {
  1501. int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
  1502. avio_w8(pb, full_range << 7);
  1503. return 19;
  1504. } else {
  1505. return 18;
  1506. }
  1507. }
  1508. static void find_compressor(char * compressor_name, int len, MOVTrack *track)
  1509. {
  1510. AVDictionaryEntry *encoder;
  1511. int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
  1512. || (track->par->width == 1440 && track->par->height == 1080)
  1513. || (track->par->width == 1920 && track->par->height == 1080);
  1514. if (track->mode == MODE_MOV &&
  1515. (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
  1516. av_strlcpy(compressor_name, encoder->value, 32);
  1517. } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
  1518. int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
  1519. AVStream *st = track->st;
  1520. int rate = av_q2d(find_fps(NULL, st));
  1521. av_strlcatf(compressor_name, len, "XDCAM");
  1522. if (track->par->format == AV_PIX_FMT_YUV422P) {
  1523. av_strlcatf(compressor_name, len, " HD422");
  1524. } else if(track->par->width == 1440) {
  1525. av_strlcatf(compressor_name, len, " HD");
  1526. } else
  1527. av_strlcatf(compressor_name, len, " EX");
  1528. av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
  1529. av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
  1530. }
  1531. }
  1532. static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  1533. {
  1534. int64_t pos = avio_tell(pb);
  1535. char compressor_name[32] = { 0 };
  1536. int avid = 0;
  1537. avio_wb32(pb, 0); /* size */
  1538. if (mov->encryption_scheme != MOV_ENC_NONE) {
  1539. ffio_wfourcc(pb, "encv");
  1540. } else {
  1541. avio_wl32(pb, track->tag); // store it byteswapped
  1542. }
  1543. avio_wb32(pb, 0); /* Reserved */
  1544. avio_wb16(pb, 0); /* Reserved */
  1545. avio_wb16(pb, 1); /* Data-reference index */
  1546. avio_wb16(pb, 0); /* Codec stream version */
  1547. avio_wb16(pb, 0); /* Codec stream revision (=0) */
  1548. if (track->mode == MODE_MOV) {
  1549. ffio_wfourcc(pb, "FFMP"); /* Vendor */
  1550. if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) {
  1551. avio_wb32(pb, 0); /* Temporal Quality */
  1552. avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
  1553. } else {
  1554. avio_wb32(pb, 0x200); /* Temporal Quality = normal */
  1555. avio_wb32(pb, 0x200); /* Spatial Quality = normal */
  1556. }
  1557. } else {
  1558. avio_wb32(pb, 0); /* Reserved */
  1559. avio_wb32(pb, 0); /* Reserved */
  1560. avio_wb32(pb, 0); /* Reserved */
  1561. }
  1562. avio_wb16(pb, track->par->width); /* Video width */
  1563. avio_wb16(pb, track->height); /* Video height */
  1564. avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
  1565. avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
  1566. avio_wb32(pb, 0); /* Data size (= 0) */
  1567. avio_wb16(pb, 1); /* Frame count (= 1) */
  1568. /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
  1569. find_compressor(compressor_name, 32, track);
  1570. avio_w8(pb, strlen(compressor_name));
  1571. avio_write(pb, compressor_name, 31);
  1572. if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
  1573. avio_wb16(pb, track->par->bits_per_coded_sample |
  1574. (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
  1575. else
  1576. avio_wb16(pb, 0x18); /* Reserved */
  1577. if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
  1578. int pal_size = 1 << track->par->bits_per_coded_sample;
  1579. int i;
  1580. avio_wb16(pb, 0); /* Color table ID */
  1581. avio_wb32(pb, 0); /* Color table seed */
  1582. avio_wb16(pb, 0x8000); /* Color table flags */
  1583. avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
  1584. for (i = 0; i < pal_size; i++) {
  1585. uint32_t rgb = track->palette[i];
  1586. uint16_t r = (rgb >> 16) & 0xff;
  1587. uint16_t g = (rgb >> 8) & 0xff;
  1588. uint16_t b = rgb & 0xff;
  1589. avio_wb16(pb, 0);
  1590. avio_wb16(pb, (r << 8) | r);
  1591. avio_wb16(pb, (g << 8) | g);
  1592. avio_wb16(pb, (b << 8) | b);
  1593. }
  1594. } else
  1595. avio_wb16(pb, 0xffff); /* Reserved */
  1596. if (track->tag == MKTAG('m','p','4','v'))
  1597. mov_write_esds_tag(pb, track);
  1598. else if (track->par->codec_id == AV_CODEC_ID_H263)
  1599. mov_write_d263_tag(pb);
  1600. else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
  1601. track->par->codec_id == AV_CODEC_ID_SVQ3) {
  1602. mov_write_extradata_tag(pb, track);
  1603. avio_wb32(pb, 0);
  1604. } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
  1605. mov_write_avid_tag(pb, track);
  1606. avid = 1;
  1607. } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
  1608. mov_write_hvcc_tag(pb, track);
  1609. else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
  1610. mov_write_avcc_tag(pb, track);
  1611. if (track->mode == MODE_IPOD)
  1612. mov_write_uuid_tag_ipod(pb);
  1613. } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
  1614. mov_write_vpcc_tag(mov->fc, pb, track);
  1615. } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
  1616. mov_write_dvc1_tag(pb, track);
  1617. else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
  1618. track->par->codec_id == AV_CODEC_ID_VP6A) {
  1619. /* Don't write any potential extradata here - the cropping
  1620. * is signalled via the normal width/height fields. */
  1621. } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
  1622. if (track->par->codec_tag == MKTAG('R','1','0','k'))
  1623. mov_write_dpxe_tag(pb, track);
  1624. } else if (track->vos_len > 0)
  1625. mov_write_glbl_tag(pb, track);
  1626. if (track->par->codec_id != AV_CODEC_ID_H264 &&
  1627. track->par->codec_id != AV_CODEC_ID_MPEG4 &&
  1628. track->par->codec_id != AV_CODEC_ID_DNXHD) {
  1629. int field_order = track->par->field_order;
  1630. #if FF_API_LAVF_AVCTX
  1631. FF_DISABLE_DEPRECATION_WARNINGS
  1632. if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
  1633. field_order = track->st->codec->field_order;
  1634. FF_ENABLE_DEPRECATION_WARNINGS
  1635. #endif
  1636. if (field_order != AV_FIELD_UNKNOWN)
  1637. mov_write_fiel_tag(pb, track, field_order);
  1638. }
  1639. if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
  1640. if (track->mode == MODE_MOV)
  1641. mov_write_gama_tag(pb, track, mov->gamma);
  1642. else
  1643. av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
  1644. }
  1645. if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
  1646. if (track->mode == MODE_MOV || track->mode == MODE_MP4)
  1647. mov_write_colr_tag(pb, track);
  1648. else
  1649. av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
  1650. }
  1651. if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
  1652. mov_write_pasp_tag(pb, track);
  1653. }
  1654. if (mov->encryption_scheme != MOV_ENC_NONE) {
  1655. ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
  1656. }
  1657. /* extra padding for avid stsd */
  1658. /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
  1659. if (avid)
  1660. avio_wb32(pb, 0);
  1661. return update_size(pb, pos);
  1662. }
  1663. static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
  1664. {
  1665. int64_t pos = avio_tell(pb);
  1666. avio_wb32(pb, 0); /* size */
  1667. ffio_wfourcc(pb, "rtp ");
  1668. avio_wb32(pb, 0); /* Reserved */
  1669. avio_wb16(pb, 0); /* Reserved */
  1670. avio_wb16(pb, 1); /* Data-reference index */
  1671. avio_wb16(pb, 1); /* Hint track version */
  1672. avio_wb16(pb, 1); /* Highest compatible version */
  1673. avio_wb32(pb, track->max_packet_size); /* Max packet size */
  1674. avio_wb32(pb, 12); /* size */
  1675. ffio_wfourcc(pb, "tims");
  1676. avio_wb32(pb, track->timescale);
  1677. return update_size(pb, pos);
  1678. }
  1679. static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
  1680. {
  1681. uint64_t str_size =strlen(reel_name);
  1682. int64_t pos = avio_tell(pb);
  1683. if (str_size >= UINT16_MAX){
  1684. av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
  1685. avio_wb16(pb, 0);
  1686. return AVERROR(EINVAL);
  1687. }
  1688. avio_wb32(pb, 0); /* size */
  1689. ffio_wfourcc(pb, "name"); /* Data format */
  1690. avio_wb16(pb, str_size); /* string size */
  1691. avio_wb16(pb, track->language); /* langcode */
  1692. avio_write(pb, reel_name, str_size); /* reel name */
  1693. return update_size(pb,pos);
  1694. }
  1695. static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
  1696. {
  1697. int64_t pos = avio_tell(pb);
  1698. #if 1
  1699. int frame_duration;
  1700. int nb_frames;
  1701. AVDictionaryEntry *t = NULL;
  1702. if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
  1703. #if FF_API_LAVF_AVCTX
  1704. FF_DISABLE_DEPRECATION_WARNINGS
  1705. frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
  1706. nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
  1707. FF_ENABLE_DEPRECATION_WARNINGS
  1708. #else
  1709. av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
  1710. return AVERROR(EINVAL);
  1711. #endif
  1712. } else {
  1713. frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
  1714. nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
  1715. }
  1716. if (nb_frames > 255) {
  1717. av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
  1718. return AVERROR(EINVAL);
  1719. }
  1720. avio_wb32(pb, 0); /* size */
  1721. ffio_wfourcc(pb, "tmcd"); /* Data format */
  1722. avio_wb32(pb, 0); /* Reserved */
  1723. avio_wb32(pb, 1); /* Data reference index */
  1724. avio_wb32(pb, 0); /* Flags */
  1725. avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
  1726. avio_wb32(pb, track->timescale); /* Timescale */
  1727. avio_wb32(pb, frame_duration); /* Frame duration */
  1728. avio_w8(pb, nb_frames); /* Number of frames */
  1729. avio_w8(pb, 0); /* Reserved */
  1730. t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
  1731. if (t && utf8len(t->value) && track->mode != MODE_MP4)
  1732. mov_write_source_reference_tag(pb, track, t->value);
  1733. else
  1734. avio_wb16(pb, 0); /* zero size */
  1735. #else
  1736. avio_wb32(pb, 0); /* size */
  1737. ffio_wfourcc(pb, "tmcd"); /* Data format */
  1738. avio_wb32(pb, 0); /* Reserved */
  1739. avio_wb32(pb, 1); /* Data reference index */
  1740. if (track->par->extradata_size)
  1741. avio_write(pb, track->par->extradata, track->par->extradata_size);
  1742. #endif
  1743. return update_size(pb, pos);
  1744. }
  1745. static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  1746. {
  1747. int64_t pos = avio_tell(pb);
  1748. avio_wb32(pb, 0); /* size */
  1749. ffio_wfourcc(pb, "stsd");
  1750. avio_wb32(pb, 0); /* version & flags */
  1751. avio_wb32(pb, 1); /* entry count */
  1752. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
  1753. mov_write_video_tag(pb, mov, track);
  1754. else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  1755. mov_write_audio_tag(s, pb, mov, track);
  1756. else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
  1757. mov_write_subtitle_tag(pb, track);
  1758. else if (track->par->codec_tag == MKTAG('r','t','p',' '))
  1759. mov_write_rtp_tag(pb, track);
  1760. else if (track->par->codec_tag == MKTAG('t','m','c','d'))
  1761. mov_write_tmcd_tag(pb, track);
  1762. return update_size(pb, pos);
  1763. }
  1764. static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
  1765. {
  1766. MOVStts *ctts_entries;
  1767. uint32_t entries = 0;
  1768. uint32_t atom_size;
  1769. int i;
  1770. ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
  1771. if (!ctts_entries)
  1772. return AVERROR(ENOMEM);
  1773. ctts_entries[0].count = 1;
  1774. ctts_entries[0].duration = track->cluster[0].cts;
  1775. for (i = 1; i < track->entry; i++) {
  1776. if (track->cluster[i].cts == ctts_entries[entries].duration) {
  1777. ctts_entries[entries].count++; /* compress */
  1778. } else {
  1779. entries++;
  1780. ctts_entries[entries].duration = track->cluster[i].cts;
  1781. ctts_entries[entries].count = 1;
  1782. }
  1783. }
  1784. entries++; /* last one */
  1785. atom_size = 16 + (entries * 8);
  1786. avio_wb32(pb, atom_size); /* size */
  1787. ffio_wfourcc(pb, "ctts");
  1788. avio_wb32(pb, 0); /* version & flags */
  1789. avio_wb32(pb, entries); /* entry count */
  1790. for (i = 0; i < entries; i++) {
  1791. avio_wb32(pb, ctts_entries[i].count);
  1792. avio_wb32(pb, ctts_entries[i].duration);
  1793. }
  1794. av_free(ctts_entries);
  1795. return atom_size;
  1796. }
  1797. /* Time to sample atom */
  1798. static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
  1799. {
  1800. MOVStts *stts_entries = NULL;
  1801. uint32_t entries = -1;
  1802. uint32_t atom_size;
  1803. int i;
  1804. if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
  1805. stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
  1806. if (!stts_entries)
  1807. return AVERROR(ENOMEM);
  1808. stts_entries[0].count = track->sample_count;
  1809. stts_entries[0].duration = 1;
  1810. entries = 1;
  1811. } else {
  1812. if (track->entry) {
  1813. stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
  1814. if (!stts_entries)
  1815. return AVERROR(ENOMEM);
  1816. }
  1817. for (i = 0; i < track->entry; i++) {
  1818. int duration = get_cluster_duration(track, i);
  1819. if (i && duration == stts_entries[entries].duration) {
  1820. stts_entries[entries].count++; /* compress */
  1821. } else {
  1822. entries++;
  1823. stts_entries[entries].duration = duration;
  1824. stts_entries[entries].count = 1;
  1825. }
  1826. }
  1827. entries++; /* last one */
  1828. }
  1829. atom_size = 16 + (entries * 8);
  1830. avio_wb32(pb, atom_size); /* size */
  1831. ffio_wfourcc(pb, "stts");
  1832. avio_wb32(pb, 0); /* version & flags */
  1833. avio_wb32(pb, entries); /* entry count */
  1834. for (i = 0; i < entries; i++) {
  1835. avio_wb32(pb, stts_entries[i].count);
  1836. avio_wb32(pb, stts_entries[i].duration);
  1837. }
  1838. av_free(stts_entries);
  1839. return atom_size;
  1840. }
  1841. static int mov_write_dref_tag(AVIOContext *pb)
  1842. {
  1843. avio_wb32(pb, 28); /* size */
  1844. ffio_wfourcc(pb, "dref");
  1845. avio_wb32(pb, 0); /* version & flags */
  1846. avio_wb32(pb, 1); /* entry count */
  1847. avio_wb32(pb, 0xc); /* size */
  1848. //FIXME add the alis and rsrc atom
  1849. ffio_wfourcc(pb, "url ");
  1850. avio_wb32(pb, 1); /* version & flags */
  1851. return 28;
  1852. }
  1853. static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  1854. {
  1855. int64_t pos = avio_tell(pb);
  1856. int ret;
  1857. avio_wb32(pb, 0); /* size */
  1858. ffio_wfourcc(pb, "stbl");
  1859. mov_write_stsd_tag(s, pb, mov, track);
  1860. mov_write_stts_tag(pb, track);
  1861. if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
  1862. track->par->codec_tag == MKTAG('r','t','p',' ')) &&
  1863. track->has_keyframes && track->has_keyframes < track->entry)
  1864. mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
  1865. if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
  1866. mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
  1867. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
  1868. track->flags & MOV_TRACK_CTTS && track->entry) {
  1869. if ((ret = mov_write_ctts_tag(pb, track)) < 0)
  1870. return ret;
  1871. }
  1872. mov_write_stsc_tag(pb, track);
  1873. mov_write_stsz_tag(pb, track);
  1874. mov_write_stco_tag(pb, track);
  1875. if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
  1876. ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
  1877. }
  1878. return update_size(pb, pos);
  1879. }
  1880. static int mov_write_dinf_tag(AVIOContext *pb)
  1881. {
  1882. int64_t pos = avio_tell(pb);
  1883. avio_wb32(pb, 0); /* size */
  1884. ffio_wfourcc(pb, "dinf");
  1885. mov_write_dref_tag(pb);
  1886. return update_size(pb, pos);
  1887. }
  1888. static int mov_write_nmhd_tag(AVIOContext *pb)
  1889. {
  1890. avio_wb32(pb, 12);
  1891. ffio_wfourcc(pb, "nmhd");
  1892. avio_wb32(pb, 0);
  1893. return 12;
  1894. }
  1895. static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
  1896. {
  1897. int64_t pos = avio_tell(pb);
  1898. const char *font = "Lucida Grande";
  1899. avio_wb32(pb, 0); /* size */
  1900. ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
  1901. avio_wb32(pb, 0); /* version & flags */
  1902. avio_wb16(pb, 0); /* text font */
  1903. avio_wb16(pb, 0); /* text face */
  1904. avio_wb16(pb, 12); /* text size */
  1905. avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
  1906. avio_wb16(pb, 0x0000); /* text color (red) */
  1907. avio_wb16(pb, 0x0000); /* text color (green) */
  1908. avio_wb16(pb, 0x0000); /* text color (blue) */
  1909. avio_wb16(pb, 0xffff); /* background color (red) */
  1910. avio_wb16(pb, 0xffff); /* background color (green) */
  1911. avio_wb16(pb, 0xffff); /* background color (blue) */
  1912. avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
  1913. avio_write(pb, font, strlen(font)); /* font name */
  1914. return update_size(pb, pos);
  1915. }
  1916. static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
  1917. {
  1918. int64_t pos = avio_tell(pb);
  1919. avio_wb32(pb, 0); /* size */
  1920. ffio_wfourcc(pb, "gmhd");
  1921. avio_wb32(pb, 0x18); /* gmin size */
  1922. ffio_wfourcc(pb, "gmin");/* generic media info */
  1923. avio_wb32(pb, 0); /* version & flags */
  1924. avio_wb16(pb, 0x40); /* graphics mode = */
  1925. avio_wb16(pb, 0x8000); /* opColor (r?) */
  1926. avio_wb16(pb, 0x8000); /* opColor (g?) */
  1927. avio_wb16(pb, 0x8000); /* opColor (b?) */
  1928. avio_wb16(pb, 0); /* balance */
  1929. avio_wb16(pb, 0); /* reserved */
  1930. /*
  1931. * This special text atom is required for
  1932. * Apple Quicktime chapters. The contents
  1933. * don't appear to be documented, so the
  1934. * bytes are copied verbatim.
  1935. */
  1936. if (track->tag != MKTAG('c','6','0','8')) {
  1937. avio_wb32(pb, 0x2C); /* size */
  1938. ffio_wfourcc(pb, "text");
  1939. avio_wb16(pb, 0x01);
  1940. avio_wb32(pb, 0x00);
  1941. avio_wb32(pb, 0x00);
  1942. avio_wb32(pb, 0x00);
  1943. avio_wb32(pb, 0x01);
  1944. avio_wb32(pb, 0x00);
  1945. avio_wb32(pb, 0x00);
  1946. avio_wb32(pb, 0x00);
  1947. avio_wb32(pb, 0x00004000);
  1948. avio_wb16(pb, 0x0000);
  1949. }
  1950. if (track->par->codec_tag == MKTAG('t','m','c','d')) {
  1951. int64_t tmcd_pos = avio_tell(pb);
  1952. avio_wb32(pb, 0); /* size */
  1953. ffio_wfourcc(pb, "tmcd");
  1954. mov_write_tcmi_tag(pb, track);
  1955. update_size(pb, tmcd_pos);
  1956. }
  1957. return update_size(pb, pos);
  1958. }
  1959. static int mov_write_smhd_tag(AVIOContext *pb)
  1960. {
  1961. avio_wb32(pb, 16); /* size */
  1962. ffio_wfourcc(pb, "smhd");
  1963. avio_wb32(pb, 0); /* version & flags */
  1964. avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
  1965. avio_wb16(pb, 0); /* reserved */
  1966. return 16;
  1967. }
  1968. static int mov_write_vmhd_tag(AVIOContext *pb)
  1969. {
  1970. avio_wb32(pb, 0x14); /* size (always 0x14) */
  1971. ffio_wfourcc(pb, "vmhd");
  1972. avio_wb32(pb, 0x01); /* version & flags */
  1973. avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
  1974. return 0x14;
  1975. }
  1976. static int is_clcp_track(MOVTrack *track)
  1977. {
  1978. return track->tag == MKTAG('c','7','0','8') ||
  1979. track->tag == MKTAG('c','6','0','8');
  1980. }
  1981. static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  1982. {
  1983. const char *hdlr, *descr = NULL, *hdlr_type = NULL;
  1984. int64_t pos = avio_tell(pb);
  1985. hdlr = "dhlr";
  1986. hdlr_type = "url ";
  1987. descr = "DataHandler";
  1988. if (track) {
  1989. hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
  1990. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  1991. hdlr_type = "vide";
  1992. descr = "VideoHandler";
  1993. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  1994. hdlr_type = "soun";
  1995. descr = "SoundHandler";
  1996. } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  1997. if (is_clcp_track(track)) {
  1998. hdlr_type = "clcp";
  1999. descr = "ClosedCaptionHandler";
  2000. } else {
  2001. if (track->tag == MKTAG('t','x','3','g')) {
  2002. hdlr_type = "sbtl";
  2003. } else if (track->tag == MKTAG('m','p','4','s')) {
  2004. hdlr_type = "subp";
  2005. } else {
  2006. hdlr_type = "text";
  2007. }
  2008. descr = "SubtitleHandler";
  2009. }
  2010. } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
  2011. hdlr_type = "hint";
  2012. descr = "HintHandler";
  2013. } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
  2014. hdlr_type = "tmcd";
  2015. descr = "TimeCodeHandler";
  2016. } else {
  2017. char tag_buf[32];
  2018. av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
  2019. track->par->codec_tag);
  2020. av_log(s, AV_LOG_WARNING,
  2021. "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
  2022. tag_buf, track->par->codec_tag);
  2023. }
  2024. if (track->st) {
  2025. // hdlr.name is used by some players to identify the content title
  2026. // of the track. So if an alternate handler description is
  2027. // specified, use it.
  2028. AVDictionaryEntry *t;
  2029. t = av_dict_get(track->st->metadata, "handler", NULL, 0);
  2030. if (t && utf8len(t->value))
  2031. descr = t->value;
  2032. }
  2033. }
  2034. avio_wb32(pb, 0); /* size */
  2035. ffio_wfourcc(pb, "hdlr");
  2036. avio_wb32(pb, 0); /* Version & flags */
  2037. avio_write(pb, hdlr, 4); /* handler */
  2038. ffio_wfourcc(pb, hdlr_type); /* handler type */
  2039. avio_wb32(pb, 0); /* reserved */
  2040. avio_wb32(pb, 0); /* reserved */
  2041. avio_wb32(pb, 0); /* reserved */
  2042. if (!track || track->mode == MODE_MOV)
  2043. avio_w8(pb, strlen(descr)); /* pascal string */
  2044. avio_write(pb, descr, strlen(descr)); /* handler description */
  2045. if (track && track->mode != MODE_MOV)
  2046. avio_w8(pb, 0); /* c string */
  2047. return update_size(pb, pos);
  2048. }
  2049. static int mov_write_hmhd_tag(AVIOContext *pb)
  2050. {
  2051. /* This atom must be present, but leaving the values at zero
  2052. * seems harmless. */
  2053. avio_wb32(pb, 28); /* size */
  2054. ffio_wfourcc(pb, "hmhd");
  2055. avio_wb32(pb, 0); /* version, flags */
  2056. avio_wb16(pb, 0); /* maxPDUsize */
  2057. avio_wb16(pb, 0); /* avgPDUsize */
  2058. avio_wb32(pb, 0); /* maxbitrate */
  2059. avio_wb32(pb, 0); /* avgbitrate */
  2060. avio_wb32(pb, 0); /* reserved */
  2061. return 28;
  2062. }
  2063. static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  2064. {
  2065. int64_t pos = avio_tell(pb);
  2066. int ret;
  2067. avio_wb32(pb, 0); /* size */
  2068. ffio_wfourcc(pb, "minf");
  2069. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
  2070. mov_write_vmhd_tag(pb);
  2071. else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  2072. mov_write_smhd_tag(pb);
  2073. else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  2074. if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
  2075. mov_write_gmhd_tag(pb, track);
  2076. } else {
  2077. mov_write_nmhd_tag(pb);
  2078. }
  2079. } else if (track->tag == MKTAG('r','t','p',' ')) {
  2080. mov_write_hmhd_tag(pb);
  2081. } else if (track->tag == MKTAG('t','m','c','d')) {
  2082. if (track->mode != MODE_MOV)
  2083. mov_write_nmhd_tag(pb);
  2084. else
  2085. mov_write_gmhd_tag(pb, track);
  2086. }
  2087. if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
  2088. mov_write_hdlr_tag(s, pb, NULL);
  2089. mov_write_dinf_tag(pb);
  2090. if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
  2091. return ret;
  2092. return update_size(pb, pos);
  2093. }
  2094. static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  2095. MOVTrack *track)
  2096. {
  2097. int version = track->track_duration < INT32_MAX ? 0 : 1;
  2098. if (track->mode == MODE_ISM)
  2099. version = 1;
  2100. (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
  2101. ffio_wfourcc(pb, "mdhd");
  2102. avio_w8(pb, version);
  2103. avio_wb24(pb, 0); /* flags */
  2104. if (version == 1) {
  2105. avio_wb64(pb, track->time);
  2106. avio_wb64(pb, track->time);
  2107. } else {
  2108. avio_wb32(pb, track->time); /* creation time */
  2109. avio_wb32(pb, track->time); /* modification time */
  2110. }
  2111. avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
  2112. if (!track->entry && mov->mode == MODE_ISM)
  2113. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  2114. else if (!track->entry)
  2115. (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
  2116. else
  2117. (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
  2118. avio_wb16(pb, track->language); /* language */
  2119. avio_wb16(pb, 0); /* reserved (quality) */
  2120. if (version != 0 && track->mode == MODE_MOV) {
  2121. av_log(NULL, AV_LOG_ERROR,
  2122. "FATAL error, file duration too long for timebase, this file will not be\n"
  2123. "playable with quicktime. Choose a different timebase or a different\n"
  2124. "container format\n");
  2125. }
  2126. return 32;
  2127. }
  2128. static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
  2129. MOVMuxContext *mov, MOVTrack *track)
  2130. {
  2131. int64_t pos = avio_tell(pb);
  2132. int ret;
  2133. avio_wb32(pb, 0); /* size */
  2134. ffio_wfourcc(pb, "mdia");
  2135. mov_write_mdhd_tag(pb, mov, track);
  2136. mov_write_hdlr_tag(s, pb, track);
  2137. if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
  2138. return ret;
  2139. return update_size(pb, pos);
  2140. }
  2141. /* transformation matrix
  2142. |a b u|
  2143. |c d v|
  2144. |tx ty w| */
  2145. static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
  2146. int16_t d, int16_t tx, int16_t ty)
  2147. {
  2148. avio_wb32(pb, a << 16); /* 16.16 format */
  2149. avio_wb32(pb, b << 16); /* 16.16 format */
  2150. avio_wb32(pb, 0); /* u in 2.30 format */
  2151. avio_wb32(pb, c << 16); /* 16.16 format */
  2152. avio_wb32(pb, d << 16); /* 16.16 format */
  2153. avio_wb32(pb, 0); /* v in 2.30 format */
  2154. avio_wb32(pb, tx << 16); /* 16.16 format */
  2155. avio_wb32(pb, ty << 16); /* 16.16 format */
  2156. avio_wb32(pb, 1 << 30); /* w in 2.30 format */
  2157. }
  2158. static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  2159. MOVTrack *track, AVStream *st)
  2160. {
  2161. int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
  2162. track->timescale, AV_ROUND_UP);
  2163. int version = duration < INT32_MAX ? 0 : 1;
  2164. int flags = MOV_TKHD_FLAG_IN_MOVIE;
  2165. int rotation = 0;
  2166. int group = 0;
  2167. uint32_t *display_matrix = NULL;
  2168. int display_matrix_size, i;
  2169. if (st) {
  2170. if (mov->per_stream_grouping)
  2171. group = st->index;
  2172. else
  2173. group = st->codecpar->codec_type;
  2174. display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
  2175. &display_matrix_size);
  2176. if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
  2177. display_matrix = NULL;
  2178. }
  2179. if (track->flags & MOV_TRACK_ENABLED)
  2180. flags |= MOV_TKHD_FLAG_ENABLED;
  2181. if (track->mode == MODE_ISM)
  2182. version = 1;
  2183. (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
  2184. ffio_wfourcc(pb, "tkhd");
  2185. avio_w8(pb, version);
  2186. avio_wb24(pb, flags);
  2187. if (version == 1) {
  2188. avio_wb64(pb, track->time);
  2189. avio_wb64(pb, track->time);
  2190. } else {
  2191. avio_wb32(pb, track->time); /* creation time */
  2192. avio_wb32(pb, track->time); /* modification time */
  2193. }
  2194. avio_wb32(pb, track->track_id); /* track-id */
  2195. avio_wb32(pb, 0); /* reserved */
  2196. if (!track->entry && mov->mode == MODE_ISM)
  2197. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  2198. else if (!track->entry)
  2199. (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
  2200. else
  2201. (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
  2202. avio_wb32(pb, 0); /* reserved */
  2203. avio_wb32(pb, 0); /* reserved */
  2204. avio_wb16(pb, 0); /* layer */
  2205. avio_wb16(pb, group); /* alternate group) */
  2206. /* Volume, only for audio */
  2207. if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  2208. avio_wb16(pb, 0x0100);
  2209. else
  2210. avio_wb16(pb, 0);
  2211. avio_wb16(pb, 0); /* reserved */
  2212. /* Matrix structure */
  2213. if (st && st->metadata) {
  2214. AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
  2215. rotation = (rot && rot->value) ? atoi(rot->value) : 0;
  2216. }
  2217. if (display_matrix) {
  2218. for (i = 0; i < 9; i++)
  2219. avio_wb32(pb, display_matrix[i]);
  2220. } else if (rotation == 90) {
  2221. write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
  2222. } else if (rotation == 180) {
  2223. write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
  2224. } else if (rotation == 270) {
  2225. write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
  2226. } else {
  2227. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  2228. }
  2229. /* Track width and height, for visual only */
  2230. if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
  2231. track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
  2232. int64_t track_width_1616;
  2233. if (track->mode == MODE_MOV) {
  2234. track_width_1616 = track->par->width * 0x10000ULL;
  2235. } else {
  2236. track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
  2237. track->par->width * 0x10000LL,
  2238. st->sample_aspect_ratio.den);
  2239. if (!track_width_1616 ||
  2240. track->height != track->par->height ||
  2241. track_width_1616 > UINT32_MAX)
  2242. track_width_1616 = track->par->width * 0x10000ULL;
  2243. }
  2244. if (track_width_1616 > UINT32_MAX) {
  2245. av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
  2246. track_width_1616 = 0;
  2247. }
  2248. avio_wb32(pb, track_width_1616);
  2249. if (track->height > 0xFFFF) {
  2250. av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
  2251. avio_wb32(pb, 0);
  2252. } else
  2253. avio_wb32(pb, track->height * 0x10000U);
  2254. } else {
  2255. avio_wb32(pb, 0);
  2256. avio_wb32(pb, 0);
  2257. }
  2258. return 0x5c;
  2259. }
  2260. static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
  2261. {
  2262. int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
  2263. track->par->sample_aspect_ratio.den);
  2264. int64_t pos = avio_tell(pb);
  2265. avio_wb32(pb, 0); /* size */
  2266. ffio_wfourcc(pb, "tapt");
  2267. avio_wb32(pb, 20);
  2268. ffio_wfourcc(pb, "clef");
  2269. avio_wb32(pb, 0);
  2270. avio_wb32(pb, width << 16);
  2271. avio_wb32(pb, track->par->height << 16);
  2272. avio_wb32(pb, 20);
  2273. ffio_wfourcc(pb, "prof");
  2274. avio_wb32(pb, 0);
  2275. avio_wb32(pb, width << 16);
  2276. avio_wb32(pb, track->par->height << 16);
  2277. avio_wb32(pb, 20);
  2278. ffio_wfourcc(pb, "enof");
  2279. avio_wb32(pb, 0);
  2280. avio_wb32(pb, track->par->width << 16);
  2281. avio_wb32(pb, track->par->height << 16);
  2282. return update_size(pb, pos);
  2283. }
  2284. // This box seems important for the psp playback ... without it the movie seems to hang
  2285. static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
  2286. MOVTrack *track)
  2287. {
  2288. int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
  2289. track->timescale, AV_ROUND_UP);
  2290. int version = duration < INT32_MAX ? 0 : 1;
  2291. int entry_size, entry_count, size;
  2292. int64_t delay, start_ct = track->start_cts;
  2293. int64_t start_dts = track->start_dts;
  2294. if (track->entry) {
  2295. if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
  2296. av_log(mov->fc, AV_LOG_DEBUG,
  2297. "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
  2298. track->cluster[0].dts, track->cluster[0].cts,
  2299. start_dts, start_ct, track->track_id);
  2300. start_dts = track->cluster[0].dts;
  2301. start_ct = track->cluster[0].cts;
  2302. }
  2303. }
  2304. delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
  2305. track->timescale, AV_ROUND_DOWN);
  2306. version |= delay < INT32_MAX ? 0 : 1;
  2307. entry_size = (version == 1) ? 20 : 12;
  2308. entry_count = 1 + (delay > 0);
  2309. size = 24 + entry_count * entry_size;
  2310. /* write the atom data */
  2311. avio_wb32(pb, size);
  2312. ffio_wfourcc(pb, "edts");
  2313. avio_wb32(pb, size - 8);
  2314. ffio_wfourcc(pb, "elst");
  2315. avio_w8(pb, version);
  2316. avio_wb24(pb, 0); /* flags */
  2317. avio_wb32(pb, entry_count);
  2318. if (delay > 0) { /* add an empty edit to delay presentation */
  2319. /* In the positive delay case, the delay includes the cts
  2320. * offset, and the second edit list entry below trims out
  2321. * the same amount from the actual content. This makes sure
  2322. * that the offset last sample is included in the edit
  2323. * list duration as well. */
  2324. if (version == 1) {
  2325. avio_wb64(pb, delay);
  2326. avio_wb64(pb, -1);
  2327. } else {
  2328. avio_wb32(pb, delay);
  2329. avio_wb32(pb, -1);
  2330. }
  2331. avio_wb32(pb, 0x00010000);
  2332. } else {
  2333. /* Avoid accidentally ending up with start_ct = -1 which has got a
  2334. * special meaning. Normally start_ct should end up positive or zero
  2335. * here, but use FFMIN in case dts is a small positive integer
  2336. * rounded to 0 when represented in MOV_TIMESCALE units. */
  2337. av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
  2338. start_ct = -FFMIN(start_dts, 0);
  2339. /* Note, this delay is calculated from the pts of the first sample,
  2340. * ensuring that we don't reduce the duration for cases with
  2341. * dts<0 pts=0. */
  2342. duration += delay;
  2343. }
  2344. /* For fragmented files, we don't know the full length yet. Setting
  2345. * duration to 0 allows us to only specify the offset, including
  2346. * the rest of the content (from all future fragments) without specifying
  2347. * an explicit duration. */
  2348. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  2349. duration = 0;
  2350. /* duration */
  2351. if (version == 1) {
  2352. avio_wb64(pb, duration);
  2353. avio_wb64(pb, start_ct);
  2354. } else {
  2355. avio_wb32(pb, duration);
  2356. avio_wb32(pb, start_ct);
  2357. }
  2358. avio_wb32(pb, 0x00010000);
  2359. return size;
  2360. }
  2361. static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
  2362. {
  2363. avio_wb32(pb, 20); // size
  2364. ffio_wfourcc(pb, "tref");
  2365. avio_wb32(pb, 12); // size (subatom)
  2366. avio_wl32(pb, track->tref_tag);
  2367. avio_wb32(pb, track->tref_id);
  2368. return 20;
  2369. }
  2370. // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
  2371. static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
  2372. {
  2373. avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
  2374. ffio_wfourcc(pb, "uuid");
  2375. ffio_wfourcc(pb, "USMT");
  2376. avio_wb32(pb, 0x21d24fce);
  2377. avio_wb32(pb, 0xbb88695c);
  2378. avio_wb32(pb, 0xfac9c740);
  2379. avio_wb32(pb, 0x1c); // another size here!
  2380. ffio_wfourcc(pb, "MTDT");
  2381. avio_wb32(pb, 0x00010012);
  2382. avio_wb32(pb, 0x0a);
  2383. avio_wb32(pb, 0x55c40000);
  2384. avio_wb32(pb, 0x1);
  2385. avio_wb32(pb, 0x0);
  2386. return 0x34;
  2387. }
  2388. static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
  2389. {
  2390. AVFormatContext *ctx = track->rtp_ctx;
  2391. char buf[1000] = "";
  2392. int len;
  2393. ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
  2394. NULL, NULL, 0, 0, ctx);
  2395. av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
  2396. len = strlen(buf);
  2397. avio_wb32(pb, len + 24);
  2398. ffio_wfourcc(pb, "udta");
  2399. avio_wb32(pb, len + 16);
  2400. ffio_wfourcc(pb, "hnti");
  2401. avio_wb32(pb, len + 8);
  2402. ffio_wfourcc(pb, "sdp ");
  2403. avio_write(pb, buf, len);
  2404. return len + 24;
  2405. }
  2406. static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
  2407. const char *tag, const char *str)
  2408. {
  2409. int64_t pos = avio_tell(pb);
  2410. AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
  2411. if (!t || !utf8len(t->value))
  2412. return 0;
  2413. avio_wb32(pb, 0); /* size */
  2414. ffio_wfourcc(pb, tag); /* type */
  2415. avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
  2416. return update_size(pb, pos);
  2417. }
  2418. static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2419. AVStream *st)
  2420. {
  2421. AVIOContext *pb_buf;
  2422. int ret, size;
  2423. uint8_t *buf;
  2424. if (!st)
  2425. return 0;
  2426. ret = avio_open_dyn_buf(&pb_buf);
  2427. if (ret < 0)
  2428. return ret;
  2429. if (mov->mode & MODE_MP4)
  2430. mov_write_track_metadata(pb_buf, st, "name", "title");
  2431. if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
  2432. avio_wb32(pb, size + 8);
  2433. ffio_wfourcc(pb, "udta");
  2434. avio_write(pb, buf, size);
  2435. }
  2436. av_free(buf);
  2437. return 0;
  2438. }
  2439. static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
  2440. MOVTrack *track, AVStream *st)
  2441. {
  2442. int64_t pos = avio_tell(pb);
  2443. int entry_backup = track->entry;
  2444. int chunk_backup = track->chunkCount;
  2445. int ret;
  2446. /* If we want to have an empty moov, but some samples already have been
  2447. * buffered (delay_moov), pretend that no samples have been written yet. */
  2448. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
  2449. track->chunkCount = track->entry = 0;
  2450. avio_wb32(pb, 0); /* size */
  2451. ffio_wfourcc(pb, "trak");
  2452. mov_write_tkhd_tag(pb, mov, track, st);
  2453. av_assert2(mov->use_editlist >= 0);
  2454. if (track->start_dts != AV_NOPTS_VALUE) {
  2455. if (mov->use_editlist)
  2456. mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
  2457. else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
  2458. av_log(mov->fc, AV_LOG_WARNING,
  2459. "Not writing any edit list even though one would have been required\n");
  2460. }
  2461. if (track->tref_tag)
  2462. mov_write_tref_tag(pb, track);
  2463. if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
  2464. return ret;
  2465. if (track->mode == MODE_PSP)
  2466. mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
  2467. if (track->tag == MKTAG('r','t','p',' '))
  2468. mov_write_udta_sdp(pb, track);
  2469. if (track->mode == MODE_MOV) {
  2470. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  2471. double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
  2472. if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
  2473. mov_write_tapt_tag(pb, track);
  2474. }
  2475. }
  2476. if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
  2477. mov_write_tapt_tag(pb, track);
  2478. }
  2479. }
  2480. mov_write_track_udta_tag(pb, mov, st);
  2481. track->entry = entry_backup;
  2482. track->chunkCount = chunk_backup;
  2483. return update_size(pb, pos);
  2484. }
  2485. static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
  2486. {
  2487. int i, has_audio = 0, has_video = 0;
  2488. int64_t pos = avio_tell(pb);
  2489. int audio_profile = mov->iods_audio_profile;
  2490. int video_profile = mov->iods_video_profile;
  2491. for (i = 0; i < mov->nb_streams; i++) {
  2492. if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  2493. has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
  2494. has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
  2495. }
  2496. }
  2497. if (audio_profile < 0)
  2498. audio_profile = 0xFF - has_audio;
  2499. if (video_profile < 0)
  2500. video_profile = 0xFF - has_video;
  2501. avio_wb32(pb, 0x0); /* size */
  2502. ffio_wfourcc(pb, "iods");
  2503. avio_wb32(pb, 0); /* version & flags */
  2504. put_descr(pb, 0x10, 7);
  2505. avio_wb16(pb, 0x004f);
  2506. avio_w8(pb, 0xff);
  2507. avio_w8(pb, 0xff);
  2508. avio_w8(pb, audio_profile);
  2509. avio_w8(pb, video_profile);
  2510. avio_w8(pb, 0xff);
  2511. return update_size(pb, pos);
  2512. }
  2513. static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
  2514. {
  2515. avio_wb32(pb, 0x20); /* size */
  2516. ffio_wfourcc(pb, "trex");
  2517. avio_wb32(pb, 0); /* version & flags */
  2518. avio_wb32(pb, track->track_id); /* track ID */
  2519. avio_wb32(pb, 1); /* default sample description index */
  2520. avio_wb32(pb, 0); /* default sample duration */
  2521. avio_wb32(pb, 0); /* default sample size */
  2522. avio_wb32(pb, 0); /* default sample flags */
  2523. return 0;
  2524. }
  2525. static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
  2526. {
  2527. int64_t pos = avio_tell(pb);
  2528. int i;
  2529. avio_wb32(pb, 0x0); /* size */
  2530. ffio_wfourcc(pb, "mvex");
  2531. for (i = 0; i < mov->nb_streams; i++)
  2532. mov_write_trex_tag(pb, &mov->tracks[i]);
  2533. return update_size(pb, pos);
  2534. }
  2535. static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  2536. {
  2537. int max_track_id = 1, i;
  2538. int64_t max_track_len = 0;
  2539. int version;
  2540. for (i = 0; i < mov->nb_streams; i++) {
  2541. if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
  2542. int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
  2543. MOV_TIMESCALE,
  2544. mov->tracks[i].timescale,
  2545. AV_ROUND_UP);
  2546. if (max_track_len < max_track_len_temp)
  2547. max_track_len = max_track_len_temp;
  2548. if (max_track_id < mov->tracks[i].track_id)
  2549. max_track_id = mov->tracks[i].track_id;
  2550. }
  2551. }
  2552. /* If using delay_moov, make sure the output is the same as if no
  2553. * samples had been written yet. */
  2554. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  2555. max_track_len = 0;
  2556. max_track_id = 1;
  2557. }
  2558. version = max_track_len < UINT32_MAX ? 0 : 1;
  2559. avio_wb32(pb, version == 1 ? 120 : 108); /* size */
  2560. ffio_wfourcc(pb, "mvhd");
  2561. avio_w8(pb, version);
  2562. avio_wb24(pb, 0); /* flags */
  2563. if (version == 1) {
  2564. avio_wb64(pb, mov->time);
  2565. avio_wb64(pb, mov->time);
  2566. } else {
  2567. avio_wb32(pb, mov->time); /* creation time */
  2568. avio_wb32(pb, mov->time); /* modification time */
  2569. }
  2570. avio_wb32(pb, MOV_TIMESCALE);
  2571. (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
  2572. avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
  2573. avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
  2574. avio_wb16(pb, 0); /* reserved */
  2575. avio_wb32(pb, 0); /* reserved */
  2576. avio_wb32(pb, 0); /* reserved */
  2577. /* Matrix structure */
  2578. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  2579. avio_wb32(pb, 0); /* reserved (preview time) */
  2580. avio_wb32(pb, 0); /* reserved (preview duration) */
  2581. avio_wb32(pb, 0); /* reserved (poster time) */
  2582. avio_wb32(pb, 0); /* reserved (selection time) */
  2583. avio_wb32(pb, 0); /* reserved (selection duration) */
  2584. avio_wb32(pb, 0); /* reserved (current time) */
  2585. avio_wb32(pb, max_track_id + 1); /* Next track id */
  2586. return 0x6c;
  2587. }
  2588. static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
  2589. AVFormatContext *s)
  2590. {
  2591. avio_wb32(pb, 33); /* size */
  2592. ffio_wfourcc(pb, "hdlr");
  2593. avio_wb32(pb, 0);
  2594. avio_wb32(pb, 0);
  2595. ffio_wfourcc(pb, "mdir");
  2596. ffio_wfourcc(pb, "appl");
  2597. avio_wb32(pb, 0);
  2598. avio_wb32(pb, 0);
  2599. avio_w8(pb, 0);
  2600. return 33;
  2601. }
  2602. /* helper function to write a data tag with the specified string as data */
  2603. static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
  2604. {
  2605. if (long_style) {
  2606. int size = 16 + strlen(data);
  2607. avio_wb32(pb, size); /* size */
  2608. ffio_wfourcc(pb, "data");
  2609. avio_wb32(pb, 1);
  2610. avio_wb32(pb, 0);
  2611. avio_write(pb, data, strlen(data));
  2612. return size;
  2613. } else {
  2614. if (!lang)
  2615. lang = ff_mov_iso639_to_lang("und", 1);
  2616. avio_wb16(pb, strlen(data)); /* string length */
  2617. avio_wb16(pb, lang);
  2618. avio_write(pb, data, strlen(data));
  2619. return strlen(data) + 4;
  2620. }
  2621. }
  2622. static int mov_write_string_tag(AVIOContext *pb, const char *name,
  2623. const char *value, int lang, int long_style)
  2624. {
  2625. int size = 0;
  2626. if (value && value[0]) {
  2627. int64_t pos = avio_tell(pb);
  2628. avio_wb32(pb, 0); /* size */
  2629. ffio_wfourcc(pb, name);
  2630. mov_write_string_data_tag(pb, value, lang, long_style);
  2631. size = update_size(pb, pos);
  2632. }
  2633. return size;
  2634. }
  2635. static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
  2636. const char *tag, int *lang)
  2637. {
  2638. int l, len, len2;
  2639. AVDictionaryEntry *t, *t2 = NULL;
  2640. char tag2[16];
  2641. *lang = 0;
  2642. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  2643. return NULL;
  2644. len = strlen(t->key);
  2645. snprintf(tag2, sizeof(tag2), "%s-", tag);
  2646. while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
  2647. len2 = strlen(t2->key);
  2648. if (len2 == len + 4 && !strcmp(t->value, t2->value)
  2649. && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
  2650. *lang = l;
  2651. return t;
  2652. }
  2653. }
  2654. return t;
  2655. }
  2656. static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
  2657. const char *name, const char *tag,
  2658. int long_style)
  2659. {
  2660. int lang;
  2661. AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
  2662. if (!t)
  2663. return 0;
  2664. return mov_write_string_tag(pb, name, t->value, lang, long_style);
  2665. }
  2666. /* iTunes bpm number */
  2667. static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
  2668. {
  2669. AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
  2670. int size = 0, tmpo = t ? atoi(t->value) : 0;
  2671. if (tmpo) {
  2672. size = 26;
  2673. avio_wb32(pb, size);
  2674. ffio_wfourcc(pb, "tmpo");
  2675. avio_wb32(pb, size-8); /* size */
  2676. ffio_wfourcc(pb, "data");
  2677. avio_wb32(pb, 0x15); //type specifier
  2678. avio_wb32(pb, 0);
  2679. avio_wb16(pb, tmpo); // data
  2680. }
  2681. return size;
  2682. }
  2683. /* 3GPP TS 26.244 */
  2684. static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
  2685. {
  2686. int lang;
  2687. int64_t pos = avio_tell(pb);
  2688. double latitude, longitude, altitude;
  2689. int32_t latitude_fix, longitude_fix, altitude_fix;
  2690. AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
  2691. const char *ptr, *place = "";
  2692. char *end;
  2693. static const char *astronomical_body = "earth";
  2694. if (!t)
  2695. return 0;
  2696. ptr = t->value;
  2697. longitude = strtod(ptr, &end);
  2698. if (end == ptr) {
  2699. av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
  2700. return 0;
  2701. }
  2702. ptr = end;
  2703. latitude = strtod(ptr, &end);
  2704. if (end == ptr) {
  2705. av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
  2706. return 0;
  2707. }
  2708. ptr = end;
  2709. altitude = strtod(ptr, &end);
  2710. /* If no altitude was present, the default 0 should be fine */
  2711. if (*end == '/')
  2712. place = end + 1;
  2713. latitude_fix = (int32_t) ((1 << 16) * latitude);
  2714. longitude_fix = (int32_t) ((1 << 16) * longitude);
  2715. altitude_fix = (int32_t) ((1 << 16) * altitude);
  2716. avio_wb32(pb, 0); /* size */
  2717. ffio_wfourcc(pb, "loci"); /* type */
  2718. avio_wb32(pb, 0); /* version + flags */
  2719. avio_wb16(pb, lang);
  2720. avio_write(pb, place, strlen(place) + 1);
  2721. avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
  2722. avio_wb32(pb, latitude_fix);
  2723. avio_wb32(pb, longitude_fix);
  2724. avio_wb32(pb, altitude_fix);
  2725. avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
  2726. avio_w8(pb, 0); /* additional notes, null terminated string */
  2727. return update_size(pb, pos);
  2728. }
  2729. /* iTunes track or disc number */
  2730. static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
  2731. AVFormatContext *s, int disc)
  2732. {
  2733. AVDictionaryEntry *t = av_dict_get(s->metadata,
  2734. disc ? "disc" : "track",
  2735. NULL, 0);
  2736. int size = 0, track = t ? atoi(t->value) : 0;
  2737. if (track) {
  2738. int tracks = 0;
  2739. char *slash = strchr(t->value, '/');
  2740. if (slash)
  2741. tracks = atoi(slash + 1);
  2742. avio_wb32(pb, 32); /* size */
  2743. ffio_wfourcc(pb, disc ? "disk" : "trkn");
  2744. avio_wb32(pb, 24); /* size */
  2745. ffio_wfourcc(pb, "data");
  2746. avio_wb32(pb, 0); // 8 bytes empty
  2747. avio_wb32(pb, 0);
  2748. avio_wb16(pb, 0); // empty
  2749. avio_wb16(pb, track); // track / disc number
  2750. avio_wb16(pb, tracks); // total track / disc number
  2751. avio_wb16(pb, 0); // empty
  2752. size = 32;
  2753. }
  2754. return size;
  2755. }
  2756. static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
  2757. const char *name, const char *tag,
  2758. int len)
  2759. {
  2760. AVDictionaryEntry *t = NULL;
  2761. uint8_t num;
  2762. int size = 24 + len;
  2763. if (len != 1 && len != 4)
  2764. return -1;
  2765. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  2766. return 0;
  2767. num = atoi(t->value);
  2768. avio_wb32(pb, size);
  2769. ffio_wfourcc(pb, name);
  2770. avio_wb32(pb, size - 8);
  2771. ffio_wfourcc(pb, "data");
  2772. avio_wb32(pb, 0x15);
  2773. avio_wb32(pb, 0);
  2774. if (len==4) avio_wb32(pb, num);
  2775. else avio_w8 (pb, num);
  2776. return size;
  2777. }
  2778. /* iTunes meta data list */
  2779. static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
  2780. AVFormatContext *s)
  2781. {
  2782. int64_t pos = avio_tell(pb);
  2783. avio_wb32(pb, 0); /* size */
  2784. ffio_wfourcc(pb, "ilst");
  2785. mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
  2786. mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
  2787. mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
  2788. mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
  2789. mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
  2790. mov_write_string_metadata(s, pb, "\251day", "date" , 1);
  2791. if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
  2792. if (!(s->flags & AVFMT_FLAG_BITEXACT))
  2793. mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
  2794. }
  2795. mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
  2796. mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
  2797. mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
  2798. mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
  2799. mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
  2800. mov_write_string_metadata(s, pb, "desc", "description",1);
  2801. mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
  2802. mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
  2803. mov_write_string_metadata(s, pb, "tven", "episode_id",1);
  2804. mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
  2805. mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
  2806. mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
  2807. mov_write_int8_metadata (s, pb, "stik", "media_type",1);
  2808. mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
  2809. mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
  2810. mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
  2811. mov_write_trkn_tag(pb, mov, s, 0); // track number
  2812. mov_write_trkn_tag(pb, mov, s, 1); // disc number
  2813. mov_write_tmpo_tag(pb, s);
  2814. return update_size(pb, pos);
  2815. }
  2816. static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
  2817. AVFormatContext *s)
  2818. {
  2819. avio_wb32(pb, 33); /* size */
  2820. ffio_wfourcc(pb, "hdlr");
  2821. avio_wb32(pb, 0);
  2822. avio_wb32(pb, 0);
  2823. ffio_wfourcc(pb, "mdta");
  2824. avio_wb32(pb, 0);
  2825. avio_wb32(pb, 0);
  2826. avio_wb32(pb, 0);
  2827. avio_w8(pb, 0);
  2828. return 33;
  2829. }
  2830. static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
  2831. AVFormatContext *s)
  2832. {
  2833. AVDictionaryEntry *t = NULL;
  2834. int64_t pos = avio_tell(pb);
  2835. int64_t curpos, entry_pos;
  2836. int count = 0;
  2837. avio_wb32(pb, 0); /* size */
  2838. ffio_wfourcc(pb, "keys");
  2839. avio_wb32(pb, 0);
  2840. entry_pos = avio_tell(pb);
  2841. avio_wb32(pb, 0); /* entry count */
  2842. while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
  2843. avio_wb32(pb, strlen(t->key) + 8);
  2844. ffio_wfourcc(pb, "mdta");
  2845. avio_write(pb, t->key, strlen(t->key));
  2846. count += 1;
  2847. }
  2848. curpos = avio_tell(pb);
  2849. avio_seek(pb, entry_pos, SEEK_SET);
  2850. avio_wb32(pb, count); // rewrite entry count
  2851. avio_seek(pb, curpos, SEEK_SET);
  2852. return update_size(pb, pos);
  2853. }
  2854. static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
  2855. AVFormatContext *s)
  2856. {
  2857. AVDictionaryEntry *t = NULL;
  2858. int64_t pos = avio_tell(pb);
  2859. int count = 1; /* keys are 1-index based */
  2860. avio_wb32(pb, 0); /* size */
  2861. ffio_wfourcc(pb, "ilst");
  2862. while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
  2863. int64_t entry_pos = avio_tell(pb);
  2864. avio_wb32(pb, 0); /* size */
  2865. avio_wb32(pb, count); /* key */
  2866. mov_write_string_data_tag(pb, t->value, 0, 1);
  2867. update_size(pb, entry_pos);
  2868. count += 1;
  2869. }
  2870. return update_size(pb, pos);
  2871. }
  2872. /* meta data tags */
  2873. static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2874. AVFormatContext *s)
  2875. {
  2876. int size = 0;
  2877. int64_t pos = avio_tell(pb);
  2878. avio_wb32(pb, 0); /* size */
  2879. ffio_wfourcc(pb, "meta");
  2880. avio_wb32(pb, 0);
  2881. if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
  2882. mov_write_mdta_hdlr_tag(pb, mov, s);
  2883. mov_write_mdta_keys_tag(pb, mov, s);
  2884. mov_write_mdta_ilst_tag(pb, mov, s);
  2885. }
  2886. else {
  2887. /* iTunes metadata tag */
  2888. mov_write_itunes_hdlr_tag(pb, mov, s);
  2889. mov_write_ilst_tag(pb, mov, s);
  2890. }
  2891. size = update_size(pb, pos);
  2892. return size;
  2893. }
  2894. static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
  2895. const char *name, const char *key)
  2896. {
  2897. int len;
  2898. AVDictionaryEntry *t;
  2899. if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
  2900. return 0;
  2901. len = strlen(t->value);
  2902. if (len > 0) {
  2903. int size = len + 8;
  2904. avio_wb32(pb, size);
  2905. ffio_wfourcc(pb, name);
  2906. avio_write(pb, t->value, len);
  2907. return size;
  2908. }
  2909. return 0;
  2910. }
  2911. static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
  2912. {
  2913. int val;
  2914. while (*b) {
  2915. GET_UTF8(val, *b++, return -1;)
  2916. avio_wb16(pb, val);
  2917. }
  2918. avio_wb16(pb, 0x00);
  2919. return 0;
  2920. }
  2921. static uint16_t language_code(const char *str)
  2922. {
  2923. return (((str[0] - 0x60) & 0x1F) << 10) +
  2924. (((str[1] - 0x60) & 0x1F) << 5) +
  2925. (( str[2] - 0x60) & 0x1F);
  2926. }
  2927. static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
  2928. const char *tag, const char *str)
  2929. {
  2930. int64_t pos = avio_tell(pb);
  2931. AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
  2932. if (!t || !utf8len(t->value))
  2933. return 0;
  2934. avio_wb32(pb, 0); /* size */
  2935. ffio_wfourcc(pb, tag); /* type */
  2936. avio_wb32(pb, 0); /* version + flags */
  2937. if (!strcmp(tag, "yrrc"))
  2938. avio_wb16(pb, atoi(t->value));
  2939. else {
  2940. avio_wb16(pb, language_code("eng")); /* language */
  2941. avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
  2942. if (!strcmp(tag, "albm") &&
  2943. (t = av_dict_get(s->metadata, "track", NULL, 0)))
  2944. avio_w8(pb, atoi(t->value));
  2945. }
  2946. return update_size(pb, pos);
  2947. }
  2948. static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
  2949. {
  2950. int64_t pos = avio_tell(pb);
  2951. int i, nb_chapters = FFMIN(s->nb_chapters, 255);
  2952. avio_wb32(pb, 0); // size
  2953. ffio_wfourcc(pb, "chpl");
  2954. avio_wb32(pb, 0x01000000); // version + flags
  2955. avio_wb32(pb, 0); // unknown
  2956. avio_w8(pb, nb_chapters);
  2957. for (i = 0; i < nb_chapters; i++) {
  2958. AVChapter *c = s->chapters[i];
  2959. AVDictionaryEntry *t;
  2960. avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
  2961. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  2962. int len = FFMIN(strlen(t->value), 255);
  2963. avio_w8(pb, len);
  2964. avio_write(pb, t->value, len);
  2965. } else
  2966. avio_w8(pb, 0);
  2967. }
  2968. return update_size(pb, pos);
  2969. }
  2970. static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2971. AVFormatContext *s)
  2972. {
  2973. AVIOContext *pb_buf;
  2974. int ret, size;
  2975. uint8_t *buf;
  2976. ret = avio_open_dyn_buf(&pb_buf);
  2977. if (ret < 0)
  2978. return ret;
  2979. if (mov->mode & MODE_3GP) {
  2980. mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
  2981. mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
  2982. mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
  2983. mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
  2984. mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
  2985. mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
  2986. mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
  2987. mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
  2988. mov_write_loci_tag(s, pb_buf);
  2989. } else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
  2990. mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
  2991. mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
  2992. mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
  2993. mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
  2994. mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
  2995. mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
  2996. // currently ignored by mov.c
  2997. mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
  2998. // add support for libquicktime, this atom is also actually read by mov.c
  2999. mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
  3000. mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
  3001. mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
  3002. mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
  3003. mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
  3004. mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
  3005. mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
  3006. } else {
  3007. /* iTunes meta data */
  3008. mov_write_meta_tag(pb_buf, mov, s);
  3009. mov_write_loci_tag(s, pb_buf);
  3010. }
  3011. if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
  3012. mov_write_chpl_tag(pb_buf, s);
  3013. if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
  3014. avio_wb32(pb, size + 8);
  3015. ffio_wfourcc(pb, "udta");
  3016. avio_write(pb, buf, size);
  3017. }
  3018. av_free(buf);
  3019. return 0;
  3020. }
  3021. static void mov_write_psp_udta_tag(AVIOContext *pb,
  3022. const char *str, const char *lang, int type)
  3023. {
  3024. int len = utf8len(str) + 1;
  3025. if (len <= 0)
  3026. return;
  3027. avio_wb16(pb, len * 2 + 10); /* size */
  3028. avio_wb32(pb, type); /* type */
  3029. avio_wb16(pb, language_code(lang)); /* language */
  3030. avio_wb16(pb, 0x01); /* ? */
  3031. ascii_to_wc(pb, str);
  3032. }
  3033. static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
  3034. {
  3035. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  3036. int64_t pos, pos2;
  3037. if (title) {
  3038. pos = avio_tell(pb);
  3039. avio_wb32(pb, 0); /* size placeholder*/
  3040. ffio_wfourcc(pb, "uuid");
  3041. ffio_wfourcc(pb, "USMT");
  3042. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  3043. avio_wb32(pb, 0xbb88695c);
  3044. avio_wb32(pb, 0xfac9c740);
  3045. pos2 = avio_tell(pb);
  3046. avio_wb32(pb, 0); /* size placeholder*/
  3047. ffio_wfourcc(pb, "MTDT");
  3048. avio_wb16(pb, 4);
  3049. // ?
  3050. avio_wb16(pb, 0x0C); /* size */
  3051. avio_wb32(pb, 0x0B); /* type */
  3052. avio_wb16(pb, language_code("und")); /* language */
  3053. avio_wb16(pb, 0x0); /* ? */
  3054. avio_wb16(pb, 0x021C); /* data */
  3055. if (!(s->flags & AVFMT_FLAG_BITEXACT))
  3056. mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
  3057. mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
  3058. mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
  3059. update_size(pb, pos2);
  3060. return update_size(pb, pos);
  3061. }
  3062. return 0;
  3063. }
  3064. static void build_chunks(MOVTrack *trk)
  3065. {
  3066. int i;
  3067. MOVIentry *chunk = &trk->cluster[0];
  3068. uint64_t chunkSize = chunk->size;
  3069. chunk->chunkNum = 1;
  3070. if (trk->chunkCount)
  3071. return;
  3072. trk->chunkCount = 1;
  3073. for (i = 1; i<trk->entry; i++){
  3074. if (chunk->pos + chunkSize == trk->cluster[i].pos &&
  3075. chunkSize + trk->cluster[i].size < (1<<20)){
  3076. chunkSize += trk->cluster[i].size;
  3077. chunk->samples_in_chunk += trk->cluster[i].entries;
  3078. } else {
  3079. trk->cluster[i].chunkNum = chunk->chunkNum+1;
  3080. chunk=&trk->cluster[i];
  3081. chunkSize = chunk->size;
  3082. trk->chunkCount++;
  3083. }
  3084. }
  3085. }
  3086. /**
  3087. * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
  3088. * the stream ids are used as track ids.
  3089. *
  3090. * This assumes mov->tracks and s->streams are in the same order and
  3091. * there are no gaps in either of them (so mov->tracks[n] refers to
  3092. * s->streams[n]).
  3093. *
  3094. * As an exception, there can be more entries in
  3095. * s->streams than in mov->tracks, in which case new track ids are
  3096. * generated (starting after the largest found stream id).
  3097. */
  3098. static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
  3099. {
  3100. int i;
  3101. if (mov->track_ids_ok)
  3102. return 0;
  3103. if (mov->use_stream_ids_as_track_ids) {
  3104. int next_generated_track_id = 0;
  3105. for (i = 0; i < s->nb_streams; i++) {
  3106. if (s->streams[i]->id > next_generated_track_id)
  3107. next_generated_track_id = s->streams[i]->id;
  3108. }
  3109. for (i = 0; i < mov->nb_streams; i++) {
  3110. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3111. continue;
  3112. mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
  3113. }
  3114. } else {
  3115. for (i = 0; i < mov->nb_streams; i++) {
  3116. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3117. continue;
  3118. mov->tracks[i].track_id = i + 1;
  3119. }
  3120. }
  3121. mov->track_ids_ok = 1;
  3122. return 0;
  3123. }
  3124. static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
  3125. AVFormatContext *s)
  3126. {
  3127. int i;
  3128. int64_t pos = avio_tell(pb);
  3129. avio_wb32(pb, 0); /* size placeholder*/
  3130. ffio_wfourcc(pb, "moov");
  3131. mov_setup_track_ids(mov, s);
  3132. for (i = 0; i < mov->nb_streams; i++) {
  3133. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3134. continue;
  3135. mov->tracks[i].time = mov->time;
  3136. if (mov->tracks[i].entry)
  3137. build_chunks(&mov->tracks[i]);
  3138. }
  3139. if (mov->chapter_track)
  3140. for (i = 0; i < s->nb_streams; i++) {
  3141. mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
  3142. mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
  3143. }
  3144. for (i = 0; i < mov->nb_streams; i++) {
  3145. MOVTrack *track = &mov->tracks[i];
  3146. if (track->tag == MKTAG('r','t','p',' ')) {
  3147. track->tref_tag = MKTAG('h','i','n','t');
  3148. track->tref_id = mov->tracks[track->src_track].track_id;
  3149. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  3150. int * fallback, size;
  3151. fallback = (int*)av_stream_get_side_data(track->st,
  3152. AV_PKT_DATA_FALLBACK_TRACK,
  3153. &size);
  3154. if (fallback != NULL && size == sizeof(int)) {
  3155. if (*fallback >= 0 && *fallback < mov->nb_streams) {
  3156. track->tref_tag = MKTAG('f','a','l','l');
  3157. track->tref_id = mov->tracks[*fallback].track_id;
  3158. }
  3159. }
  3160. }
  3161. }
  3162. for (i = 0; i < mov->nb_streams; i++) {
  3163. if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
  3164. int src_trk = mov->tracks[i].src_track;
  3165. mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
  3166. mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
  3167. //src_trk may have a different timescale than the tmcd track
  3168. mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
  3169. mov->tracks[i].timescale,
  3170. mov->tracks[src_trk].timescale);
  3171. }
  3172. }
  3173. mov_write_mvhd_tag(pb, mov);
  3174. if (mov->mode != MODE_MOV && !mov->iods_skip)
  3175. mov_write_iods_tag(pb, mov);
  3176. for (i = 0; i < mov->nb_streams; i++) {
  3177. if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
  3178. int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
  3179. if (ret < 0)
  3180. return ret;
  3181. }
  3182. }
  3183. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  3184. mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
  3185. if (mov->mode == MODE_PSP)
  3186. mov_write_uuidusmt_tag(pb, s);
  3187. else
  3188. mov_write_udta_tag(pb, mov, s);
  3189. return update_size(pb, pos);
  3190. }
  3191. static void param_write_int(AVIOContext *pb, const char *name, int value)
  3192. {
  3193. avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
  3194. }
  3195. static void param_write_string(AVIOContext *pb, const char *name, const char *value)
  3196. {
  3197. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
  3198. }
  3199. static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
  3200. {
  3201. char buf[150];
  3202. len = FFMIN(sizeof(buf) / 2 - 1, len);
  3203. ff_data_to_hex(buf, value, len, 0);
  3204. buf[2 * len] = '\0';
  3205. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
  3206. }
  3207. static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
  3208. {
  3209. int64_t pos = avio_tell(pb);
  3210. int i;
  3211. int64_t manifest_bit_rate = 0;
  3212. AVCPBProperties *props = NULL;
  3213. static const uint8_t uuid[] = {
  3214. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  3215. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  3216. };
  3217. avio_wb32(pb, 0);
  3218. ffio_wfourcc(pb, "uuid");
  3219. avio_write(pb, uuid, sizeof(uuid));
  3220. avio_wb32(pb, 0);
  3221. avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  3222. avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
  3223. avio_printf(pb, "<head>\n");
  3224. if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
  3225. avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
  3226. LIBAVFORMAT_IDENT);
  3227. avio_printf(pb, "</head>\n");
  3228. avio_printf(pb, "<body>\n");
  3229. avio_printf(pb, "<switch>\n");
  3230. mov_setup_track_ids(mov, s);
  3231. for (i = 0; i < mov->nb_streams; i++) {
  3232. MOVTrack *track = &mov->tracks[i];
  3233. const char *type;
  3234. int track_id = track->track_id;
  3235. AVStream *st = track->st;
  3236. AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
  3237. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  3238. type = "video";
  3239. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  3240. type = "audio";
  3241. } else {
  3242. continue;
  3243. }
  3244. props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
  3245. if (track->par->bit_rate) {
  3246. manifest_bit_rate = track->par->bit_rate;
  3247. } else if (props) {
  3248. manifest_bit_rate = props->max_bitrate;
  3249. }
  3250. avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
  3251. manifest_bit_rate);
  3252. param_write_int(pb, "systemBitrate", manifest_bit_rate);
  3253. param_write_int(pb, "trackID", track_id);
  3254. param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
  3255. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  3256. if (track->par->codec_id == AV_CODEC_ID_H264) {
  3257. uint8_t *ptr;
  3258. int size = track->par->extradata_size;
  3259. if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
  3260. &size)) {
  3261. param_write_hex(pb, "CodecPrivateData",
  3262. ptr ? ptr : track->par->extradata,
  3263. size);
  3264. av_free(ptr);
  3265. }
  3266. param_write_string(pb, "FourCC", "H264");
  3267. } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
  3268. param_write_string(pb, "FourCC", "WVC1");
  3269. param_write_hex(pb, "CodecPrivateData", track->par->extradata,
  3270. track->par->extradata_size);
  3271. }
  3272. param_write_int(pb, "MaxWidth", track->par->width);
  3273. param_write_int(pb, "MaxHeight", track->par->height);
  3274. param_write_int(pb, "DisplayWidth", track->par->width);
  3275. param_write_int(pb, "DisplayHeight", track->par->height);
  3276. } else {
  3277. if (track->par->codec_id == AV_CODEC_ID_AAC) {
  3278. switch (track->par->profile)
  3279. {
  3280. case FF_PROFILE_AAC_HE_V2:
  3281. param_write_string(pb, "FourCC", "AACP");
  3282. break;
  3283. case FF_PROFILE_AAC_HE:
  3284. param_write_string(pb, "FourCC", "AACH");
  3285. break;
  3286. default:
  3287. param_write_string(pb, "FourCC", "AACL");
  3288. }
  3289. } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
  3290. param_write_string(pb, "FourCC", "WMAP");
  3291. }
  3292. param_write_hex(pb, "CodecPrivateData", track->par->extradata,
  3293. track->par->extradata_size);
  3294. param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
  3295. track->par->codec_id));
  3296. param_write_int(pb, "Channels", track->par->channels);
  3297. param_write_int(pb, "SamplingRate", track->par->sample_rate);
  3298. param_write_int(pb, "BitsPerSample", 16);
  3299. param_write_int(pb, "PacketSize", track->par->block_align ?
  3300. track->par->block_align : 4);
  3301. }
  3302. avio_printf(pb, "</%s>\n", type);
  3303. }
  3304. avio_printf(pb, "</switch>\n");
  3305. avio_printf(pb, "</body>\n");
  3306. avio_printf(pb, "</smil>\n");
  3307. return update_size(pb, pos);
  3308. }
  3309. static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  3310. {
  3311. avio_wb32(pb, 16);
  3312. ffio_wfourcc(pb, "mfhd");
  3313. avio_wb32(pb, 0);
  3314. avio_wb32(pb, mov->fragments);
  3315. return 0;
  3316. }
  3317. static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
  3318. {
  3319. return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
  3320. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
  3321. }
  3322. static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  3323. MOVTrack *track, int64_t moof_offset)
  3324. {
  3325. int64_t pos = avio_tell(pb);
  3326. uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  3327. MOV_TFHD_BASE_DATA_OFFSET;
  3328. if (!track->entry) {
  3329. flags |= MOV_TFHD_DURATION_IS_EMPTY;
  3330. } else {
  3331. flags |= MOV_TFHD_DEFAULT_FLAGS;
  3332. }
  3333. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
  3334. flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
  3335. if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
  3336. flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
  3337. flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
  3338. }
  3339. /* Don't set a default sample size, the silverlight player refuses
  3340. * to play files with that set. Don't set a default sample duration,
  3341. * WMP freaks out if it is set. Don't set a base data offset, PIFF
  3342. * file format says it MUST NOT be set. */
  3343. if (track->mode == MODE_ISM)
  3344. flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  3345. MOV_TFHD_BASE_DATA_OFFSET);
  3346. avio_wb32(pb, 0); /* size placeholder */
  3347. ffio_wfourcc(pb, "tfhd");
  3348. avio_w8(pb, 0); /* version */
  3349. avio_wb24(pb, flags);
  3350. avio_wb32(pb, track->track_id); /* track-id */
  3351. if (flags & MOV_TFHD_BASE_DATA_OFFSET)
  3352. avio_wb64(pb, moof_offset);
  3353. if (flags & MOV_TFHD_DEFAULT_DURATION) {
  3354. track->default_duration = get_cluster_duration(track, 0);
  3355. avio_wb32(pb, track->default_duration);
  3356. }
  3357. if (flags & MOV_TFHD_DEFAULT_SIZE) {
  3358. track->default_size = track->entry ? track->cluster[0].size : 1;
  3359. avio_wb32(pb, track->default_size);
  3360. } else
  3361. track->default_size = -1;
  3362. if (flags & MOV_TFHD_DEFAULT_FLAGS) {
  3363. /* Set the default flags based on the second sample, if available.
  3364. * If the first sample is different, that can be signaled via a separate field. */
  3365. if (track->entry > 1)
  3366. track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
  3367. else
  3368. track->default_sample_flags =
  3369. track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
  3370. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
  3371. MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
  3372. avio_wb32(pb, track->default_sample_flags);
  3373. }
  3374. return update_size(pb, pos);
  3375. }
  3376. static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
  3377. MOVTrack *track, int moof_size,
  3378. int first, int end)
  3379. {
  3380. int64_t pos = avio_tell(pb);
  3381. uint32_t flags = MOV_TRUN_DATA_OFFSET;
  3382. int i;
  3383. for (i = first; i < end; i++) {
  3384. if (get_cluster_duration(track, i) != track->default_duration)
  3385. flags |= MOV_TRUN_SAMPLE_DURATION;
  3386. if (track->cluster[i].size != track->default_size)
  3387. flags |= MOV_TRUN_SAMPLE_SIZE;
  3388. if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
  3389. flags |= MOV_TRUN_SAMPLE_FLAGS;
  3390. }
  3391. if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
  3392. get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
  3393. flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
  3394. if (track->flags & MOV_TRACK_CTTS)
  3395. flags |= MOV_TRUN_SAMPLE_CTS;
  3396. avio_wb32(pb, 0); /* size placeholder */
  3397. ffio_wfourcc(pb, "trun");
  3398. avio_w8(pb, 0); /* version */
  3399. avio_wb24(pb, flags);
  3400. avio_wb32(pb, end - first); /* sample count */
  3401. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
  3402. !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
  3403. !mov->first_trun)
  3404. avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
  3405. else
  3406. avio_wb32(pb, moof_size + 8 + track->data_offset +
  3407. track->cluster[first].pos); /* data offset */
  3408. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
  3409. avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
  3410. for (i = first; i < end; i++) {
  3411. if (flags & MOV_TRUN_SAMPLE_DURATION)
  3412. avio_wb32(pb, get_cluster_duration(track, i));
  3413. if (flags & MOV_TRUN_SAMPLE_SIZE)
  3414. avio_wb32(pb, track->cluster[i].size);
  3415. if (flags & MOV_TRUN_SAMPLE_FLAGS)
  3416. avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
  3417. if (flags & MOV_TRUN_SAMPLE_CTS)
  3418. avio_wb32(pb, track->cluster[i].cts);
  3419. }
  3420. mov->first_trun = 0;
  3421. return update_size(pb, pos);
  3422. }
  3423. static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
  3424. {
  3425. int64_t pos = avio_tell(pb);
  3426. static const uint8_t uuid[] = {
  3427. 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
  3428. 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
  3429. };
  3430. avio_wb32(pb, 0); /* size placeholder */
  3431. ffio_wfourcc(pb, "uuid");
  3432. avio_write(pb, uuid, sizeof(uuid));
  3433. avio_w8(pb, 1);
  3434. avio_wb24(pb, 0);
  3435. avio_wb64(pb, track->start_dts + track->frag_start +
  3436. track->cluster[0].cts);
  3437. avio_wb64(pb, track->end_pts -
  3438. (track->cluster[0].dts + track->cluster[0].cts));
  3439. return update_size(pb, pos);
  3440. }
  3441. static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
  3442. MOVTrack *track, int entry)
  3443. {
  3444. int n = track->nb_frag_info - 1 - entry, i;
  3445. int size = 8 + 16 + 4 + 1 + 16*n;
  3446. static const uint8_t uuid[] = {
  3447. 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
  3448. 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
  3449. };
  3450. if (entry < 0)
  3451. return 0;
  3452. avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
  3453. avio_wb32(pb, size);
  3454. ffio_wfourcc(pb, "uuid");
  3455. avio_write(pb, uuid, sizeof(uuid));
  3456. avio_w8(pb, 1);
  3457. avio_wb24(pb, 0);
  3458. avio_w8(pb, n);
  3459. for (i = 0; i < n; i++) {
  3460. int index = entry + 1 + i;
  3461. avio_wb64(pb, track->frag_info[index].time);
  3462. avio_wb64(pb, track->frag_info[index].duration);
  3463. }
  3464. if (n < mov->ism_lookahead) {
  3465. int free_size = 16 * (mov->ism_lookahead - n);
  3466. avio_wb32(pb, free_size);
  3467. ffio_wfourcc(pb, "free");
  3468. ffio_fill(pb, 0, free_size - 8);
  3469. }
  3470. return 0;
  3471. }
  3472. static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
  3473. MOVTrack *track)
  3474. {
  3475. int64_t pos = avio_tell(pb);
  3476. int i;
  3477. for (i = 0; i < mov->ism_lookahead; i++) {
  3478. /* Update the tfrf tag for the last ism_lookahead fragments,
  3479. * nb_frag_info - 1 is the next fragment to be written. */
  3480. mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
  3481. }
  3482. avio_seek(pb, pos, SEEK_SET);
  3483. return 0;
  3484. }
  3485. static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
  3486. int size)
  3487. {
  3488. int i;
  3489. for (i = 0; i < mov->nb_streams; i++) {
  3490. MOVTrack *track = &mov->tracks[i];
  3491. MOVFragmentInfo *info;
  3492. if ((tracks >= 0 && i != tracks) || !track->entry)
  3493. continue;
  3494. track->nb_frag_info++;
  3495. if (track->nb_frag_info >= track->frag_info_capacity) {
  3496. unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
  3497. if (av_reallocp_array(&track->frag_info,
  3498. new_capacity,
  3499. sizeof(*track->frag_info)))
  3500. return AVERROR(ENOMEM);
  3501. track->frag_info_capacity = new_capacity;
  3502. }
  3503. info = &track->frag_info[track->nb_frag_info - 1];
  3504. info->offset = avio_tell(pb);
  3505. info->size = size;
  3506. // Try to recreate the original pts for the first packet
  3507. // from the fields we have stored
  3508. info->time = track->start_dts + track->frag_start +
  3509. track->cluster[0].cts;
  3510. info->duration = track->end_pts -
  3511. (track->cluster[0].dts + track->cluster[0].cts);
  3512. // If the pts is less than zero, we will have trimmed
  3513. // away parts of the media track using an edit list,
  3514. // and the corresponding start presentation time is zero.
  3515. if (info->time < 0) {
  3516. info->duration += info->time;
  3517. info->time = 0;
  3518. }
  3519. info->tfrf_offset = 0;
  3520. mov_write_tfrf_tags(pb, mov, track);
  3521. }
  3522. return 0;
  3523. }
  3524. static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
  3525. {
  3526. int64_t pos = avio_tell(pb);
  3527. avio_wb32(pb, 0); /* size */
  3528. ffio_wfourcc(pb, "tfdt");
  3529. avio_w8(pb, 1); /* version */
  3530. avio_wb24(pb, 0);
  3531. avio_wb64(pb, track->frag_start);
  3532. return update_size(pb, pos);
  3533. }
  3534. static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
  3535. MOVTrack *track, int64_t moof_offset,
  3536. int moof_size)
  3537. {
  3538. int64_t pos = avio_tell(pb);
  3539. int i, start = 0;
  3540. avio_wb32(pb, 0); /* size placeholder */
  3541. ffio_wfourcc(pb, "traf");
  3542. mov_write_tfhd_tag(pb, mov, track, moof_offset);
  3543. if (mov->mode != MODE_ISM)
  3544. mov_write_tfdt_tag(pb, track);
  3545. for (i = 1; i < track->entry; i++) {
  3546. if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
  3547. mov_write_trun_tag(pb, mov, track, moof_size, start, i);
  3548. start = i;
  3549. }
  3550. }
  3551. mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
  3552. if (mov->mode == MODE_ISM) {
  3553. mov_write_tfxd_tag(pb, track);
  3554. if (mov->ism_lookahead) {
  3555. int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
  3556. if (track->nb_frag_info > 0) {
  3557. MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
  3558. if (!info->tfrf_offset)
  3559. info->tfrf_offset = avio_tell(pb);
  3560. }
  3561. avio_wb32(pb, 8 + size);
  3562. ffio_wfourcc(pb, "free");
  3563. for (i = 0; i < size; i++)
  3564. avio_w8(pb, 0);
  3565. }
  3566. }
  3567. return update_size(pb, pos);
  3568. }
  3569. static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
  3570. int tracks, int moof_size)
  3571. {
  3572. int64_t pos = avio_tell(pb);
  3573. int i;
  3574. avio_wb32(pb, 0); /* size placeholder */
  3575. ffio_wfourcc(pb, "moof");
  3576. mov->first_trun = 1;
  3577. mov_write_mfhd_tag(pb, mov);
  3578. for (i = 0; i < mov->nb_streams; i++) {
  3579. MOVTrack *track = &mov->tracks[i];
  3580. if (tracks >= 0 && i != tracks)
  3581. continue;
  3582. if (!track->entry)
  3583. continue;
  3584. mov_write_traf_tag(pb, mov, track, pos, moof_size);
  3585. }
  3586. return update_size(pb, pos);
  3587. }
  3588. static int mov_write_sidx_tag(AVIOContext *pb,
  3589. MOVTrack *track, int ref_size, int total_sidx_size)
  3590. {
  3591. int64_t pos = avio_tell(pb), offset_pos, end_pos;
  3592. int64_t presentation_time, duration, offset;
  3593. int starts_with_SAP, i, entries;
  3594. if (track->entry) {
  3595. entries = 1;
  3596. presentation_time = track->start_dts + track->frag_start +
  3597. track->cluster[0].cts;
  3598. duration = track->end_pts -
  3599. (track->cluster[0].dts + track->cluster[0].cts);
  3600. starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
  3601. // pts<0 should be cut away using edts
  3602. if (presentation_time < 0) {
  3603. duration += presentation_time;
  3604. presentation_time = 0;
  3605. }
  3606. } else {
  3607. entries = track->nb_frag_info;
  3608. if (entries <= 0)
  3609. return 0;
  3610. presentation_time = track->frag_info[0].time;
  3611. }
  3612. avio_wb32(pb, 0); /* size */
  3613. ffio_wfourcc(pb, "sidx");
  3614. avio_w8(pb, 1); /* version */
  3615. avio_wb24(pb, 0);
  3616. avio_wb32(pb, track->track_id); /* reference_ID */
  3617. avio_wb32(pb, track->timescale); /* timescale */
  3618. avio_wb64(pb, presentation_time); /* earliest_presentation_time */
  3619. offset_pos = avio_tell(pb);
  3620. avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
  3621. avio_wb16(pb, 0); /* reserved */
  3622. avio_wb16(pb, entries); /* reference_count */
  3623. for (i = 0; i < entries; i++) {
  3624. if (!track->entry) {
  3625. if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
  3626. av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
  3627. }
  3628. duration = track->frag_info[i].duration;
  3629. ref_size = track->frag_info[i].size;
  3630. starts_with_SAP = 1;
  3631. }
  3632. avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
  3633. avio_wb32(pb, duration); /* subsegment_duration */
  3634. avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
  3635. }
  3636. end_pos = avio_tell(pb);
  3637. offset = pos + total_sidx_size - end_pos;
  3638. avio_seek(pb, offset_pos, SEEK_SET);
  3639. avio_wb64(pb, offset);
  3640. avio_seek(pb, end_pos, SEEK_SET);
  3641. return update_size(pb, pos);
  3642. }
  3643. static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
  3644. int tracks, int ref_size)
  3645. {
  3646. int i, round, ret;
  3647. AVIOContext *avio_buf;
  3648. int total_size = 0;
  3649. for (round = 0; round < 2; round++) {
  3650. // First run one round to calculate the total size of all
  3651. // sidx atoms.
  3652. // This would be much simpler if we'd only write one sidx
  3653. // atom, for the first track in the moof.
  3654. if (round == 0) {
  3655. if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
  3656. return ret;
  3657. } else {
  3658. avio_buf = pb;
  3659. }
  3660. for (i = 0; i < mov->nb_streams; i++) {
  3661. MOVTrack *track = &mov->tracks[i];
  3662. if (tracks >= 0 && i != tracks)
  3663. continue;
  3664. // When writing a sidx for the full file, entry is 0, but
  3665. // we want to include all tracks. ref_size is 0 in this case,
  3666. // since we read it from frag_info instead.
  3667. if (!track->entry && ref_size > 0)
  3668. continue;
  3669. total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
  3670. total_size);
  3671. }
  3672. if (round == 0)
  3673. total_size = ffio_close_null_buf(avio_buf);
  3674. }
  3675. return 0;
  3676. }
  3677. static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
  3678. int64_t mdat_size)
  3679. {
  3680. AVIOContext *avio_buf;
  3681. int ret, moof_size;
  3682. if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
  3683. return ret;
  3684. mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
  3685. moof_size = ffio_close_null_buf(avio_buf);
  3686. if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
  3687. mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
  3688. if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
  3689. return ret;
  3690. return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
  3691. }
  3692. static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
  3693. {
  3694. int64_t pos = avio_tell(pb);
  3695. int i;
  3696. avio_wb32(pb, 0); /* size placeholder */
  3697. ffio_wfourcc(pb, "tfra");
  3698. avio_w8(pb, 1); /* version */
  3699. avio_wb24(pb, 0);
  3700. avio_wb32(pb, track->track_id);
  3701. avio_wb32(pb, 0); /* length of traf/trun/sample num */
  3702. avio_wb32(pb, track->nb_frag_info);
  3703. for (i = 0; i < track->nb_frag_info; i++) {
  3704. avio_wb64(pb, track->frag_info[i].time);
  3705. avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
  3706. avio_w8(pb, 1); /* traf number */
  3707. avio_w8(pb, 1); /* trun number */
  3708. avio_w8(pb, 1); /* sample number */
  3709. }
  3710. return update_size(pb, pos);
  3711. }
  3712. static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
  3713. {
  3714. int64_t pos = avio_tell(pb);
  3715. int i;
  3716. avio_wb32(pb, 0); /* size placeholder */
  3717. ffio_wfourcc(pb, "mfra");
  3718. /* An empty mfra atom is enough to indicate to the publishing point that
  3719. * the stream has ended. */
  3720. if (mov->flags & FF_MOV_FLAG_ISML)
  3721. return update_size(pb, pos);
  3722. for (i = 0; i < mov->nb_streams; i++) {
  3723. MOVTrack *track = &mov->tracks[i];
  3724. if (track->nb_frag_info)
  3725. mov_write_tfra_tag(pb, track);
  3726. }
  3727. avio_wb32(pb, 16);
  3728. ffio_wfourcc(pb, "mfro");
  3729. avio_wb32(pb, 0); /* version + flags */
  3730. avio_wb32(pb, avio_tell(pb) + 4 - pos);
  3731. return update_size(pb, pos);
  3732. }
  3733. static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
  3734. {
  3735. avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
  3736. ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
  3737. mov->mdat_pos = avio_tell(pb);
  3738. avio_wb32(pb, 0); /* size placeholder*/
  3739. ffio_wfourcc(pb, "mdat");
  3740. return 0;
  3741. }
  3742. /* TODO: This needs to be more general */
  3743. static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
  3744. {
  3745. MOVMuxContext *mov = s->priv_data;
  3746. int64_t pos = avio_tell(pb);
  3747. int has_h264 = 0, has_video = 0;
  3748. int minor = 0x200;
  3749. int i;
  3750. for (i = 0; i < s->nb_streams; i++) {
  3751. AVStream *st = s->streams[i];
  3752. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  3753. has_video = 1;
  3754. if (st->codecpar->codec_id == AV_CODEC_ID_H264)
  3755. has_h264 = 1;
  3756. }
  3757. avio_wb32(pb, 0); /* size */
  3758. ffio_wfourcc(pb, "ftyp");
  3759. if (mov->major_brand && strlen(mov->major_brand) >= 4)
  3760. ffio_wfourcc(pb, mov->major_brand);
  3761. else if (mov->mode == MODE_3GP) {
  3762. ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
  3763. minor = has_h264 ? 0x100 : 0x200;
  3764. } else if (mov->mode & MODE_3G2) {
  3765. ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
  3766. minor = has_h264 ? 0x20000 : 0x10000;
  3767. } else if (mov->mode == MODE_PSP)
  3768. ffio_wfourcc(pb, "MSNV");
  3769. else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
  3770. ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
  3771. else if (mov->mode == MODE_MP4)
  3772. ffio_wfourcc(pb, "isom");
  3773. else if (mov->mode == MODE_IPOD)
  3774. ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
  3775. else if (mov->mode == MODE_ISM)
  3776. ffio_wfourcc(pb, "isml");
  3777. else if (mov->mode == MODE_F4V)
  3778. ffio_wfourcc(pb, "f4v ");
  3779. else
  3780. ffio_wfourcc(pb, "qt ");
  3781. avio_wb32(pb, minor);
  3782. if (mov->mode == MODE_MOV)
  3783. ffio_wfourcc(pb, "qt ");
  3784. else if (mov->mode == MODE_ISM) {
  3785. ffio_wfourcc(pb, "piff");
  3786. } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
  3787. ffio_wfourcc(pb, "isom");
  3788. ffio_wfourcc(pb, "iso2");
  3789. if (has_h264)
  3790. ffio_wfourcc(pb, "avc1");
  3791. }
  3792. // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
  3793. // brand. This is compatible with users that don't understand tfdt.
  3794. if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
  3795. ffio_wfourcc(pb, "iso6");
  3796. if (mov->mode == MODE_3GP)
  3797. ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
  3798. else if (mov->mode & MODE_3G2)
  3799. ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
  3800. else if (mov->mode == MODE_PSP)
  3801. ffio_wfourcc(pb, "MSNV");
  3802. else if (mov->mode == MODE_MP4)
  3803. ffio_wfourcc(pb, "mp41");
  3804. if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  3805. ffio_wfourcc(pb, "dash");
  3806. return update_size(pb, pos);
  3807. }
  3808. static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
  3809. {
  3810. AVStream *video_st = s->streams[0];
  3811. AVCodecParameters *video_par = s->streams[0]->codecpar;
  3812. AVCodecParameters *audio_par = s->streams[1]->codecpar;
  3813. int audio_rate = audio_par->sample_rate;
  3814. int64_t frame_rate = (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den;
  3815. int audio_kbitrate = audio_par->bit_rate / 1000;
  3816. int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
  3817. if (frame_rate < 0 || frame_rate > INT32_MAX) {
  3818. av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
  3819. return AVERROR(EINVAL);
  3820. }
  3821. avio_wb32(pb, 0x94); /* size */
  3822. ffio_wfourcc(pb, "uuid");
  3823. ffio_wfourcc(pb, "PROF");
  3824. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  3825. avio_wb32(pb, 0xbb88695c);
  3826. avio_wb32(pb, 0xfac9c740);
  3827. avio_wb32(pb, 0x0); /* ? */
  3828. avio_wb32(pb, 0x3); /* 3 sections ? */
  3829. avio_wb32(pb, 0x14); /* size */
  3830. ffio_wfourcc(pb, "FPRF");
  3831. avio_wb32(pb, 0x0); /* ? */
  3832. avio_wb32(pb, 0x0); /* ? */
  3833. avio_wb32(pb, 0x0); /* ? */
  3834. avio_wb32(pb, 0x2c); /* size */
  3835. ffio_wfourcc(pb, "APRF"); /* audio */
  3836. avio_wb32(pb, 0x0);
  3837. avio_wb32(pb, 0x2); /* TrackID */
  3838. ffio_wfourcc(pb, "mp4a");
  3839. avio_wb32(pb, 0x20f);
  3840. avio_wb32(pb, 0x0);
  3841. avio_wb32(pb, audio_kbitrate);
  3842. avio_wb32(pb, audio_kbitrate);
  3843. avio_wb32(pb, audio_rate);
  3844. avio_wb32(pb, audio_par->channels);
  3845. avio_wb32(pb, 0x34); /* size */
  3846. ffio_wfourcc(pb, "VPRF"); /* video */
  3847. avio_wb32(pb, 0x0);
  3848. avio_wb32(pb, 0x1); /* TrackID */
  3849. if (video_par->codec_id == AV_CODEC_ID_H264) {
  3850. ffio_wfourcc(pb, "avc1");
  3851. avio_wb16(pb, 0x014D);
  3852. avio_wb16(pb, 0x0015);
  3853. } else {
  3854. ffio_wfourcc(pb, "mp4v");
  3855. avio_wb16(pb, 0x0000);
  3856. avio_wb16(pb, 0x0103);
  3857. }
  3858. avio_wb32(pb, 0x0);
  3859. avio_wb32(pb, video_kbitrate);
  3860. avio_wb32(pb, video_kbitrate);
  3861. avio_wb32(pb, frame_rate);
  3862. avio_wb32(pb, frame_rate);
  3863. avio_wb16(pb, video_par->width);
  3864. avio_wb16(pb, video_par->height);
  3865. avio_wb32(pb, 0x010001); /* ? */
  3866. return 0;
  3867. }
  3868. static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
  3869. {
  3870. MOVMuxContext *mov = s->priv_data;
  3871. int i;
  3872. mov_write_ftyp_tag(pb,s);
  3873. if (mov->mode == MODE_PSP) {
  3874. int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
  3875. for (i = 0; i < s->nb_streams; i++) {
  3876. AVStream *st = s->streams[i];
  3877. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  3878. video_streams_nb++;
  3879. else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  3880. audio_streams_nb++;
  3881. else
  3882. other_streams_nb++;
  3883. }
  3884. if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
  3885. av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
  3886. return AVERROR(EINVAL);
  3887. }
  3888. return mov_write_uuidprof_tag(pb, s);
  3889. }
  3890. return 0;
  3891. }
  3892. static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
  3893. {
  3894. uint32_t c = -1;
  3895. int i, closed_gop = 0;
  3896. for (i = 0; i < pkt->size - 4; i++) {
  3897. c = (c << 8) + pkt->data[i];
  3898. if (c == 0x1b8) { // gop
  3899. closed_gop = pkt->data[i + 4] >> 6 & 0x01;
  3900. } else if (c == 0x100) { // pic
  3901. int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
  3902. if (!temp_ref || closed_gop) // I picture is not reordered
  3903. *flags = MOV_SYNC_SAMPLE;
  3904. else
  3905. *flags = MOV_PARTIAL_SYNC_SAMPLE;
  3906. break;
  3907. }
  3908. }
  3909. return 0;
  3910. }
  3911. static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
  3912. {
  3913. const uint8_t *start, *next, *end = pkt->data + pkt->size;
  3914. int seq = 0, entry = 0;
  3915. int key = pkt->flags & AV_PKT_FLAG_KEY;
  3916. start = find_next_marker(pkt->data, end);
  3917. for (next = start; next < end; start = next) {
  3918. next = find_next_marker(start + 4, end);
  3919. switch (AV_RB32(start)) {
  3920. case VC1_CODE_SEQHDR:
  3921. seq = 1;
  3922. break;
  3923. case VC1_CODE_ENTRYPOINT:
  3924. entry = 1;
  3925. break;
  3926. case VC1_CODE_SLICE:
  3927. trk->vc1_info.slices = 1;
  3928. break;
  3929. }
  3930. }
  3931. if (!trk->entry && trk->vc1_info.first_packet_seen)
  3932. trk->vc1_info.first_frag_written = 1;
  3933. if (!trk->entry && !trk->vc1_info.first_frag_written) {
  3934. /* First packet in first fragment */
  3935. trk->vc1_info.first_packet_seq = seq;
  3936. trk->vc1_info.first_packet_entry = entry;
  3937. trk->vc1_info.first_packet_seen = 1;
  3938. } else if ((seq && !trk->vc1_info.packet_seq) ||
  3939. (entry && !trk->vc1_info.packet_entry)) {
  3940. int i;
  3941. for (i = 0; i < trk->entry; i++)
  3942. trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
  3943. trk->has_keyframes = 0;
  3944. if (seq)
  3945. trk->vc1_info.packet_seq = 1;
  3946. if (entry)
  3947. trk->vc1_info.packet_entry = 1;
  3948. if (!trk->vc1_info.first_frag_written) {
  3949. /* First fragment */
  3950. if ((!seq || trk->vc1_info.first_packet_seq) &&
  3951. (!entry || trk->vc1_info.first_packet_entry)) {
  3952. /* First packet had the same headers as this one, readd the
  3953. * sync sample flag. */
  3954. trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
  3955. trk->has_keyframes = 1;
  3956. }
  3957. }
  3958. }
  3959. if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
  3960. key = seq && entry;
  3961. else if (trk->vc1_info.packet_seq)
  3962. key = seq;
  3963. else if (trk->vc1_info.packet_entry)
  3964. key = entry;
  3965. if (key) {
  3966. trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
  3967. trk->has_keyframes++;
  3968. }
  3969. }
  3970. static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
  3971. {
  3972. MOVMuxContext *mov = s->priv_data;
  3973. int ret, buf_size;
  3974. uint8_t *buf;
  3975. int i, offset;
  3976. if (!track->mdat_buf)
  3977. return 0;
  3978. if (!mov->mdat_buf) {
  3979. if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
  3980. return ret;
  3981. }
  3982. buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
  3983. track->mdat_buf = NULL;
  3984. offset = avio_tell(mov->mdat_buf);
  3985. avio_write(mov->mdat_buf, buf, buf_size);
  3986. av_free(buf);
  3987. for (i = track->entries_flushed; i < track->entry; i++)
  3988. track->cluster[i].pos += offset;
  3989. track->entries_flushed = track->entry;
  3990. return 0;
  3991. }
  3992. static int mov_flush_fragment(AVFormatContext *s, int force)
  3993. {
  3994. MOVMuxContext *mov = s->priv_data;
  3995. int i, first_track = -1;
  3996. int64_t mdat_size = 0;
  3997. int ret;
  3998. int has_video = 0, starts_with_key = 0, first_video_track = 1;
  3999. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
  4000. return 0;
  4001. // Try to fill in the duration of the last packet in each stream
  4002. // from queued packets in the interleave queues. If the flushing
  4003. // of fragments was triggered automatically by an AVPacket, we
  4004. // already have reliable info for the end of that track, but other
  4005. // tracks may need to be filled in.
  4006. for (i = 0; i < s->nb_streams; i++) {
  4007. MOVTrack *track = &mov->tracks[i];
  4008. if (!track->end_reliable) {
  4009. int64_t ts_offset;
  4010. const AVPacket *next = ff_interleaved_peek(s, i, &ts_offset);
  4011. if (next) {
  4012. track->track_duration = next->dts - track->start_dts + ts_offset;
  4013. if (next->pts != AV_NOPTS_VALUE)
  4014. track->end_pts = next->pts;
  4015. else
  4016. track->end_pts = next->dts;
  4017. track->end_pts += ts_offset;
  4018. }
  4019. }
  4020. }
  4021. for (i = 0; i < mov->nb_streams; i++) {
  4022. MOVTrack *track = &mov->tracks[i];
  4023. if (track->entry <= 1)
  4024. continue;
  4025. // Sample durations are calculated as the diff of dts values,
  4026. // but for the last sample in a fragment, we don't know the dts
  4027. // of the first sample in the next fragment, so we have to rely
  4028. // on what was set as duration in the AVPacket. Not all callers
  4029. // set this though, so we might want to replace it with an
  4030. // estimate if it currently is zero.
  4031. if (get_cluster_duration(track, track->entry - 1) != 0)
  4032. continue;
  4033. // Use the duration (i.e. dts diff) of the second last sample for
  4034. // the last one. This is a wild guess (and fatal if it turns out
  4035. // to be too long), but probably the best we can do - having a zero
  4036. // duration is bad as well.
  4037. track->track_duration += get_cluster_duration(track, track->entry - 2);
  4038. track->end_pts += get_cluster_duration(track, track->entry - 2);
  4039. if (!mov->missing_duration_warned) {
  4040. av_log(s, AV_LOG_WARNING,
  4041. "Estimating the duration of the last packet in a "
  4042. "fragment, consider setting the duration field in "
  4043. "AVPacket instead.\n");
  4044. mov->missing_duration_warned = 1;
  4045. }
  4046. }
  4047. if (!mov->moov_written) {
  4048. int64_t pos = avio_tell(s->pb);
  4049. uint8_t *buf;
  4050. int buf_size, moov_size;
  4051. for (i = 0; i < mov->nb_streams; i++)
  4052. if (!mov->tracks[i].entry)
  4053. break;
  4054. /* Don't write the initial moov unless all tracks have data */
  4055. if (i < mov->nb_streams && !force)
  4056. return 0;
  4057. moov_size = get_moov_size(s);
  4058. for (i = 0; i < mov->nb_streams; i++)
  4059. mov->tracks[i].data_offset = pos + moov_size + 8;
  4060. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
  4061. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  4062. mov_write_identification(s->pb, s);
  4063. if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
  4064. return ret;
  4065. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
  4066. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  4067. mov->reserved_header_pos = avio_tell(s->pb);
  4068. avio_flush(s->pb);
  4069. mov->moov_written = 1;
  4070. return 0;
  4071. }
  4072. buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
  4073. mov->mdat_buf = NULL;
  4074. avio_wb32(s->pb, buf_size + 8);
  4075. ffio_wfourcc(s->pb, "mdat");
  4076. avio_write(s->pb, buf, buf_size);
  4077. av_free(buf);
  4078. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  4079. mov->reserved_header_pos = avio_tell(s->pb);
  4080. mov->moov_written = 1;
  4081. mov->mdat_size = 0;
  4082. for (i = 0; i < mov->nb_streams; i++) {
  4083. if (mov->tracks[i].entry)
  4084. mov->tracks[i].frag_start += mov->tracks[i].start_dts +
  4085. mov->tracks[i].track_duration -
  4086. mov->tracks[i].cluster[0].dts;
  4087. mov->tracks[i].entry = 0;
  4088. mov->tracks[i].end_reliable = 0;
  4089. }
  4090. avio_flush(s->pb);
  4091. return 0;
  4092. }
  4093. if (mov->frag_interleave) {
  4094. for (i = 0; i < mov->nb_streams; i++) {
  4095. MOVTrack *track = &mov->tracks[i];
  4096. int ret;
  4097. if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
  4098. return ret;
  4099. }
  4100. if (!mov->mdat_buf)
  4101. return 0;
  4102. mdat_size = avio_tell(mov->mdat_buf);
  4103. }
  4104. for (i = 0; i < mov->nb_streams; i++) {
  4105. MOVTrack *track = &mov->tracks[i];
  4106. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
  4107. track->data_offset = 0;
  4108. else
  4109. track->data_offset = mdat_size;
  4110. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  4111. has_video = 1;
  4112. if (first_video_track) {
  4113. if (track->entry)
  4114. starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
  4115. first_video_track = 0;
  4116. }
  4117. }
  4118. if (!track->entry)
  4119. continue;
  4120. if (track->mdat_buf)
  4121. mdat_size += avio_tell(track->mdat_buf);
  4122. if (first_track < 0)
  4123. first_track = i;
  4124. }
  4125. if (!mdat_size)
  4126. return 0;
  4127. avio_write_marker(s->pb,
  4128. av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
  4129. (has_video ? starts_with_key : mov->tracks[first_track].cluster[0].flags & MOV_SYNC_SAMPLE) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT);
  4130. for (i = 0; i < mov->nb_streams; i++) {
  4131. MOVTrack *track = &mov->tracks[i];
  4132. int buf_size, write_moof = 1, moof_tracks = -1;
  4133. uint8_t *buf;
  4134. int64_t duration = 0;
  4135. if (track->entry)
  4136. duration = track->start_dts + track->track_duration -
  4137. track->cluster[0].dts;
  4138. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
  4139. if (!track->mdat_buf)
  4140. continue;
  4141. mdat_size = avio_tell(track->mdat_buf);
  4142. moof_tracks = i;
  4143. } else {
  4144. write_moof = i == first_track;
  4145. }
  4146. if (write_moof) {
  4147. avio_flush(s->pb);
  4148. mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
  4149. mov->fragments++;
  4150. avio_wb32(s->pb, mdat_size + 8);
  4151. ffio_wfourcc(s->pb, "mdat");
  4152. }
  4153. if (track->entry)
  4154. track->frag_start += duration;
  4155. track->entry = 0;
  4156. track->entries_flushed = 0;
  4157. track->end_reliable = 0;
  4158. if (!mov->frag_interleave) {
  4159. if (!track->mdat_buf)
  4160. continue;
  4161. buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
  4162. track->mdat_buf = NULL;
  4163. } else {
  4164. if (!mov->mdat_buf)
  4165. continue;
  4166. buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
  4167. mov->mdat_buf = NULL;
  4168. }
  4169. avio_write(s->pb, buf, buf_size);
  4170. av_free(buf);
  4171. }
  4172. mov->mdat_size = 0;
  4173. avio_flush(s->pb);
  4174. return 0;
  4175. }
  4176. static int mov_auto_flush_fragment(AVFormatContext *s, int force)
  4177. {
  4178. MOVMuxContext *mov = s->priv_data;
  4179. int had_moov = mov->moov_written;
  4180. int ret = mov_flush_fragment(s, force);
  4181. if (ret < 0)
  4182. return ret;
  4183. // If using delay_moov, the first flush only wrote the moov,
  4184. // not the actual moof+mdat pair, thus flush once again.
  4185. if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  4186. ret = mov_flush_fragment(s, force);
  4187. return ret;
  4188. }
  4189. static int check_pkt(AVFormatContext *s, AVPacket *pkt)
  4190. {
  4191. MOVMuxContext *mov = s->priv_data;
  4192. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4193. int64_t ref;
  4194. uint64_t duration;
  4195. if (trk->entry) {
  4196. ref = trk->cluster[trk->entry - 1].dts;
  4197. } else if ( trk->start_dts != AV_NOPTS_VALUE
  4198. && !trk->frag_discont) {
  4199. ref = trk->start_dts + trk->track_duration;
  4200. } else
  4201. ref = pkt->dts; // Skip tests for the first packet
  4202. duration = pkt->dts - ref;
  4203. if (pkt->dts < ref || duration >= INT_MAX) {
  4204. av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
  4205. duration, pkt->dts
  4206. );
  4207. pkt->dts = ref + 1;
  4208. pkt->pts = AV_NOPTS_VALUE;
  4209. }
  4210. if (pkt->duration < 0 || pkt->duration > INT_MAX) {
  4211. av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
  4212. return AVERROR(EINVAL);
  4213. }
  4214. return 0;
  4215. }
  4216. int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  4217. {
  4218. MOVMuxContext *mov = s->priv_data;
  4219. AVIOContext *pb = s->pb;
  4220. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4221. AVCodecParameters *par = trk->par;
  4222. unsigned int samples_in_chunk = 0;
  4223. int size = pkt->size, ret = 0;
  4224. uint8_t *reformatted_data = NULL;
  4225. ret = check_pkt(s, pkt);
  4226. if (ret < 0)
  4227. return ret;
  4228. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  4229. int ret;
  4230. if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  4231. if (mov->frag_interleave && mov->fragments > 0) {
  4232. if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
  4233. if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
  4234. return ret;
  4235. }
  4236. }
  4237. if (!trk->mdat_buf) {
  4238. if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
  4239. return ret;
  4240. }
  4241. pb = trk->mdat_buf;
  4242. } else {
  4243. if (!mov->mdat_buf) {
  4244. if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
  4245. return ret;
  4246. }
  4247. pb = mov->mdat_buf;
  4248. }
  4249. }
  4250. if (par->codec_id == AV_CODEC_ID_AMR_NB) {
  4251. /* We must find out how many AMR blocks there are in one packet */
  4252. static const uint16_t packed_size[16] =
  4253. {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
  4254. int len = 0;
  4255. while (len < size && samples_in_chunk < 100) {
  4256. len += packed_size[(pkt->data[len] >> 3) & 0x0F];
  4257. samples_in_chunk++;
  4258. }
  4259. if (samples_in_chunk > 1) {
  4260. av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
  4261. return -1;
  4262. }
  4263. } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
  4264. par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
  4265. samples_in_chunk = trk->par->frame_size;
  4266. } else if (trk->sample_size)
  4267. samples_in_chunk = size / trk->sample_size;
  4268. else
  4269. samples_in_chunk = 1;
  4270. if (samples_in_chunk < 1) {
  4271. av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n");
  4272. return AVERROR_PATCHWELCOME;
  4273. }
  4274. /* copy extradata if it exists */
  4275. if (trk->vos_len == 0 && par->extradata_size > 0 &&
  4276. !TAG_IS_AVCI(trk->tag) &&
  4277. (par->codec_id != AV_CODEC_ID_DNXHD)) {
  4278. trk->vos_len = par->extradata_size;
  4279. trk->vos_data = av_malloc(trk->vos_len);
  4280. if (!trk->vos_data) {
  4281. ret = AVERROR(ENOMEM);
  4282. goto err;
  4283. }
  4284. memcpy(trk->vos_data, par->extradata, trk->vos_len);
  4285. }
  4286. if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
  4287. (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
  4288. if (!s->streams[pkt->stream_index]->nb_frames) {
  4289. av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
  4290. "use the audio bitstream filter 'aac_adtstoasc' to fix it "
  4291. "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
  4292. return -1;
  4293. }
  4294. av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
  4295. }
  4296. if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
  4297. /* from x264 or from bytestream H.264 */
  4298. /* NAL reformatting needed */
  4299. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  4300. ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
  4301. &size);
  4302. avio_write(pb, reformatted_data, size);
  4303. } else {
  4304. if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
  4305. size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
  4306. if (size < 0) {
  4307. ret = size;
  4308. goto err;
  4309. }
  4310. } else {
  4311. size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
  4312. }
  4313. }
  4314. } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
  4315. (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
  4316. /* extradata is Annex B, assume the bitstream is too and convert it */
  4317. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  4318. ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
  4319. avio_write(pb, reformatted_data, size);
  4320. } else {
  4321. size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
  4322. }
  4323. #if CONFIG_AC3_PARSER
  4324. } else if (par->codec_id == AV_CODEC_ID_EAC3) {
  4325. size = handle_eac3(mov, pkt, trk);
  4326. if (size < 0)
  4327. return size;
  4328. else if (!size)
  4329. goto end;
  4330. avio_write(pb, pkt->data, size);
  4331. #endif
  4332. } else {
  4333. if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
  4334. if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
  4335. int nal_size_length = (par->extradata[4] & 0x3) + 1;
  4336. ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
  4337. } else {
  4338. ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
  4339. }
  4340. if (ret) {
  4341. goto err;
  4342. }
  4343. } else {
  4344. avio_write(pb, pkt->data, size);
  4345. }
  4346. }
  4347. if ((par->codec_id == AV_CODEC_ID_DNXHD ||
  4348. par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
  4349. /* copy frame to create needed atoms */
  4350. trk->vos_len = size;
  4351. trk->vos_data = av_malloc(size);
  4352. if (!trk->vos_data) {
  4353. ret = AVERROR(ENOMEM);
  4354. goto err;
  4355. }
  4356. memcpy(trk->vos_data, pkt->data, size);
  4357. }
  4358. if (trk->entry >= trk->cluster_capacity) {
  4359. unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
  4360. if (av_reallocp_array(&trk->cluster, new_capacity,
  4361. sizeof(*trk->cluster))) {
  4362. ret = AVERROR(ENOMEM);
  4363. goto err;
  4364. }
  4365. trk->cluster_capacity = new_capacity;
  4366. }
  4367. trk->cluster[trk->entry].pos = avio_tell(pb) - size;
  4368. trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
  4369. trk->cluster[trk->entry].chunkNum = 0;
  4370. trk->cluster[trk->entry].size = size;
  4371. trk->cluster[trk->entry].entries = samples_in_chunk;
  4372. trk->cluster[trk->entry].dts = pkt->dts;
  4373. if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
  4374. if (!trk->frag_discont) {
  4375. /* First packet of a new fragment. We already wrote the duration
  4376. * of the last packet of the previous fragment based on track_duration,
  4377. * which might not exactly match our dts. Therefore adjust the dts
  4378. * of this packet to be what the previous packets duration implies. */
  4379. trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
  4380. /* We also may have written the pts and the corresponding duration
  4381. * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
  4382. * the next fragment. This means the cts of the first sample must
  4383. * be the same in all fragments, unless end_pts was updated by
  4384. * the packet causing the fragment to be written. */
  4385. if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
  4386. mov->mode == MODE_ISM)
  4387. pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
  4388. } else {
  4389. /* New fragment, but discontinuous from previous fragments.
  4390. * Pretend the duration sum of the earlier fragments is
  4391. * pkt->dts - trk->start_dts. */
  4392. trk->frag_start = pkt->dts - trk->start_dts;
  4393. trk->end_pts = AV_NOPTS_VALUE;
  4394. trk->frag_discont = 0;
  4395. }
  4396. }
  4397. if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
  4398. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
  4399. /* Not using edit lists and shifting the first track to start from zero.
  4400. * If the other streams start from a later timestamp, we won't be able
  4401. * to signal the difference in starting time without an edit list.
  4402. * Thus move the timestamp for this first sample to 0, increasing
  4403. * its duration instead. */
  4404. trk->cluster[trk->entry].dts = trk->start_dts = 0;
  4405. }
  4406. if (trk->start_dts == AV_NOPTS_VALUE) {
  4407. trk->start_dts = pkt->dts;
  4408. if (trk->frag_discont) {
  4409. if (mov->use_editlist) {
  4410. /* Pretend the whole stream started at pts=0, with earlier fragments
  4411. * already written. If the stream started at pts=0, the duration sum
  4412. * of earlier fragments would have been pkt->pts. */
  4413. trk->frag_start = pkt->pts;
  4414. trk->start_dts = pkt->dts - pkt->pts;
  4415. } else {
  4416. /* Pretend the whole stream started at dts=0, with earlier fragments
  4417. * already written, with a duration summing up to pkt->dts. */
  4418. trk->frag_start = pkt->dts;
  4419. trk->start_dts = 0;
  4420. }
  4421. trk->frag_discont = 0;
  4422. } else if (pkt->dts && mov->moov_written)
  4423. av_log(s, AV_LOG_WARNING,
  4424. "Track %d starts with a nonzero dts %"PRId64", while the moov "
  4425. "already has been written. Set the delay_moov flag to handle "
  4426. "this case.\n",
  4427. pkt->stream_index, pkt->dts);
  4428. }
  4429. trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
  4430. trk->last_sample_is_subtitle_end = 0;
  4431. if (pkt->pts == AV_NOPTS_VALUE) {
  4432. av_log(s, AV_LOG_WARNING, "pts has no value\n");
  4433. pkt->pts = pkt->dts;
  4434. }
  4435. if (pkt->dts != pkt->pts)
  4436. trk->flags |= MOV_TRACK_CTTS;
  4437. trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
  4438. trk->cluster[trk->entry].flags = 0;
  4439. if (trk->start_cts == AV_NOPTS_VALUE)
  4440. trk->start_cts = pkt->pts - pkt->dts;
  4441. if (trk->end_pts == AV_NOPTS_VALUE)
  4442. trk->end_pts = trk->cluster[trk->entry].dts +
  4443. trk->cluster[trk->entry].cts + pkt->duration;
  4444. else
  4445. trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
  4446. trk->cluster[trk->entry].cts +
  4447. pkt->duration);
  4448. if (par->codec_id == AV_CODEC_ID_VC1) {
  4449. mov_parse_vc1_frame(pkt, trk);
  4450. } else if (pkt->flags & AV_PKT_FLAG_KEY) {
  4451. if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
  4452. trk->entry > 0) { // force sync sample for the first key frame
  4453. mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
  4454. if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
  4455. trk->flags |= MOV_TRACK_STPS;
  4456. } else {
  4457. trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
  4458. }
  4459. if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
  4460. trk->has_keyframes++;
  4461. }
  4462. trk->entry++;
  4463. trk->sample_count += samples_in_chunk;
  4464. mov->mdat_size += size;
  4465. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
  4466. ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
  4467. reformatted_data, size);
  4468. end:
  4469. err:
  4470. av_free(reformatted_data);
  4471. return ret;
  4472. }
  4473. static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
  4474. {
  4475. MOVMuxContext *mov = s->priv_data;
  4476. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4477. AVCodecParameters *par = trk->par;
  4478. int64_t frag_duration = 0;
  4479. int size = pkt->size;
  4480. int ret = check_pkt(s, pkt);
  4481. if (ret < 0)
  4482. return ret;
  4483. if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
  4484. int i;
  4485. for (i = 0; i < s->nb_streams; i++)
  4486. mov->tracks[i].frag_discont = 1;
  4487. mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
  4488. }
  4489. if (!pkt->size) {
  4490. if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
  4491. trk->start_dts = pkt->dts;
  4492. if (pkt->pts != AV_NOPTS_VALUE)
  4493. trk->start_cts = pkt->pts - pkt->dts;
  4494. else
  4495. trk->start_cts = 0;
  4496. }
  4497. if (trk->par->codec_id == AV_CODEC_ID_MP4ALS) {
  4498. int side_size = 0;
  4499. uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
  4500. if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
  4501. void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
  4502. if (!newextra)
  4503. return AVERROR(ENOMEM);
  4504. av_free(par->extradata);
  4505. par->extradata = newextra;
  4506. memcpy(par->extradata, side, side_size);
  4507. par->extradata_size = side_size;
  4508. mov->need_rewrite_extradata = 1;
  4509. }
  4510. }
  4511. return 0; /* Discard 0 sized packets */
  4512. }
  4513. if (trk->entry && pkt->stream_index < s->nb_streams)
  4514. frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
  4515. s->streams[pkt->stream_index]->time_base,
  4516. AV_TIME_BASE_Q);
  4517. if ((mov->max_fragment_duration &&
  4518. frag_duration >= mov->max_fragment_duration) ||
  4519. (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
  4520. (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
  4521. par->codec_type == AVMEDIA_TYPE_VIDEO &&
  4522. trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
  4523. if (frag_duration >= mov->min_fragment_duration) {
  4524. // Set the duration of this track to line up with the next
  4525. // sample in this track. This avoids relying on AVPacket
  4526. // duration, but only helps for this particular track, not
  4527. // for the other ones that are flushed at the same time.
  4528. trk->track_duration = pkt->dts - trk->start_dts;
  4529. if (pkt->pts != AV_NOPTS_VALUE)
  4530. trk->end_pts = pkt->pts;
  4531. else
  4532. trk->end_pts = pkt->dts;
  4533. trk->end_reliable = 1;
  4534. mov_auto_flush_fragment(s, 0);
  4535. }
  4536. }
  4537. return ff_mov_write_packet(s, pkt);
  4538. }
  4539. static int mov_write_subtitle_end_packet(AVFormatContext *s,
  4540. int stream_index,
  4541. int64_t dts) {
  4542. AVPacket end;
  4543. uint8_t data[2] = {0};
  4544. int ret;
  4545. av_init_packet(&end);
  4546. end.size = sizeof(data);
  4547. end.data = data;
  4548. end.pts = dts;
  4549. end.dts = dts;
  4550. end.duration = 0;
  4551. end.stream_index = stream_index;
  4552. ret = mov_write_single_packet(s, &end);
  4553. av_packet_unref(&end);
  4554. return ret;
  4555. }
  4556. static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  4557. {
  4558. if (!pkt) {
  4559. mov_flush_fragment(s, 1);
  4560. return 1;
  4561. } else {
  4562. int i;
  4563. MOVMuxContext *mov = s->priv_data;
  4564. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4565. if (!pkt->size)
  4566. return mov_write_single_packet(s, pkt); /* Passthrough. */
  4567. /*
  4568. * Subtitles require special handling.
  4569. *
  4570. * 1) For full complaince, every track must have a sample at
  4571. * dts == 0, which is rarely true for subtitles. So, as soon
  4572. * as we see any packet with dts > 0, write an empty subtitle
  4573. * at dts == 0 for any subtitle track with no samples in it.
  4574. *
  4575. * 2) For each subtitle track, check if the current packet's
  4576. * dts is past the duration of the last subtitle sample. If
  4577. * so, we now need to write an end sample for that subtitle.
  4578. *
  4579. * This must be done conditionally to allow for subtitles that
  4580. * immediately replace each other, in which case an end sample
  4581. * is not needed, and is, in fact, actively harmful.
  4582. *
  4583. * 3) See mov_write_trailer for how the final end sample is
  4584. * handled.
  4585. */
  4586. for (i = 0; i < mov->nb_streams; i++) {
  4587. MOVTrack *trk = &mov->tracks[i];
  4588. int ret;
  4589. if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
  4590. trk->track_duration < pkt->dts &&
  4591. (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
  4592. ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
  4593. if (ret < 0) return ret;
  4594. trk->last_sample_is_subtitle_end = 1;
  4595. }
  4596. }
  4597. if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  4598. AVPacket *opkt = pkt;
  4599. int reshuffle_ret, ret;
  4600. if (trk->is_unaligned_qt_rgb) {
  4601. int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
  4602. int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
  4603. reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
  4604. if (reshuffle_ret < 0)
  4605. return reshuffle_ret;
  4606. } else
  4607. reshuffle_ret = 0;
  4608. if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
  4609. ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
  4610. if (ret < 0)
  4611. goto fail;
  4612. if (ret)
  4613. trk->pal_done++;
  4614. } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
  4615. (trk->par->format == AV_PIX_FMT_GRAY8 ||
  4616. trk->par->format == AV_PIX_FMT_MONOBLACK)) {
  4617. for (i = 0; i < pkt->size; i++)
  4618. pkt->data[i] = ~pkt->data[i];
  4619. }
  4620. if (reshuffle_ret) {
  4621. ret = mov_write_single_packet(s, pkt);
  4622. fail:
  4623. if (reshuffle_ret)
  4624. av_packet_free(&pkt);
  4625. return ret;
  4626. }
  4627. }
  4628. return mov_write_single_packet(s, pkt);
  4629. }
  4630. }
  4631. // QuickTime chapters involve an additional text track with the chapter names
  4632. // as samples, and a tref pointing from the other tracks to the chapter one.
  4633. static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
  4634. {
  4635. AVIOContext *pb;
  4636. MOVMuxContext *mov = s->priv_data;
  4637. MOVTrack *track = &mov->tracks[tracknum];
  4638. AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
  4639. int i, len;
  4640. track->mode = mov->mode;
  4641. track->tag = MKTAG('t','e','x','t');
  4642. track->timescale = MOV_TIMESCALE;
  4643. track->par = avcodec_parameters_alloc();
  4644. if (!track->par)
  4645. return AVERROR(ENOMEM);
  4646. track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
  4647. #if 0
  4648. // These properties are required to make QT recognize the chapter track
  4649. uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
  4650. if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
  4651. return AVERROR(ENOMEM);
  4652. memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
  4653. #else
  4654. if (avio_open_dyn_buf(&pb) >= 0) {
  4655. int size;
  4656. uint8_t *buf;
  4657. /* Stub header (usually for Quicktime chapter track) */
  4658. // TextSampleEntry
  4659. avio_wb32(pb, 0x01); // displayFlags
  4660. avio_w8(pb, 0x00); // horizontal justification
  4661. avio_w8(pb, 0x00); // vertical justification
  4662. avio_w8(pb, 0x00); // bgColourRed
  4663. avio_w8(pb, 0x00); // bgColourGreen
  4664. avio_w8(pb, 0x00); // bgColourBlue
  4665. avio_w8(pb, 0x00); // bgColourAlpha
  4666. // BoxRecord
  4667. avio_wb16(pb, 0x00); // defTextBoxTop
  4668. avio_wb16(pb, 0x00); // defTextBoxLeft
  4669. avio_wb16(pb, 0x00); // defTextBoxBottom
  4670. avio_wb16(pb, 0x00); // defTextBoxRight
  4671. // StyleRecord
  4672. avio_wb16(pb, 0x00); // startChar
  4673. avio_wb16(pb, 0x00); // endChar
  4674. avio_wb16(pb, 0x01); // fontID
  4675. avio_w8(pb, 0x00); // fontStyleFlags
  4676. avio_w8(pb, 0x00); // fontSize
  4677. avio_w8(pb, 0x00); // fgColourRed
  4678. avio_w8(pb, 0x00); // fgColourGreen
  4679. avio_w8(pb, 0x00); // fgColourBlue
  4680. avio_w8(pb, 0x00); // fgColourAlpha
  4681. // FontTableBox
  4682. avio_wb32(pb, 0x0D); // box size
  4683. ffio_wfourcc(pb, "ftab"); // box atom name
  4684. avio_wb16(pb, 0x01); // entry count
  4685. // FontRecord
  4686. avio_wb16(pb, 0x01); // font ID
  4687. avio_w8(pb, 0x00); // font name length
  4688. if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
  4689. track->par->extradata = buf;
  4690. track->par->extradata_size = size;
  4691. } else {
  4692. av_freep(&buf);
  4693. }
  4694. }
  4695. #endif
  4696. for (i = 0; i < s->nb_chapters; i++) {
  4697. AVChapter *c = s->chapters[i];
  4698. AVDictionaryEntry *t;
  4699. int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
  4700. pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
  4701. pkt.duration = end - pkt.dts;
  4702. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  4703. static const char encd[12] = {
  4704. 0x00, 0x00, 0x00, 0x0C,
  4705. 'e', 'n', 'c', 'd',
  4706. 0x00, 0x00, 0x01, 0x00 };
  4707. len = strlen(t->value);
  4708. pkt.size = len + 2 + 12;
  4709. pkt.data = av_malloc(pkt.size);
  4710. if (!pkt.data)
  4711. return AVERROR(ENOMEM);
  4712. AV_WB16(pkt.data, len);
  4713. memcpy(pkt.data + 2, t->value, len);
  4714. memcpy(pkt.data + len + 2, encd, sizeof(encd));
  4715. ff_mov_write_packet(s, &pkt);
  4716. av_freep(&pkt.data);
  4717. }
  4718. }
  4719. return 0;
  4720. }
  4721. static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
  4722. {
  4723. int ret;
  4724. /* compute the frame number */
  4725. ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
  4726. return ret;
  4727. }
  4728. static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
  4729. {
  4730. int ret;
  4731. MOVMuxContext *mov = s->priv_data;
  4732. MOVTrack *track = &mov->tracks[index];
  4733. AVStream *src_st = s->streams[src_index];
  4734. AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
  4735. AVRational rate = find_fps(s, src_st);
  4736. /* tmcd track based on video stream */
  4737. track->mode = mov->mode;
  4738. track->tag = MKTAG('t','m','c','d');
  4739. track->src_track = src_index;
  4740. track->timescale = mov->tracks[src_index].timescale;
  4741. if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
  4742. track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
  4743. /* set st to src_st for metadata access*/
  4744. track->st = src_st;
  4745. /* encode context: tmcd data stream */
  4746. track->par = avcodec_parameters_alloc();
  4747. if (!track->par)
  4748. return AVERROR(ENOMEM);
  4749. track->par->codec_type = AVMEDIA_TYPE_DATA;
  4750. track->par->codec_tag = track->tag;
  4751. track->st->avg_frame_rate = av_inv_q(rate);
  4752. /* the tmcd track just contains one packet with the frame number */
  4753. pkt.data = av_malloc(pkt.size);
  4754. if (!pkt.data)
  4755. return AVERROR(ENOMEM);
  4756. AV_WB32(pkt.data, tc.start);
  4757. ret = ff_mov_write_packet(s, &pkt);
  4758. av_free(pkt.data);
  4759. return ret;
  4760. }
  4761. /*
  4762. * st->disposition controls the "enabled" flag in the tkhd tag.
  4763. * QuickTime will not play a track if it is not enabled. So make sure
  4764. * that one track of each type (audio, video, subtitle) is enabled.
  4765. *
  4766. * Subtitles are special. For audio and video, setting "enabled" also
  4767. * makes the track "default" (i.e. it is rendered when played). For
  4768. * subtitles, an "enabled" subtitle is not rendered by default, but
  4769. * if no subtitle is enabled, the subtitle menu in QuickTime will be
  4770. * empty!
  4771. */
  4772. static void enable_tracks(AVFormatContext *s)
  4773. {
  4774. MOVMuxContext *mov = s->priv_data;
  4775. int i;
  4776. int enabled[AVMEDIA_TYPE_NB];
  4777. int first[AVMEDIA_TYPE_NB];
  4778. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  4779. enabled[i] = 0;
  4780. first[i] = -1;
  4781. }
  4782. for (i = 0; i < s->nb_streams; i++) {
  4783. AVStream *st = s->streams[i];
  4784. if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
  4785. st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
  4786. continue;
  4787. if (first[st->codecpar->codec_type] < 0)
  4788. first[st->codecpar->codec_type] = i;
  4789. if (st->disposition & AV_DISPOSITION_DEFAULT) {
  4790. mov->tracks[i].flags |= MOV_TRACK_ENABLED;
  4791. enabled[st->codecpar->codec_type]++;
  4792. }
  4793. }
  4794. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  4795. switch (i) {
  4796. case AVMEDIA_TYPE_VIDEO:
  4797. case AVMEDIA_TYPE_AUDIO:
  4798. case AVMEDIA_TYPE_SUBTITLE:
  4799. if (enabled[i] > 1)
  4800. mov->per_stream_grouping = 1;
  4801. if (!enabled[i] && first[i] >= 0)
  4802. mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
  4803. break;
  4804. }
  4805. }
  4806. }
  4807. static void mov_free(AVFormatContext *s)
  4808. {
  4809. MOVMuxContext *mov = s->priv_data;
  4810. int i;
  4811. if (mov->chapter_track) {
  4812. if (mov->tracks[mov->chapter_track].par)
  4813. av_freep(&mov->tracks[mov->chapter_track].par->extradata);
  4814. av_freep(&mov->tracks[mov->chapter_track].par);
  4815. }
  4816. for (i = 0; i < mov->nb_streams; i++) {
  4817. if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
  4818. ff_mov_close_hinting(&mov->tracks[i]);
  4819. else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
  4820. av_freep(&mov->tracks[i].par);
  4821. av_freep(&mov->tracks[i].cluster);
  4822. av_freep(&mov->tracks[i].frag_info);
  4823. if (mov->tracks[i].vos_len)
  4824. av_freep(&mov->tracks[i].vos_data);
  4825. ff_mov_cenc_free(&mov->tracks[i].cenc);
  4826. }
  4827. av_freep(&mov->tracks);
  4828. }
  4829. static uint32_t rgb_to_yuv(uint32_t rgb)
  4830. {
  4831. uint8_t r, g, b;
  4832. int y, cb, cr;
  4833. r = (rgb >> 16) & 0xFF;
  4834. g = (rgb >> 8) & 0xFF;
  4835. b = (rgb ) & 0xFF;
  4836. y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
  4837. cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
  4838. cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
  4839. return (y << 16) | (cr << 8) | cb;
  4840. }
  4841. static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
  4842. AVStream *st)
  4843. {
  4844. int i, width = 720, height = 480;
  4845. int have_palette = 0, have_size = 0;
  4846. uint32_t palette[16];
  4847. char *cur = st->codecpar->extradata;
  4848. while (cur && *cur) {
  4849. if (strncmp("palette:", cur, 8) == 0) {
  4850. int i, count;
  4851. count = sscanf(cur + 8,
  4852. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  4853. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  4854. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  4855. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
  4856. &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
  4857. &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
  4858. &palette[ 8], &palette[ 9], &palette[10], &palette[11],
  4859. &palette[12], &palette[13], &palette[14], &palette[15]);
  4860. for (i = 0; i < count; i++) {
  4861. palette[i] = rgb_to_yuv(palette[i]);
  4862. }
  4863. have_palette = 1;
  4864. } else if (!strncmp("size:", cur, 5)) {
  4865. sscanf(cur + 5, "%dx%d", &width, &height);
  4866. have_size = 1;
  4867. }
  4868. if (have_palette && have_size)
  4869. break;
  4870. cur += strcspn(cur, "\n\r");
  4871. cur += strspn(cur, "\n\r");
  4872. }
  4873. if (have_palette) {
  4874. track->vos_data = av_malloc(16*4);
  4875. if (!track->vos_data)
  4876. return AVERROR(ENOMEM);
  4877. for (i = 0; i < 16; i++) {
  4878. AV_WB32(track->vos_data + i * 4, palette[i]);
  4879. }
  4880. track->vos_len = 16 * 4;
  4881. }
  4882. st->codecpar->width = width;
  4883. st->codecpar->height = track->height = height;
  4884. return 0;
  4885. }
  4886. static int mov_init(AVFormatContext *s)
  4887. {
  4888. MOVMuxContext *mov = s->priv_data;
  4889. AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  4890. int i, ret, hint_track = 0, tmcd_track = 0;
  4891. mov->fc = s;
  4892. /* Default mode == MP4 */
  4893. mov->mode = MODE_MP4;
  4894. if (s->oformat) {
  4895. if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
  4896. else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
  4897. else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
  4898. else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
  4899. else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
  4900. else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
  4901. else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
  4902. }
  4903. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  4904. mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
  4905. /* Set the FRAGMENT flag if any of the fragmentation methods are
  4906. * enabled. */
  4907. if (mov->max_fragment_duration || mov->max_fragment_size ||
  4908. mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
  4909. FF_MOV_FLAG_FRAG_KEYFRAME |
  4910. FF_MOV_FLAG_FRAG_CUSTOM))
  4911. mov->flags |= FF_MOV_FLAG_FRAGMENT;
  4912. /* Set other implicit flags immediately */
  4913. if (mov->mode == MODE_ISM)
  4914. mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
  4915. FF_MOV_FLAG_FRAGMENT;
  4916. if (mov->flags & FF_MOV_FLAG_DASH)
  4917. mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
  4918. FF_MOV_FLAG_DEFAULT_BASE_MOOF;
  4919. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
  4920. av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
  4921. s->flags &= ~AVFMT_FLAG_AUTO_BSF;
  4922. }
  4923. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  4924. mov->reserved_moov_size = -1;
  4925. }
  4926. if (mov->use_editlist < 0) {
  4927. mov->use_editlist = 1;
  4928. if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
  4929. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  4930. // If we can avoid needing an edit list by shifting the
  4931. // tracks, prefer that over (trying to) write edit lists
  4932. // in fragmented output.
  4933. if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
  4934. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
  4935. mov->use_editlist = 0;
  4936. }
  4937. }
  4938. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
  4939. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
  4940. av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
  4941. if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
  4942. s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
  4943. /* Clear the omit_tfhd_offset flag if default_base_moof is set;
  4944. * if the latter is set that's enough and omit_tfhd_offset doesn't
  4945. * add anything extra on top of that. */
  4946. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
  4947. mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
  4948. mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
  4949. if (mov->frag_interleave &&
  4950. mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
  4951. av_log(s, AV_LOG_ERROR,
  4952. "Sample interleaving in fragments is mutually exclusive with "
  4953. "omit_tfhd_offset and separate_moof\n");
  4954. return AVERROR(EINVAL);
  4955. }
  4956. /* Non-seekable output is ok if using fragmentation. If ism_lookahead
  4957. * is enabled, we don't support non-seekable output at all. */
  4958. if (!s->pb->seekable &&
  4959. (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
  4960. av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
  4961. return AVERROR(EINVAL);
  4962. }
  4963. mov->nb_streams = s->nb_streams;
  4964. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
  4965. mov->chapter_track = mov->nb_streams++;
  4966. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  4967. /* Add hint tracks for each audio and video stream */
  4968. hint_track = mov->nb_streams;
  4969. for (i = 0; i < s->nb_streams; i++) {
  4970. AVStream *st = s->streams[i];
  4971. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
  4972. st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  4973. mov->nb_streams++;
  4974. }
  4975. }
  4976. }
  4977. if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
  4978. || mov->write_tmcd == 1) {
  4979. tmcd_track = mov->nb_streams;
  4980. /* +1 tmcd track for each video stream with a timecode */
  4981. for (i = 0; i < s->nb_streams; i++) {
  4982. AVStream *st = s->streams[i];
  4983. AVDictionaryEntry *t = global_tcr;
  4984. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  4985. (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
  4986. AVTimecode tc;
  4987. ret = mov_check_timecode_track(s, &tc, i, t->value);
  4988. if (ret >= 0)
  4989. mov->nb_meta_tmcd++;
  4990. }
  4991. }
  4992. /* check if there is already a tmcd track to remux */
  4993. if (mov->nb_meta_tmcd) {
  4994. for (i = 0; i < s->nb_streams; i++) {
  4995. AVStream *st = s->streams[i];
  4996. if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
  4997. av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
  4998. "so timecode metadata are now ignored\n");
  4999. mov->nb_meta_tmcd = 0;
  5000. }
  5001. }
  5002. }
  5003. mov->nb_streams += mov->nb_meta_tmcd;
  5004. }
  5005. // Reserve an extra stream for chapters for the case where chapters
  5006. // are written in the trailer
  5007. mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
  5008. if (!mov->tracks)
  5009. return AVERROR(ENOMEM);
  5010. if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
  5011. if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
  5012. mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
  5013. if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
  5014. av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
  5015. mov->encryption_key_len, AES_CTR_KEY_SIZE);
  5016. return AVERROR(EINVAL);
  5017. }
  5018. if (mov->encryption_kid_len != CENC_KID_SIZE) {
  5019. av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
  5020. mov->encryption_kid_len, CENC_KID_SIZE);
  5021. return AVERROR(EINVAL);
  5022. }
  5023. } else {
  5024. av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
  5025. mov->encryption_scheme_str);
  5026. return AVERROR(EINVAL);
  5027. }
  5028. }
  5029. for (i = 0; i < s->nb_streams; i++) {
  5030. AVStream *st= s->streams[i];
  5031. MOVTrack *track= &mov->tracks[i];
  5032. AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
  5033. track->st = st;
  5034. track->par = st->codecpar;
  5035. track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
  5036. if (track->language < 0)
  5037. track->language = 0;
  5038. track->mode = mov->mode;
  5039. track->tag = mov_find_codec_tag(s, track);
  5040. if (!track->tag) {
  5041. av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
  5042. "codec not currently supported in container\n",
  5043. avcodec_get_name(st->codecpar->codec_id), i);
  5044. return AVERROR(EINVAL);
  5045. }
  5046. /* If hinting of this track is enabled by a later hint track,
  5047. * this is updated. */
  5048. track->hint_track = -1;
  5049. track->start_dts = AV_NOPTS_VALUE;
  5050. track->start_cts = AV_NOPTS_VALUE;
  5051. track->end_pts = AV_NOPTS_VALUE;
  5052. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  5053. if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
  5054. track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
  5055. track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
  5056. if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
  5057. av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
  5058. return AVERROR(EINVAL);
  5059. }
  5060. track->height = track->tag >> 24 == 'n' ? 486 : 576;
  5061. }
  5062. if (mov->video_track_timescale) {
  5063. track->timescale = mov->video_track_timescale;
  5064. } else {
  5065. track->timescale = st->time_base.den;
  5066. while(track->timescale < 10000)
  5067. track->timescale *= 2;
  5068. }
  5069. if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
  5070. av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
  5071. return AVERROR(EINVAL);
  5072. }
  5073. if (track->mode == MODE_MOV && track->timescale > 100000)
  5074. av_log(s, AV_LOG_WARNING,
  5075. "WARNING codec timebase is very high. If duration is too long,\n"
  5076. "file may not be playable by quicktime. Specify a shorter timebase\n"
  5077. "or choose different container.\n");
  5078. if (track->mode == MODE_MOV &&
  5079. track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
  5080. track->tag == MKTAG('r','a','w',' ')) {
  5081. enum AVPixelFormat pix_fmt = track->par->format;
  5082. if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
  5083. pix_fmt = AV_PIX_FMT_MONOWHITE;
  5084. track->is_unaligned_qt_rgb =
  5085. pix_fmt == AV_PIX_FMT_RGB24 ||
  5086. pix_fmt == AV_PIX_FMT_BGR24 ||
  5087. pix_fmt == AV_PIX_FMT_PAL8 ||
  5088. pix_fmt == AV_PIX_FMT_GRAY8 ||
  5089. pix_fmt == AV_PIX_FMT_MONOWHITE ||
  5090. pix_fmt == AV_PIX_FMT_MONOBLACK;
  5091. }
  5092. if (track->mode == MODE_MP4 &&
  5093. track->par->codec_id == AV_CODEC_ID_VP9) {
  5094. if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  5095. av_log(s, AV_LOG_ERROR,
  5096. "VP9 in MP4 support is experimental, add "
  5097. "'-strict %d' if you want to use it.\n",
  5098. FF_COMPLIANCE_EXPERIMENTAL);
  5099. return AVERROR_EXPERIMENTAL;
  5100. }
  5101. }
  5102. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  5103. track->timescale = st->codecpar->sample_rate;
  5104. if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
  5105. av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
  5106. track->audio_vbr = 1;
  5107. }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
  5108. st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  5109. st->codecpar->codec_id == AV_CODEC_ID_ILBC){
  5110. if (!st->codecpar->block_align) {
  5111. av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
  5112. return AVERROR(EINVAL);
  5113. }
  5114. track->sample_size = st->codecpar->block_align;
  5115. }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
  5116. track->audio_vbr = 1;
  5117. }else{
  5118. track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
  5119. }
  5120. if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
  5121. st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
  5122. track->audio_vbr = 1;
  5123. }
  5124. if (track->mode != MODE_MOV &&
  5125. track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
  5126. if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
  5127. av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
  5128. i, track->par->sample_rate);
  5129. return AVERROR(EINVAL);
  5130. } else {
  5131. av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
  5132. i, track->par->sample_rate);
  5133. }
  5134. }
  5135. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  5136. track->timescale = st->time_base.den;
  5137. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
  5138. track->timescale = st->time_base.den;
  5139. } else {
  5140. track->timescale = MOV_TIMESCALE;
  5141. }
  5142. if (!track->height)
  5143. track->height = st->codecpar->height;
  5144. /* The ism specific timescale isn't mandatory, but is assumed by
  5145. * some tools, such as mp4split. */
  5146. if (mov->mode == MODE_ISM)
  5147. track->timescale = 10000000;
  5148. avpriv_set_pts_info(st, 64, 1, track->timescale);
  5149. if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
  5150. ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
  5151. track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
  5152. if (ret)
  5153. return ret;
  5154. }
  5155. }
  5156. enable_tracks(s);
  5157. return 0;
  5158. }
  5159. static int mov_write_header(AVFormatContext *s)
  5160. {
  5161. AVIOContext *pb = s->pb;
  5162. MOVMuxContext *mov = s->priv_data;
  5163. AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  5164. int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
  5165. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
  5166. nb_tracks++;
  5167. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  5168. /* Add hint tracks for each audio and video stream */
  5169. hint_track = nb_tracks;
  5170. for (i = 0; i < s->nb_streams; i++) {
  5171. AVStream *st = s->streams[i];
  5172. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
  5173. st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  5174. nb_tracks++;
  5175. }
  5176. }
  5177. }
  5178. if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
  5179. tmcd_track = nb_tracks;
  5180. for (i = 0; i < s->nb_streams; i++) {
  5181. int j;
  5182. AVStream *st= s->streams[i];
  5183. MOVTrack *track= &mov->tracks[i];
  5184. /* copy extradata if it exists */
  5185. if (st->codecpar->extradata_size) {
  5186. if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  5187. mov_create_dvd_sub_decoder_specific_info(track, st);
  5188. else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
  5189. track->vos_len = st->codecpar->extradata_size;
  5190. track->vos_data = av_malloc(track->vos_len);
  5191. if (!track->vos_data) {
  5192. return AVERROR(ENOMEM);
  5193. }
  5194. memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
  5195. }
  5196. }
  5197. if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
  5198. track->par->channel_layout != AV_CH_LAYOUT_MONO)
  5199. continue;
  5200. for (j = 0; j < s->nb_streams; j++) {
  5201. AVStream *stj= s->streams[j];
  5202. MOVTrack *trackj= &mov->tracks[j];
  5203. if (j == i)
  5204. continue;
  5205. if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
  5206. trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
  5207. trackj->language != track->language ||
  5208. trackj->tag != track->tag
  5209. )
  5210. continue;
  5211. track->multichannel_as_mono++;
  5212. }
  5213. }
  5214. if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  5215. if ((ret = mov_write_identification(pb, s)) < 0)
  5216. return ret;
  5217. }
  5218. if (mov->reserved_moov_size){
  5219. mov->reserved_header_pos = avio_tell(pb);
  5220. if (mov->reserved_moov_size > 0)
  5221. avio_skip(pb, mov->reserved_moov_size);
  5222. }
  5223. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  5224. /* If no fragmentation options have been set, set a default. */
  5225. if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
  5226. FF_MOV_FLAG_FRAG_CUSTOM)) &&
  5227. !mov->max_fragment_duration && !mov->max_fragment_size)
  5228. mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
  5229. } else {
  5230. if (mov->flags & FF_MOV_FLAG_FASTSTART)
  5231. mov->reserved_header_pos = avio_tell(pb);
  5232. mov_write_mdat_tag(pb, mov);
  5233. }
  5234. ff_parse_creation_time_metadata(s, &mov->time, 1);
  5235. if (mov->time)
  5236. mov->time += 0x7C25B080; // 1970 based -> 1904 based
  5237. if (mov->chapter_track)
  5238. if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  5239. return ret;
  5240. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  5241. /* Initialize the hint tracks for each audio and video stream */
  5242. for (i = 0; i < s->nb_streams; i++) {
  5243. AVStream *st = s->streams[i];
  5244. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
  5245. st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  5246. if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
  5247. return ret;
  5248. hint_track++;
  5249. }
  5250. }
  5251. }
  5252. if (mov->nb_meta_tmcd) {
  5253. /* Initialize the tmcd tracks */
  5254. for (i = 0; i < s->nb_streams; i++) {
  5255. AVStream *st = s->streams[i];
  5256. t = global_tcr;
  5257. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  5258. AVTimecode tc;
  5259. if (!t)
  5260. t = av_dict_get(st->metadata, "timecode", NULL, 0);
  5261. if (!t)
  5262. continue;
  5263. if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
  5264. continue;
  5265. if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
  5266. return ret;
  5267. tmcd_track++;
  5268. }
  5269. }
  5270. }
  5271. avio_flush(pb);
  5272. if (mov->flags & FF_MOV_FLAG_ISML)
  5273. mov_write_isml_manifest(pb, mov, s);
  5274. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
  5275. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  5276. if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
  5277. return ret;
  5278. avio_flush(pb);
  5279. mov->moov_written = 1;
  5280. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  5281. mov->reserved_header_pos = avio_tell(pb);
  5282. }
  5283. return 0;
  5284. }
  5285. static int get_moov_size(AVFormatContext *s)
  5286. {
  5287. int ret;
  5288. AVIOContext *moov_buf;
  5289. MOVMuxContext *mov = s->priv_data;
  5290. if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
  5291. return ret;
  5292. if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
  5293. return ret;
  5294. return ffio_close_null_buf(moov_buf);
  5295. }
  5296. static int get_sidx_size(AVFormatContext *s)
  5297. {
  5298. int ret;
  5299. AVIOContext *buf;
  5300. MOVMuxContext *mov = s->priv_data;
  5301. if ((ret = ffio_open_null_buf(&buf)) < 0)
  5302. return ret;
  5303. mov_write_sidx_tags(buf, mov, -1, 0);
  5304. return ffio_close_null_buf(buf);
  5305. }
  5306. /*
  5307. * This function gets the moov size if moved to the top of the file: the chunk
  5308. * offset table can switch between stco (32-bit entries) to co64 (64-bit
  5309. * entries) when the moov is moved to the beginning, so the size of the moov
  5310. * would change. It also updates the chunk offset tables.
  5311. */
  5312. static int compute_moov_size(AVFormatContext *s)
  5313. {
  5314. int i, moov_size, moov_size2;
  5315. MOVMuxContext *mov = s->priv_data;
  5316. moov_size = get_moov_size(s);
  5317. if (moov_size < 0)
  5318. return moov_size;
  5319. for (i = 0; i < mov->nb_streams; i++)
  5320. mov->tracks[i].data_offset += moov_size;
  5321. moov_size2 = get_moov_size(s);
  5322. if (moov_size2 < 0)
  5323. return moov_size2;
  5324. /* if the size changed, we just switched from stco to co64 and need to
  5325. * update the offsets */
  5326. if (moov_size2 != moov_size)
  5327. for (i = 0; i < mov->nb_streams; i++)
  5328. mov->tracks[i].data_offset += moov_size2 - moov_size;
  5329. return moov_size2;
  5330. }
  5331. static int compute_sidx_size(AVFormatContext *s)
  5332. {
  5333. int i, sidx_size;
  5334. MOVMuxContext *mov = s->priv_data;
  5335. sidx_size = get_sidx_size(s);
  5336. if (sidx_size < 0)
  5337. return sidx_size;
  5338. for (i = 0; i < mov->nb_streams; i++)
  5339. mov->tracks[i].data_offset += sidx_size;
  5340. return sidx_size;
  5341. }
  5342. static int shift_data(AVFormatContext *s)
  5343. {
  5344. int ret = 0, moov_size;
  5345. MOVMuxContext *mov = s->priv_data;
  5346. int64_t pos, pos_end = avio_tell(s->pb);
  5347. uint8_t *buf, *read_buf[2];
  5348. int read_buf_id = 0;
  5349. int read_size[2];
  5350. AVIOContext *read_pb;
  5351. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  5352. moov_size = compute_sidx_size(s);
  5353. else
  5354. moov_size = compute_moov_size(s);
  5355. if (moov_size < 0)
  5356. return moov_size;
  5357. buf = av_malloc(moov_size * 2);
  5358. if (!buf)
  5359. return AVERROR(ENOMEM);
  5360. read_buf[0] = buf;
  5361. read_buf[1] = buf + moov_size;
  5362. /* Shift the data: the AVIO context of the output can only be used for
  5363. * writing, so we re-open the same output, but for reading. It also avoids
  5364. * a read/seek/write/seek back and forth. */
  5365. avio_flush(s->pb);
  5366. ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
  5367. if (ret < 0) {
  5368. av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
  5369. "the second pass (faststart)\n", s->filename);
  5370. goto end;
  5371. }
  5372. /* mark the end of the shift to up to the last data we wrote, and get ready
  5373. * for writing */
  5374. pos_end = avio_tell(s->pb);
  5375. avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
  5376. /* start reading at where the new moov will be placed */
  5377. avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
  5378. pos = avio_tell(read_pb);
  5379. #define READ_BLOCK do { \
  5380. read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
  5381. read_buf_id ^= 1; \
  5382. } while (0)
  5383. /* shift data by chunk of at most moov_size */
  5384. READ_BLOCK;
  5385. do {
  5386. int n;
  5387. READ_BLOCK;
  5388. n = read_size[read_buf_id];
  5389. if (n <= 0)
  5390. break;
  5391. avio_write(s->pb, read_buf[read_buf_id], n);
  5392. pos += n;
  5393. } while (pos < pos_end);
  5394. ff_format_io_close(s, &read_pb);
  5395. end:
  5396. av_free(buf);
  5397. return ret;
  5398. }
  5399. static int mov_write_trailer(AVFormatContext *s)
  5400. {
  5401. MOVMuxContext *mov = s->priv_data;
  5402. AVIOContext *pb = s->pb;
  5403. int res = 0;
  5404. int i;
  5405. int64_t moov_pos;
  5406. if (mov->need_rewrite_extradata) {
  5407. for (i = 0; i < s->nb_streams; i++) {
  5408. MOVTrack *track = &mov->tracks[i];
  5409. AVCodecParameters *par = track->par;
  5410. track->vos_len = par->extradata_size;
  5411. track->vos_data = av_malloc(track->vos_len);
  5412. if (!track->vos_data)
  5413. return AVERROR(ENOMEM);
  5414. memcpy(track->vos_data, par->extradata, track->vos_len);
  5415. }
  5416. mov->need_rewrite_extradata = 0;
  5417. }
  5418. /*
  5419. * Before actually writing the trailer, make sure that there are no
  5420. * dangling subtitles, that need a terminating sample.
  5421. */
  5422. for (i = 0; i < mov->nb_streams; i++) {
  5423. MOVTrack *trk = &mov->tracks[i];
  5424. if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
  5425. !trk->last_sample_is_subtitle_end) {
  5426. mov_write_subtitle_end_packet(s, i, trk->track_duration);
  5427. trk->last_sample_is_subtitle_end = 1;
  5428. }
  5429. }
  5430. // If there were no chapters when the header was written, but there
  5431. // are chapters now, write them in the trailer. This only works
  5432. // when we are not doing fragments.
  5433. if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  5434. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
  5435. mov->chapter_track = mov->nb_streams++;
  5436. if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  5437. return res;
  5438. }
  5439. }
  5440. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  5441. moov_pos = avio_tell(pb);
  5442. /* Write size of mdat tag */
  5443. if (mov->mdat_size + 8 <= UINT32_MAX) {
  5444. avio_seek(pb, mov->mdat_pos, SEEK_SET);
  5445. avio_wb32(pb, mov->mdat_size + 8);
  5446. } else {
  5447. /* overwrite 'wide' placeholder atom */
  5448. avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
  5449. /* special value: real atom size will be 64 bit value after
  5450. * tag field */
  5451. avio_wb32(pb, 1);
  5452. ffio_wfourcc(pb, "mdat");
  5453. avio_wb64(pb, mov->mdat_size + 16);
  5454. }
  5455. avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
  5456. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  5457. av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
  5458. res = shift_data(s);
  5459. if (res < 0)
  5460. return res;
  5461. avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
  5462. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  5463. return res;
  5464. } else if (mov->reserved_moov_size > 0) {
  5465. int64_t size;
  5466. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  5467. return res;
  5468. size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
  5469. if (size < 8){
  5470. av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
  5471. return AVERROR(EINVAL);
  5472. }
  5473. avio_wb32(pb, size);
  5474. ffio_wfourcc(pb, "free");
  5475. ffio_fill(pb, 0, size - 8);
  5476. avio_seek(pb, moov_pos, SEEK_SET);
  5477. } else {
  5478. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  5479. return res;
  5480. }
  5481. res = 0;
  5482. } else {
  5483. mov_auto_flush_fragment(s, 1);
  5484. for (i = 0; i < mov->nb_streams; i++)
  5485. mov->tracks[i].data_offset = 0;
  5486. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
  5487. int64_t end;
  5488. av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
  5489. res = shift_data(s);
  5490. if (res < 0)
  5491. return res;
  5492. end = avio_tell(pb);
  5493. avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
  5494. mov_write_sidx_tags(pb, mov, -1, 0);
  5495. avio_seek(pb, end, SEEK_SET);
  5496. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
  5497. mov_write_mfra_tag(pb, mov);
  5498. } else {
  5499. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
  5500. mov_write_mfra_tag(pb, mov);
  5501. }
  5502. }
  5503. return res;
  5504. }
  5505. static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
  5506. {
  5507. int ret = 1;
  5508. AVStream *st = s->streams[pkt->stream_index];
  5509. if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
  5510. if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
  5511. ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
  5512. }
  5513. return ret;
  5514. }
  5515. #if CONFIG_MOV_MUXER
  5516. MOV_CLASS(mov)
  5517. AVOutputFormat ff_mov_muxer = {
  5518. .name = "mov",
  5519. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  5520. .extensions = "mov",
  5521. .priv_data_size = sizeof(MOVMuxContext),
  5522. .audio_codec = AV_CODEC_ID_AAC,
  5523. .video_codec = CONFIG_LIBX264_ENCODER ?
  5524. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  5525. .init = mov_init,
  5526. .write_header = mov_write_header,
  5527. .write_packet = mov_write_packet,
  5528. .write_trailer = mov_write_trailer,
  5529. .deinit = mov_free,
  5530. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5531. .codec_tag = (const AVCodecTag* const []){
  5532. ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
  5533. },
  5534. .check_bitstream = mov_check_bitstream,
  5535. .priv_class = &mov_muxer_class,
  5536. };
  5537. #endif
  5538. #if CONFIG_TGP_MUXER
  5539. MOV_CLASS(tgp)
  5540. AVOutputFormat ff_tgp_muxer = {
  5541. .name = "3gp",
  5542. .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
  5543. .extensions = "3gp",
  5544. .priv_data_size = sizeof(MOVMuxContext),
  5545. .audio_codec = AV_CODEC_ID_AMR_NB,
  5546. .video_codec = AV_CODEC_ID_H263,
  5547. .init = mov_init,
  5548. .write_header = mov_write_header,
  5549. .write_packet = mov_write_packet,
  5550. .write_trailer = mov_write_trailer,
  5551. .deinit = mov_free,
  5552. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5553. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  5554. .check_bitstream = mov_check_bitstream,
  5555. .priv_class = &tgp_muxer_class,
  5556. };
  5557. #endif
  5558. #if CONFIG_MP4_MUXER
  5559. MOV_CLASS(mp4)
  5560. AVOutputFormat ff_mp4_muxer = {
  5561. .name = "mp4",
  5562. .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
  5563. .mime_type = "video/mp4",
  5564. .extensions = "mp4",
  5565. .priv_data_size = sizeof(MOVMuxContext),
  5566. .audio_codec = AV_CODEC_ID_AAC,
  5567. .video_codec = CONFIG_LIBX264_ENCODER ?
  5568. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  5569. .init = mov_init,
  5570. .write_header = mov_write_header,
  5571. .write_packet = mov_write_packet,
  5572. .write_trailer = mov_write_trailer,
  5573. .deinit = mov_free,
  5574. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5575. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  5576. .check_bitstream = mov_check_bitstream,
  5577. .priv_class = &mp4_muxer_class,
  5578. };
  5579. #endif
  5580. #if CONFIG_PSP_MUXER
  5581. MOV_CLASS(psp)
  5582. AVOutputFormat ff_psp_muxer = {
  5583. .name = "psp",
  5584. .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
  5585. .extensions = "mp4,psp",
  5586. .priv_data_size = sizeof(MOVMuxContext),
  5587. .audio_codec = AV_CODEC_ID_AAC,
  5588. .video_codec = CONFIG_LIBX264_ENCODER ?
  5589. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  5590. .init = mov_init,
  5591. .write_header = mov_write_header,
  5592. .write_packet = mov_write_packet,
  5593. .write_trailer = mov_write_trailer,
  5594. .deinit = mov_free,
  5595. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5596. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  5597. .check_bitstream = mov_check_bitstream,
  5598. .priv_class = &psp_muxer_class,
  5599. };
  5600. #endif
  5601. #if CONFIG_TG2_MUXER
  5602. MOV_CLASS(tg2)
  5603. AVOutputFormat ff_tg2_muxer = {
  5604. .name = "3g2",
  5605. .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
  5606. .extensions = "3g2",
  5607. .priv_data_size = sizeof(MOVMuxContext),
  5608. .audio_codec = AV_CODEC_ID_AMR_NB,
  5609. .video_codec = AV_CODEC_ID_H263,
  5610. .init = mov_init,
  5611. .write_header = mov_write_header,
  5612. .write_packet = mov_write_packet,
  5613. .write_trailer = mov_write_trailer,
  5614. .deinit = mov_free,
  5615. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5616. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  5617. .check_bitstream = mov_check_bitstream,
  5618. .priv_class = &tg2_muxer_class,
  5619. };
  5620. #endif
  5621. #if CONFIG_IPOD_MUXER
  5622. MOV_CLASS(ipod)
  5623. AVOutputFormat ff_ipod_muxer = {
  5624. .name = "ipod",
  5625. .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
  5626. .mime_type = "video/mp4",
  5627. .extensions = "m4v,m4a",
  5628. .priv_data_size = sizeof(MOVMuxContext),
  5629. .audio_codec = AV_CODEC_ID_AAC,
  5630. .video_codec = AV_CODEC_ID_H264,
  5631. .init = mov_init,
  5632. .write_header = mov_write_header,
  5633. .write_packet = mov_write_packet,
  5634. .write_trailer = mov_write_trailer,
  5635. .deinit = mov_free,
  5636. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5637. .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
  5638. .check_bitstream = mov_check_bitstream,
  5639. .priv_class = &ipod_muxer_class,
  5640. };
  5641. #endif
  5642. #if CONFIG_ISMV_MUXER
  5643. MOV_CLASS(ismv)
  5644. AVOutputFormat ff_ismv_muxer = {
  5645. .name = "ismv",
  5646. .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
  5647. .mime_type = "video/mp4",
  5648. .extensions = "ismv,isma",
  5649. .priv_data_size = sizeof(MOVMuxContext),
  5650. .audio_codec = AV_CODEC_ID_AAC,
  5651. .video_codec = AV_CODEC_ID_H264,
  5652. .init = mov_init,
  5653. .write_header = mov_write_header,
  5654. .write_packet = mov_write_packet,
  5655. .write_trailer = mov_write_trailer,
  5656. .deinit = mov_free,
  5657. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5658. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  5659. .check_bitstream = mov_check_bitstream,
  5660. .priv_class = &ismv_muxer_class,
  5661. };
  5662. #endif
  5663. #if CONFIG_F4V_MUXER
  5664. MOV_CLASS(f4v)
  5665. AVOutputFormat ff_f4v_muxer = {
  5666. .name = "f4v",
  5667. .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
  5668. .mime_type = "application/f4v",
  5669. .extensions = "f4v",
  5670. .priv_data_size = sizeof(MOVMuxContext),
  5671. .audio_codec = AV_CODEC_ID_AAC,
  5672. .video_codec = AV_CODEC_ID_H264,
  5673. .init = mov_init,
  5674. .write_header = mov_write_header,
  5675. .write_packet = mov_write_packet,
  5676. .write_trailer = mov_write_trailer,
  5677. .deinit = mov_free,
  5678. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
  5679. .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
  5680. .check_bitstream = mov_check_bitstream,
  5681. .priv_class = &f4v_muxer_class,
  5682. };
  5683. #endif