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.

6810 lines
247KB

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