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.

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