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.

6803 lines
246KB

  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_SMPTE170M:
  1620. case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
  1621. case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
  1622. default: avio_wb16(pb, 2);
  1623. }
  1624. switch (track->par->color_trc) {
  1625. case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
  1626. case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
  1627. case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
  1628. default: avio_wb16(pb, 2);
  1629. }
  1630. switch (track->par->color_space) {
  1631. case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
  1632. case AVCOL_SPC_BT470BG:
  1633. case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
  1634. case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
  1635. default: avio_wb16(pb, 2);
  1636. }
  1637. if (track->mode == MODE_MP4) {
  1638. int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
  1639. avio_w8(pb, full_range << 7);
  1640. return 19;
  1641. } else {
  1642. return 18;
  1643. }
  1644. }
  1645. static void find_compressor(char * compressor_name, int len, MOVTrack *track)
  1646. {
  1647. AVDictionaryEntry *encoder;
  1648. int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
  1649. || (track->par->width == 1440 && track->par->height == 1080)
  1650. || (track->par->width == 1920 && track->par->height == 1080);
  1651. if (track->mode == MODE_MOV &&
  1652. (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
  1653. av_strlcpy(compressor_name, encoder->value, 32);
  1654. } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
  1655. int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
  1656. AVStream *st = track->st;
  1657. int rate = defined_frame_rate(NULL, st);
  1658. av_strlcatf(compressor_name, len, "XDCAM");
  1659. if (track->par->format == AV_PIX_FMT_YUV422P) {
  1660. av_strlcatf(compressor_name, len, " HD422");
  1661. } else if(track->par->width == 1440) {
  1662. av_strlcatf(compressor_name, len, " HD");
  1663. } else
  1664. av_strlcatf(compressor_name, len, " EX");
  1665. av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
  1666. av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
  1667. }
  1668. }
  1669. static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  1670. {
  1671. int64_t pos = avio_tell(pb);
  1672. char compressor_name[32] = { 0 };
  1673. int avid = 0;
  1674. int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
  1675. || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
  1676. || track->par->codec_id == AV_CODEC_ID_V308
  1677. || track->par->codec_id == AV_CODEC_ID_V408
  1678. || track->par->codec_id == AV_CODEC_ID_V410
  1679. || track->par->codec_id == AV_CODEC_ID_V210);
  1680. avio_wb32(pb, 0); /* size */
  1681. if (mov->encryption_scheme != MOV_ENC_NONE) {
  1682. ffio_wfourcc(pb, "encv");
  1683. } else {
  1684. avio_wl32(pb, track->tag); // store it byteswapped
  1685. }
  1686. avio_wb32(pb, 0); /* Reserved */
  1687. avio_wb16(pb, 0); /* Reserved */
  1688. avio_wb16(pb, 1); /* Data-reference index */
  1689. if (uncompressed_ycbcr) {
  1690. avio_wb16(pb, 2); /* Codec stream version */
  1691. } else {
  1692. avio_wb16(pb, 0); /* Codec stream version */
  1693. }
  1694. avio_wb16(pb, 0); /* Codec stream revision (=0) */
  1695. if (track->mode == MODE_MOV) {
  1696. ffio_wfourcc(pb, "FFMP"); /* Vendor */
  1697. if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
  1698. avio_wb32(pb, 0); /* Temporal Quality */
  1699. avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
  1700. } else {
  1701. avio_wb32(pb, 0x200); /* Temporal Quality = normal */
  1702. avio_wb32(pb, 0x200); /* Spatial Quality = normal */
  1703. }
  1704. } else {
  1705. avio_wb32(pb, 0); /* Reserved */
  1706. avio_wb32(pb, 0); /* Reserved */
  1707. avio_wb32(pb, 0); /* Reserved */
  1708. }
  1709. avio_wb16(pb, track->par->width); /* Video width */
  1710. avio_wb16(pb, track->height); /* Video height */
  1711. avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
  1712. avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
  1713. avio_wb32(pb, 0); /* Data size (= 0) */
  1714. avio_wb16(pb, 1); /* Frame count (= 1) */
  1715. /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
  1716. find_compressor(compressor_name, 32, track);
  1717. avio_w8(pb, strlen(compressor_name));
  1718. avio_write(pb, compressor_name, 31);
  1719. if (track->mode == MODE_MOV &&
  1720. (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
  1721. avio_wb16(pb, 0x18);
  1722. else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
  1723. avio_wb16(pb, track->par->bits_per_coded_sample |
  1724. (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
  1725. else
  1726. avio_wb16(pb, 0x18); /* Reserved */
  1727. if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
  1728. int pal_size = 1 << track->par->bits_per_coded_sample;
  1729. int i;
  1730. avio_wb16(pb, 0); /* Color table ID */
  1731. avio_wb32(pb, 0); /* Color table seed */
  1732. avio_wb16(pb, 0x8000); /* Color table flags */
  1733. avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
  1734. for (i = 0; i < pal_size; i++) {
  1735. uint32_t rgb = track->palette[i];
  1736. uint16_t r = (rgb >> 16) & 0xff;
  1737. uint16_t g = (rgb >> 8) & 0xff;
  1738. uint16_t b = rgb & 0xff;
  1739. avio_wb16(pb, 0);
  1740. avio_wb16(pb, (r << 8) | r);
  1741. avio_wb16(pb, (g << 8) | g);
  1742. avio_wb16(pb, (b << 8) | b);
  1743. }
  1744. } else
  1745. avio_wb16(pb, 0xffff); /* Reserved */
  1746. if (track->tag == MKTAG('m','p','4','v'))
  1747. mov_write_esds_tag(pb, track);
  1748. else if (track->par->codec_id == AV_CODEC_ID_H263)
  1749. mov_write_d263_tag(pb);
  1750. else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
  1751. track->par->codec_id == AV_CODEC_ID_SVQ3) {
  1752. mov_write_extradata_tag(pb, track);
  1753. avio_wb32(pb, 0);
  1754. } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
  1755. mov_write_avid_tag(pb, track);
  1756. avid = 1;
  1757. } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
  1758. mov_write_hvcc_tag(pb, track);
  1759. else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
  1760. mov_write_avcc_tag(pb, track);
  1761. if (track->mode == MODE_IPOD)
  1762. mov_write_uuid_tag_ipod(pb);
  1763. } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
  1764. mov_write_vpcc_tag(mov->fc, pb, track);
  1765. } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
  1766. mov_write_dvc1_tag(pb, track);
  1767. else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
  1768. track->par->codec_id == AV_CODEC_ID_VP6A) {
  1769. /* Don't write any potential extradata here - the cropping
  1770. * is signalled via the normal width/height fields. */
  1771. } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
  1772. if (track->par->codec_tag == MKTAG('R','1','0','k'))
  1773. mov_write_dpxe_tag(pb, track);
  1774. } else if (track->vos_len > 0)
  1775. mov_write_glbl_tag(pb, track);
  1776. if (track->par->codec_id != AV_CODEC_ID_H264 &&
  1777. track->par->codec_id != AV_CODEC_ID_MPEG4 &&
  1778. track->par->codec_id != AV_CODEC_ID_DNXHD) {
  1779. int field_order = track->par->field_order;
  1780. #if FF_API_LAVF_AVCTX
  1781. FF_DISABLE_DEPRECATION_WARNINGS
  1782. if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
  1783. field_order = track->st->codec->field_order;
  1784. FF_ENABLE_DEPRECATION_WARNINGS
  1785. #endif
  1786. if (field_order != AV_FIELD_UNKNOWN)
  1787. mov_write_fiel_tag(pb, track, field_order);
  1788. }
  1789. if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
  1790. if (track->mode == MODE_MOV)
  1791. mov_write_gama_tag(pb, track, mov->gamma);
  1792. else
  1793. av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
  1794. }
  1795. if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
  1796. if (track->mode == MODE_MOV || track->mode == MODE_MP4)
  1797. mov_write_colr_tag(pb, track);
  1798. else
  1799. av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
  1800. }
  1801. if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
  1802. AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
  1803. AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
  1804. if (stereo_3d)
  1805. mov_write_st3d_tag(pb, stereo_3d);
  1806. if (spherical_mapping)
  1807. mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
  1808. }
  1809. if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
  1810. mov_write_pasp_tag(pb, track);
  1811. }
  1812. if (uncompressed_ycbcr){
  1813. mov_write_clap_tag(pb, track);
  1814. }
  1815. if (mov->encryption_scheme != MOV_ENC_NONE) {
  1816. ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
  1817. }
  1818. /* extra padding for avid stsd */
  1819. /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
  1820. if (avid)
  1821. avio_wb32(pb, 0);
  1822. return update_size(pb, pos);
  1823. }
  1824. static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
  1825. {
  1826. int64_t pos = avio_tell(pb);
  1827. avio_wb32(pb, 0); /* size */
  1828. ffio_wfourcc(pb, "rtp ");
  1829. avio_wb32(pb, 0); /* Reserved */
  1830. avio_wb16(pb, 0); /* Reserved */
  1831. avio_wb16(pb, 1); /* Data-reference index */
  1832. avio_wb16(pb, 1); /* Hint track version */
  1833. avio_wb16(pb, 1); /* Highest compatible version */
  1834. avio_wb32(pb, track->max_packet_size); /* Max packet size */
  1835. avio_wb32(pb, 12); /* size */
  1836. ffio_wfourcc(pb, "tims");
  1837. avio_wb32(pb, track->timescale);
  1838. return update_size(pb, pos);
  1839. }
  1840. static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
  1841. {
  1842. uint64_t str_size =strlen(reel_name);
  1843. int64_t pos = avio_tell(pb);
  1844. if (str_size >= UINT16_MAX){
  1845. av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
  1846. avio_wb16(pb, 0);
  1847. return AVERROR(EINVAL);
  1848. }
  1849. avio_wb32(pb, 0); /* size */
  1850. ffio_wfourcc(pb, "name"); /* Data format */
  1851. avio_wb16(pb, str_size); /* string size */
  1852. avio_wb16(pb, track->language); /* langcode */
  1853. avio_write(pb, reel_name, str_size); /* reel name */
  1854. return update_size(pb,pos);
  1855. }
  1856. static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
  1857. {
  1858. int64_t pos = avio_tell(pb);
  1859. #if 1
  1860. int frame_duration;
  1861. int nb_frames;
  1862. AVDictionaryEntry *t = NULL;
  1863. if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
  1864. #if FF_API_LAVF_AVCTX
  1865. FF_DISABLE_DEPRECATION_WARNINGS
  1866. frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
  1867. nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
  1868. FF_ENABLE_DEPRECATION_WARNINGS
  1869. #else
  1870. av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
  1871. return AVERROR(EINVAL);
  1872. #endif
  1873. } else {
  1874. frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
  1875. nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
  1876. }
  1877. if (nb_frames > 255) {
  1878. av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
  1879. return AVERROR(EINVAL);
  1880. }
  1881. avio_wb32(pb, 0); /* size */
  1882. ffio_wfourcc(pb, "tmcd"); /* Data format */
  1883. avio_wb32(pb, 0); /* Reserved */
  1884. avio_wb32(pb, 1); /* Data reference index */
  1885. avio_wb32(pb, 0); /* Flags */
  1886. avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
  1887. avio_wb32(pb, track->timescale); /* Timescale */
  1888. avio_wb32(pb, frame_duration); /* Frame duration */
  1889. avio_w8(pb, nb_frames); /* Number of frames */
  1890. avio_w8(pb, 0); /* Reserved */
  1891. t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
  1892. if (t && utf8len(t->value) && track->mode != MODE_MP4)
  1893. mov_write_source_reference_tag(pb, track, t->value);
  1894. else
  1895. avio_wb16(pb, 0); /* zero size */
  1896. #else
  1897. avio_wb32(pb, 0); /* size */
  1898. ffio_wfourcc(pb, "tmcd"); /* Data format */
  1899. avio_wb32(pb, 0); /* Reserved */
  1900. avio_wb32(pb, 1); /* Data reference index */
  1901. if (track->par->extradata_size)
  1902. avio_write(pb, track->par->extradata, track->par->extradata_size);
  1903. #endif
  1904. return update_size(pb, pos);
  1905. }
  1906. static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
  1907. {
  1908. int64_t pos = avio_tell(pb);
  1909. avio_wb32(pb, 0); /* size */
  1910. ffio_wfourcc(pb, "gpmd");
  1911. avio_wb32(pb, 0); /* Reserved */
  1912. avio_wb16(pb, 0); /* Reserved */
  1913. avio_wb16(pb, 1); /* Data-reference index */
  1914. avio_wb32(pb, 0); /* Reserved */
  1915. return update_size(pb, pos);
  1916. }
  1917. static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  1918. {
  1919. int64_t pos = avio_tell(pb);
  1920. avio_wb32(pb, 0); /* size */
  1921. ffio_wfourcc(pb, "stsd");
  1922. avio_wb32(pb, 0); /* version & flags */
  1923. avio_wb32(pb, 1); /* entry count */
  1924. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
  1925. mov_write_video_tag(pb, mov, track);
  1926. else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  1927. mov_write_audio_tag(s, pb, mov, track);
  1928. else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
  1929. mov_write_subtitle_tag(pb, track);
  1930. else if (track->par->codec_tag == MKTAG('r','t','p',' '))
  1931. mov_write_rtp_tag(pb, track);
  1932. else if (track->par->codec_tag == MKTAG('t','m','c','d'))
  1933. mov_write_tmcd_tag(pb, track);
  1934. else if (track->par->codec_tag == MKTAG('g','p','m','d'))
  1935. mov_write_gpmd_tag(pb, track);
  1936. return update_size(pb, pos);
  1937. }
  1938. static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  1939. {
  1940. MOVMuxContext *mov = s->priv_data;
  1941. MOVStts *ctts_entries;
  1942. uint32_t entries = 0;
  1943. uint32_t atom_size;
  1944. int i;
  1945. ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
  1946. if (!ctts_entries)
  1947. return AVERROR(ENOMEM);
  1948. ctts_entries[0].count = 1;
  1949. ctts_entries[0].duration = track->cluster[0].cts;
  1950. for (i = 1; i < track->entry; i++) {
  1951. if (track->cluster[i].cts == ctts_entries[entries].duration) {
  1952. ctts_entries[entries].count++; /* compress */
  1953. } else {
  1954. entries++;
  1955. ctts_entries[entries].duration = track->cluster[i].cts;
  1956. ctts_entries[entries].count = 1;
  1957. }
  1958. }
  1959. entries++; /* last one */
  1960. atom_size = 16 + (entries * 8);
  1961. avio_wb32(pb, atom_size); /* size */
  1962. ffio_wfourcc(pb, "ctts");
  1963. if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
  1964. avio_w8(pb, 1); /* version */
  1965. else
  1966. avio_w8(pb, 0); /* version */
  1967. avio_wb24(pb, 0); /* flags */
  1968. avio_wb32(pb, entries); /* entry count */
  1969. for (i = 0; i < entries; i++) {
  1970. avio_wb32(pb, ctts_entries[i].count);
  1971. avio_wb32(pb, ctts_entries[i].duration);
  1972. }
  1973. av_free(ctts_entries);
  1974. return atom_size;
  1975. }
  1976. /* Time to sample atom */
  1977. static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
  1978. {
  1979. MOVStts *stts_entries = NULL;
  1980. uint32_t entries = -1;
  1981. uint32_t atom_size;
  1982. int i;
  1983. if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
  1984. stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
  1985. if (!stts_entries)
  1986. return AVERROR(ENOMEM);
  1987. stts_entries[0].count = track->sample_count;
  1988. stts_entries[0].duration = 1;
  1989. entries = 1;
  1990. } else {
  1991. if (track->entry) {
  1992. stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
  1993. if (!stts_entries)
  1994. return AVERROR(ENOMEM);
  1995. }
  1996. for (i = 0; i < track->entry; i++) {
  1997. int duration = get_cluster_duration(track, i);
  1998. if (i && duration == stts_entries[entries].duration) {
  1999. stts_entries[entries].count++; /* compress */
  2000. } else {
  2001. entries++;
  2002. stts_entries[entries].duration = duration;
  2003. stts_entries[entries].count = 1;
  2004. }
  2005. }
  2006. entries++; /* last one */
  2007. }
  2008. atom_size = 16 + (entries * 8);
  2009. avio_wb32(pb, atom_size); /* size */
  2010. ffio_wfourcc(pb, "stts");
  2011. avio_wb32(pb, 0); /* version & flags */
  2012. avio_wb32(pb, entries); /* entry count */
  2013. for (i = 0; i < entries; i++) {
  2014. avio_wb32(pb, stts_entries[i].count);
  2015. avio_wb32(pb, stts_entries[i].duration);
  2016. }
  2017. av_free(stts_entries);
  2018. return atom_size;
  2019. }
  2020. static int mov_write_dref_tag(AVIOContext *pb)
  2021. {
  2022. avio_wb32(pb, 28); /* size */
  2023. ffio_wfourcc(pb, "dref");
  2024. avio_wb32(pb, 0); /* version & flags */
  2025. avio_wb32(pb, 1); /* entry count */
  2026. avio_wb32(pb, 0xc); /* size */
  2027. //FIXME add the alis and rsrc atom
  2028. ffio_wfourcc(pb, "url ");
  2029. avio_wb32(pb, 1); /* version & flags */
  2030. return 28;
  2031. }
  2032. static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
  2033. {
  2034. struct sgpd_entry {
  2035. int count;
  2036. int16_t roll_distance;
  2037. int group_description_index;
  2038. };
  2039. struct sgpd_entry *sgpd_entries = NULL;
  2040. int entries = -1;
  2041. int group = 0;
  2042. int i, j;
  2043. const int OPUS_SEEK_PREROLL_MS = 80;
  2044. int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
  2045. (AVRational){1, 1000},
  2046. (AVRational){1, 48000});
  2047. if (!track->entry)
  2048. return 0;
  2049. sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
  2050. if (!sgpd_entries)
  2051. return AVERROR(ENOMEM);
  2052. av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
  2053. if (track->par->codec_id == AV_CODEC_ID_OPUS) {
  2054. for (i = 0; i < track->entry; i++) {
  2055. int roll_samples_remaining = roll_samples;
  2056. int distance = 0;
  2057. for (j = i - 1; j >= 0; j--) {
  2058. roll_samples_remaining -= get_cluster_duration(track, j);
  2059. distance++;
  2060. if (roll_samples_remaining <= 0)
  2061. break;
  2062. }
  2063. /* We don't have enough preceeding samples to compute a valid
  2064. roll_distance here, so this sample can't be independently
  2065. decoded. */
  2066. if (roll_samples_remaining > 0)
  2067. distance = 0;
  2068. /* Verify distance is a minimum of 2 (60ms) packets and a maximum of
  2069. 32 (2.5ms) packets. */
  2070. av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
  2071. if (i && distance == sgpd_entries[entries].roll_distance) {
  2072. sgpd_entries[entries].count++;
  2073. } else {
  2074. entries++;
  2075. sgpd_entries[entries].count = 1;
  2076. sgpd_entries[entries].roll_distance = distance;
  2077. sgpd_entries[entries].group_description_index = distance ? ++group : 0;
  2078. }
  2079. }
  2080. } else {
  2081. entries++;
  2082. sgpd_entries[entries].count = track->sample_count;
  2083. sgpd_entries[entries].roll_distance = 1;
  2084. sgpd_entries[entries].group_description_index = ++group;
  2085. }
  2086. entries++;
  2087. if (!group) {
  2088. av_free(sgpd_entries);
  2089. return 0;
  2090. }
  2091. /* Write sgpd tag */
  2092. avio_wb32(pb, 24 + (group * 2)); /* size */
  2093. ffio_wfourcc(pb, "sgpd");
  2094. avio_wb32(pb, 1 << 24); /* fullbox */
  2095. ffio_wfourcc(pb, "roll");
  2096. avio_wb32(pb, 2); /* default_length */
  2097. avio_wb32(pb, group); /* entry_count */
  2098. for (i = 0; i < entries; i++) {
  2099. if (sgpd_entries[i].group_description_index) {
  2100. avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
  2101. }
  2102. }
  2103. /* Write sbgp tag */
  2104. avio_wb32(pb, 20 + (entries * 8)); /* size */
  2105. ffio_wfourcc(pb, "sbgp");
  2106. avio_wb32(pb, 0); /* fullbox */
  2107. ffio_wfourcc(pb, "roll");
  2108. avio_wb32(pb, entries); /* entry_count */
  2109. for (i = 0; i < entries; i++) {
  2110. avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
  2111. avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
  2112. }
  2113. av_free(sgpd_entries);
  2114. return 0;
  2115. }
  2116. static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  2117. {
  2118. int64_t pos = avio_tell(pb);
  2119. int ret;
  2120. avio_wb32(pb, 0); /* size */
  2121. ffio_wfourcc(pb, "stbl");
  2122. mov_write_stsd_tag(s, pb, mov, track);
  2123. mov_write_stts_tag(pb, track);
  2124. if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
  2125. track->par->codec_tag == MKTAG('r','t','p',' ')) &&
  2126. track->has_keyframes && track->has_keyframes < track->entry)
  2127. mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
  2128. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
  2129. mov_write_sdtp_tag(pb, track);
  2130. if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
  2131. mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
  2132. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
  2133. track->flags & MOV_TRACK_CTTS && track->entry) {
  2134. if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
  2135. return ret;
  2136. }
  2137. mov_write_stsc_tag(pb, track);
  2138. mov_write_stsz_tag(pb, track);
  2139. mov_write_stco_tag(pb, track);
  2140. if (track->cenc.aes_ctr) {
  2141. ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
  2142. }
  2143. if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
  2144. mov_preroll_write_stbl_atoms(pb, track);
  2145. }
  2146. return update_size(pb, pos);
  2147. }
  2148. static int mov_write_dinf_tag(AVIOContext *pb)
  2149. {
  2150. int64_t pos = avio_tell(pb);
  2151. avio_wb32(pb, 0); /* size */
  2152. ffio_wfourcc(pb, "dinf");
  2153. mov_write_dref_tag(pb);
  2154. return update_size(pb, pos);
  2155. }
  2156. static int mov_write_nmhd_tag(AVIOContext *pb)
  2157. {
  2158. avio_wb32(pb, 12);
  2159. ffio_wfourcc(pb, "nmhd");
  2160. avio_wb32(pb, 0);
  2161. return 12;
  2162. }
  2163. static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
  2164. {
  2165. int64_t pos = avio_tell(pb);
  2166. const char *font = "Lucida Grande";
  2167. avio_wb32(pb, 0); /* size */
  2168. ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
  2169. avio_wb32(pb, 0); /* version & flags */
  2170. avio_wb16(pb, 0); /* text font */
  2171. avio_wb16(pb, 0); /* text face */
  2172. avio_wb16(pb, 12); /* text size */
  2173. avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
  2174. avio_wb16(pb, 0x0000); /* text color (red) */
  2175. avio_wb16(pb, 0x0000); /* text color (green) */
  2176. avio_wb16(pb, 0x0000); /* text color (blue) */
  2177. avio_wb16(pb, 0xffff); /* background color (red) */
  2178. avio_wb16(pb, 0xffff); /* background color (green) */
  2179. avio_wb16(pb, 0xffff); /* background color (blue) */
  2180. avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
  2181. avio_write(pb, font, strlen(font)); /* font name */
  2182. return update_size(pb, pos);
  2183. }
  2184. static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
  2185. {
  2186. int64_t pos = avio_tell(pb);
  2187. avio_wb32(pb, 0); /* size */
  2188. ffio_wfourcc(pb, "gmhd");
  2189. avio_wb32(pb, 0x18); /* gmin size */
  2190. ffio_wfourcc(pb, "gmin");/* generic media info */
  2191. avio_wb32(pb, 0); /* version & flags */
  2192. avio_wb16(pb, 0x40); /* graphics mode = */
  2193. avio_wb16(pb, 0x8000); /* opColor (r?) */
  2194. avio_wb16(pb, 0x8000); /* opColor (g?) */
  2195. avio_wb16(pb, 0x8000); /* opColor (b?) */
  2196. avio_wb16(pb, 0); /* balance */
  2197. avio_wb16(pb, 0); /* reserved */
  2198. /*
  2199. * This special text atom is required for
  2200. * Apple Quicktime chapters. The contents
  2201. * don't appear to be documented, so the
  2202. * bytes are copied verbatim.
  2203. */
  2204. if (track->tag != MKTAG('c','6','0','8')) {
  2205. avio_wb32(pb, 0x2C); /* size */
  2206. ffio_wfourcc(pb, "text");
  2207. avio_wb16(pb, 0x01);
  2208. avio_wb32(pb, 0x00);
  2209. avio_wb32(pb, 0x00);
  2210. avio_wb32(pb, 0x00);
  2211. avio_wb32(pb, 0x01);
  2212. avio_wb32(pb, 0x00);
  2213. avio_wb32(pb, 0x00);
  2214. avio_wb32(pb, 0x00);
  2215. avio_wb32(pb, 0x00004000);
  2216. avio_wb16(pb, 0x0000);
  2217. }
  2218. if (track->par->codec_tag == MKTAG('t','m','c','d')) {
  2219. int64_t tmcd_pos = avio_tell(pb);
  2220. avio_wb32(pb, 0); /* size */
  2221. ffio_wfourcc(pb, "tmcd");
  2222. mov_write_tcmi_tag(pb, track);
  2223. update_size(pb, tmcd_pos);
  2224. } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
  2225. int64_t gpmd_pos = avio_tell(pb);
  2226. avio_wb32(pb, 0); /* size */
  2227. ffio_wfourcc(pb, "gpmd");
  2228. avio_wb32(pb, 0); /* version */
  2229. update_size(pb, gpmd_pos);
  2230. }
  2231. return update_size(pb, pos);
  2232. }
  2233. static int mov_write_smhd_tag(AVIOContext *pb)
  2234. {
  2235. avio_wb32(pb, 16); /* size */
  2236. ffio_wfourcc(pb, "smhd");
  2237. avio_wb32(pb, 0); /* version & flags */
  2238. avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
  2239. avio_wb16(pb, 0); /* reserved */
  2240. return 16;
  2241. }
  2242. static int mov_write_vmhd_tag(AVIOContext *pb)
  2243. {
  2244. avio_wb32(pb, 0x14); /* size (always 0x14) */
  2245. ffio_wfourcc(pb, "vmhd");
  2246. avio_wb32(pb, 0x01); /* version & flags */
  2247. avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
  2248. return 0x14;
  2249. }
  2250. static int is_clcp_track(MOVTrack *track)
  2251. {
  2252. return track->tag == MKTAG('c','7','0','8') ||
  2253. track->tag == MKTAG('c','6','0','8');
  2254. }
  2255. static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  2256. {
  2257. const char *hdlr, *descr = NULL, *hdlr_type = NULL;
  2258. int64_t pos = avio_tell(pb);
  2259. hdlr = "dhlr";
  2260. hdlr_type = "url ";
  2261. descr = "DataHandler";
  2262. if (track) {
  2263. hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
  2264. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  2265. hdlr_type = "vide";
  2266. descr = "VideoHandler";
  2267. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  2268. hdlr_type = "soun";
  2269. descr = "SoundHandler";
  2270. } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  2271. if (is_clcp_track(track)) {
  2272. hdlr_type = "clcp";
  2273. descr = "ClosedCaptionHandler";
  2274. } else {
  2275. if (track->tag == MKTAG('t','x','3','g')) {
  2276. hdlr_type = "sbtl";
  2277. } else if (track->tag == MKTAG('m','p','4','s')) {
  2278. hdlr_type = "subp";
  2279. } else {
  2280. hdlr_type = "text";
  2281. }
  2282. descr = "SubtitleHandler";
  2283. }
  2284. } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
  2285. hdlr_type = "hint";
  2286. descr = "HintHandler";
  2287. } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
  2288. hdlr_type = "tmcd";
  2289. descr = "TimeCodeHandler";
  2290. } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
  2291. hdlr_type = "meta";
  2292. descr = "GoPro MET"; // GoPro Metadata
  2293. } else {
  2294. av_log(s, AV_LOG_WARNING,
  2295. "Unknown hldr_type for %s, writing dummy values\n",
  2296. av_fourcc2str(track->par->codec_tag));
  2297. }
  2298. if (track->st) {
  2299. // hdlr.name is used by some players to identify the content title
  2300. // of the track. So if an alternate handler description is
  2301. // specified, use it.
  2302. AVDictionaryEntry *t;
  2303. t = av_dict_get(track->st->metadata, "handler", NULL, 0);
  2304. if (t && utf8len(t->value))
  2305. descr = t->value;
  2306. }
  2307. }
  2308. avio_wb32(pb, 0); /* size */
  2309. ffio_wfourcc(pb, "hdlr");
  2310. avio_wb32(pb, 0); /* Version & flags */
  2311. avio_write(pb, hdlr, 4); /* handler */
  2312. ffio_wfourcc(pb, hdlr_type); /* handler type */
  2313. avio_wb32(pb, 0); /* reserved */
  2314. avio_wb32(pb, 0); /* reserved */
  2315. avio_wb32(pb, 0); /* reserved */
  2316. if (!track || track->mode == MODE_MOV)
  2317. avio_w8(pb, strlen(descr)); /* pascal string */
  2318. avio_write(pb, descr, strlen(descr)); /* handler description */
  2319. if (track && track->mode != MODE_MOV)
  2320. avio_w8(pb, 0); /* c string */
  2321. return update_size(pb, pos);
  2322. }
  2323. static int mov_write_hmhd_tag(AVIOContext *pb)
  2324. {
  2325. /* This atom must be present, but leaving the values at zero
  2326. * seems harmless. */
  2327. avio_wb32(pb, 28); /* size */
  2328. ffio_wfourcc(pb, "hmhd");
  2329. avio_wb32(pb, 0); /* version, flags */
  2330. avio_wb16(pb, 0); /* maxPDUsize */
  2331. avio_wb16(pb, 0); /* avgPDUsize */
  2332. avio_wb32(pb, 0); /* maxbitrate */
  2333. avio_wb32(pb, 0); /* avgbitrate */
  2334. avio_wb32(pb, 0); /* reserved */
  2335. return 28;
  2336. }
  2337. static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  2338. {
  2339. int64_t pos = avio_tell(pb);
  2340. int ret;
  2341. avio_wb32(pb, 0); /* size */
  2342. ffio_wfourcc(pb, "minf");
  2343. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
  2344. mov_write_vmhd_tag(pb);
  2345. else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  2346. mov_write_smhd_tag(pb);
  2347. else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  2348. if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
  2349. mov_write_gmhd_tag(pb, track);
  2350. } else {
  2351. mov_write_nmhd_tag(pb);
  2352. }
  2353. } else if (track->tag == MKTAG('r','t','p',' ')) {
  2354. mov_write_hmhd_tag(pb);
  2355. } else if (track->tag == MKTAG('t','m','c','d')) {
  2356. if (track->mode != MODE_MOV)
  2357. mov_write_nmhd_tag(pb);
  2358. else
  2359. mov_write_gmhd_tag(pb, track);
  2360. } else if (track->tag == MKTAG('g','p','m','d')) {
  2361. mov_write_gmhd_tag(pb, track);
  2362. }
  2363. if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
  2364. mov_write_hdlr_tag(s, pb, NULL);
  2365. mov_write_dinf_tag(pb);
  2366. if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
  2367. return ret;
  2368. return update_size(pb, pos);
  2369. }
  2370. static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  2371. MOVTrack *track)
  2372. {
  2373. int version = track->track_duration < INT32_MAX ? 0 : 1;
  2374. if (track->mode == MODE_ISM)
  2375. version = 1;
  2376. (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
  2377. ffio_wfourcc(pb, "mdhd");
  2378. avio_w8(pb, version);
  2379. avio_wb24(pb, 0); /* flags */
  2380. if (version == 1) {
  2381. avio_wb64(pb, track->time);
  2382. avio_wb64(pb, track->time);
  2383. } else {
  2384. avio_wb32(pb, track->time); /* creation time */
  2385. avio_wb32(pb, track->time); /* modification time */
  2386. }
  2387. avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
  2388. if (!track->entry && mov->mode == MODE_ISM)
  2389. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  2390. else if (!track->entry)
  2391. (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
  2392. else
  2393. (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
  2394. avio_wb16(pb, track->language); /* language */
  2395. avio_wb16(pb, 0); /* reserved (quality) */
  2396. if (version != 0 && track->mode == MODE_MOV) {
  2397. av_log(NULL, AV_LOG_ERROR,
  2398. "FATAL error, file duration too long for timebase, this file will not be\n"
  2399. "playable with quicktime. Choose a different timebase or a different\n"
  2400. "container format\n");
  2401. }
  2402. return 32;
  2403. }
  2404. static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
  2405. MOVMuxContext *mov, MOVTrack *track)
  2406. {
  2407. int64_t pos = avio_tell(pb);
  2408. int ret;
  2409. avio_wb32(pb, 0); /* size */
  2410. ffio_wfourcc(pb, "mdia");
  2411. mov_write_mdhd_tag(pb, mov, track);
  2412. mov_write_hdlr_tag(s, pb, track);
  2413. if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
  2414. return ret;
  2415. return update_size(pb, pos);
  2416. }
  2417. /* transformation matrix
  2418. |a b u|
  2419. |c d v|
  2420. |tx ty w| */
  2421. static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
  2422. int16_t d, int16_t tx, int16_t ty)
  2423. {
  2424. avio_wb32(pb, a << 16); /* 16.16 format */
  2425. avio_wb32(pb, b << 16); /* 16.16 format */
  2426. avio_wb32(pb, 0); /* u in 2.30 format */
  2427. avio_wb32(pb, c << 16); /* 16.16 format */
  2428. avio_wb32(pb, d << 16); /* 16.16 format */
  2429. avio_wb32(pb, 0); /* v in 2.30 format */
  2430. avio_wb32(pb, tx << 16); /* 16.16 format */
  2431. avio_wb32(pb, ty << 16); /* 16.16 format */
  2432. avio_wb32(pb, 1 << 30); /* w in 2.30 format */
  2433. }
  2434. static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  2435. MOVTrack *track, AVStream *st)
  2436. {
  2437. int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
  2438. track->timescale, AV_ROUND_UP);
  2439. int version = duration < INT32_MAX ? 0 : 1;
  2440. int flags = MOV_TKHD_FLAG_IN_MOVIE;
  2441. int rotation = 0;
  2442. int group = 0;
  2443. uint32_t *display_matrix = NULL;
  2444. int display_matrix_size, i;
  2445. if (st) {
  2446. if (mov->per_stream_grouping)
  2447. group = st->index;
  2448. else
  2449. group = st->codecpar->codec_type;
  2450. display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
  2451. &display_matrix_size);
  2452. if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
  2453. display_matrix = NULL;
  2454. }
  2455. if (track->flags & MOV_TRACK_ENABLED)
  2456. flags |= MOV_TKHD_FLAG_ENABLED;
  2457. if (track->mode == MODE_ISM)
  2458. version = 1;
  2459. (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
  2460. ffio_wfourcc(pb, "tkhd");
  2461. avio_w8(pb, version);
  2462. avio_wb24(pb, flags);
  2463. if (version == 1) {
  2464. avio_wb64(pb, track->time);
  2465. avio_wb64(pb, track->time);
  2466. } else {
  2467. avio_wb32(pb, track->time); /* creation time */
  2468. avio_wb32(pb, track->time); /* modification time */
  2469. }
  2470. avio_wb32(pb, track->track_id); /* track-id */
  2471. avio_wb32(pb, 0); /* reserved */
  2472. if (!track->entry && mov->mode == MODE_ISM)
  2473. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  2474. else if (!track->entry)
  2475. (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
  2476. else
  2477. (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
  2478. avio_wb32(pb, 0); /* reserved */
  2479. avio_wb32(pb, 0); /* reserved */
  2480. avio_wb16(pb, 0); /* layer */
  2481. avio_wb16(pb, group); /* alternate group) */
  2482. /* Volume, only for audio */
  2483. if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  2484. avio_wb16(pb, 0x0100);
  2485. else
  2486. avio_wb16(pb, 0);
  2487. avio_wb16(pb, 0); /* reserved */
  2488. /* Matrix structure */
  2489. #if FF_API_OLD_ROTATE_API
  2490. if (st && st->metadata) {
  2491. AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
  2492. rotation = (rot && rot->value) ? atoi(rot->value) : 0;
  2493. }
  2494. #endif
  2495. if (display_matrix) {
  2496. for (i = 0; i < 9; i++)
  2497. avio_wb32(pb, display_matrix[i]);
  2498. #if FF_API_OLD_ROTATE_API
  2499. } else if (rotation == 90) {
  2500. write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
  2501. } else if (rotation == 180) {
  2502. write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
  2503. } else if (rotation == 270) {
  2504. write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
  2505. #endif
  2506. } else {
  2507. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  2508. }
  2509. /* Track width and height, for visual only */
  2510. if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
  2511. track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
  2512. int64_t track_width_1616;
  2513. if (track->mode == MODE_MOV) {
  2514. track_width_1616 = track->par->width * 0x10000ULL;
  2515. } else {
  2516. track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
  2517. track->par->width * 0x10000LL,
  2518. st->sample_aspect_ratio.den);
  2519. if (!track_width_1616 ||
  2520. track->height != track->par->height ||
  2521. track_width_1616 > UINT32_MAX)
  2522. track_width_1616 = track->par->width * 0x10000ULL;
  2523. }
  2524. if (track_width_1616 > UINT32_MAX) {
  2525. av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
  2526. track_width_1616 = 0;
  2527. }
  2528. avio_wb32(pb, track_width_1616);
  2529. if (track->height > 0xFFFF) {
  2530. av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
  2531. avio_wb32(pb, 0);
  2532. } else
  2533. avio_wb32(pb, track->height * 0x10000U);
  2534. } else {
  2535. avio_wb32(pb, 0);
  2536. avio_wb32(pb, 0);
  2537. }
  2538. return 0x5c;
  2539. }
  2540. static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
  2541. {
  2542. int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
  2543. track->par->sample_aspect_ratio.den);
  2544. int64_t pos = avio_tell(pb);
  2545. avio_wb32(pb, 0); /* size */
  2546. ffio_wfourcc(pb, "tapt");
  2547. avio_wb32(pb, 20);
  2548. ffio_wfourcc(pb, "clef");
  2549. avio_wb32(pb, 0);
  2550. avio_wb32(pb, width << 16);
  2551. avio_wb32(pb, track->par->height << 16);
  2552. avio_wb32(pb, 20);
  2553. ffio_wfourcc(pb, "prof");
  2554. avio_wb32(pb, 0);
  2555. avio_wb32(pb, width << 16);
  2556. avio_wb32(pb, track->par->height << 16);
  2557. avio_wb32(pb, 20);
  2558. ffio_wfourcc(pb, "enof");
  2559. avio_wb32(pb, 0);
  2560. avio_wb32(pb, track->par->width << 16);
  2561. avio_wb32(pb, track->par->height << 16);
  2562. return update_size(pb, pos);
  2563. }
  2564. // This box seems important for the psp playback ... without it the movie seems to hang
  2565. static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
  2566. MOVTrack *track)
  2567. {
  2568. int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
  2569. track->timescale, AV_ROUND_UP);
  2570. int version = duration < INT32_MAX ? 0 : 1;
  2571. int entry_size, entry_count, size;
  2572. int64_t delay, start_ct = track->start_cts;
  2573. int64_t start_dts = track->start_dts;
  2574. if (track->entry) {
  2575. if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
  2576. av_log(mov->fc, AV_LOG_DEBUG,
  2577. "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
  2578. track->cluster[0].dts, track->cluster[0].cts,
  2579. start_dts, start_ct, track->track_id);
  2580. start_dts = track->cluster[0].dts;
  2581. start_ct = track->cluster[0].cts;
  2582. }
  2583. }
  2584. delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
  2585. track->timescale, AV_ROUND_DOWN);
  2586. version |= delay < INT32_MAX ? 0 : 1;
  2587. entry_size = (version == 1) ? 20 : 12;
  2588. entry_count = 1 + (delay > 0);
  2589. size = 24 + entry_count * entry_size;
  2590. /* write the atom data */
  2591. avio_wb32(pb, size);
  2592. ffio_wfourcc(pb, "edts");
  2593. avio_wb32(pb, size - 8);
  2594. ffio_wfourcc(pb, "elst");
  2595. avio_w8(pb, version);
  2596. avio_wb24(pb, 0); /* flags */
  2597. avio_wb32(pb, entry_count);
  2598. if (delay > 0) { /* add an empty edit to delay presentation */
  2599. /* In the positive delay case, the delay includes the cts
  2600. * offset, and the second edit list entry below trims out
  2601. * the same amount from the actual content. This makes sure
  2602. * that the offset last sample is included in the edit
  2603. * list duration as well. */
  2604. if (version == 1) {
  2605. avio_wb64(pb, delay);
  2606. avio_wb64(pb, -1);
  2607. } else {
  2608. avio_wb32(pb, delay);
  2609. avio_wb32(pb, -1);
  2610. }
  2611. avio_wb32(pb, 0x00010000);
  2612. } else {
  2613. /* Avoid accidentally ending up with start_ct = -1 which has got a
  2614. * special meaning. Normally start_ct should end up positive or zero
  2615. * here, but use FFMIN in case dts is a small positive integer
  2616. * rounded to 0 when represented in MOV_TIMESCALE units. */
  2617. av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
  2618. start_ct = -FFMIN(start_dts, 0);
  2619. /* Note, this delay is calculated from the pts of the first sample,
  2620. * ensuring that we don't reduce the duration for cases with
  2621. * dts<0 pts=0. */
  2622. duration += delay;
  2623. }
  2624. /* For fragmented files, we don't know the full length yet. Setting
  2625. * duration to 0 allows us to only specify the offset, including
  2626. * the rest of the content (from all future fragments) without specifying
  2627. * an explicit duration. */
  2628. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  2629. duration = 0;
  2630. /* duration */
  2631. if (version == 1) {
  2632. avio_wb64(pb, duration);
  2633. avio_wb64(pb, start_ct);
  2634. } else {
  2635. avio_wb32(pb, duration);
  2636. avio_wb32(pb, start_ct);
  2637. }
  2638. avio_wb32(pb, 0x00010000);
  2639. return size;
  2640. }
  2641. static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
  2642. {
  2643. avio_wb32(pb, 20); // size
  2644. ffio_wfourcc(pb, "tref");
  2645. avio_wb32(pb, 12); // size (subatom)
  2646. avio_wl32(pb, track->tref_tag);
  2647. avio_wb32(pb, track->tref_id);
  2648. return 20;
  2649. }
  2650. // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
  2651. static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
  2652. {
  2653. avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
  2654. ffio_wfourcc(pb, "uuid");
  2655. ffio_wfourcc(pb, "USMT");
  2656. avio_wb32(pb, 0x21d24fce);
  2657. avio_wb32(pb, 0xbb88695c);
  2658. avio_wb32(pb, 0xfac9c740);
  2659. avio_wb32(pb, 0x1c); // another size here!
  2660. ffio_wfourcc(pb, "MTDT");
  2661. avio_wb32(pb, 0x00010012);
  2662. avio_wb32(pb, 0x0a);
  2663. avio_wb32(pb, 0x55c40000);
  2664. avio_wb32(pb, 0x1);
  2665. avio_wb32(pb, 0x0);
  2666. return 0x34;
  2667. }
  2668. static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
  2669. {
  2670. AVFormatContext *ctx = track->rtp_ctx;
  2671. char buf[1000] = "";
  2672. int len;
  2673. ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
  2674. NULL, NULL, 0, 0, ctx);
  2675. av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
  2676. len = strlen(buf);
  2677. avio_wb32(pb, len + 24);
  2678. ffio_wfourcc(pb, "udta");
  2679. avio_wb32(pb, len + 16);
  2680. ffio_wfourcc(pb, "hnti");
  2681. avio_wb32(pb, len + 8);
  2682. ffio_wfourcc(pb, "sdp ");
  2683. avio_write(pb, buf, len);
  2684. return len + 24;
  2685. }
  2686. static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
  2687. const char *tag, const char *str)
  2688. {
  2689. int64_t pos = avio_tell(pb);
  2690. AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
  2691. if (!t || !utf8len(t->value))
  2692. return 0;
  2693. avio_wb32(pb, 0); /* size */
  2694. ffio_wfourcc(pb, tag); /* type */
  2695. avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
  2696. return update_size(pb, pos);
  2697. }
  2698. static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2699. AVStream *st)
  2700. {
  2701. AVIOContext *pb_buf;
  2702. int ret, size;
  2703. uint8_t *buf;
  2704. if (!st)
  2705. return 0;
  2706. ret = avio_open_dyn_buf(&pb_buf);
  2707. if (ret < 0)
  2708. return ret;
  2709. if (mov->mode & MODE_MP4)
  2710. mov_write_track_metadata(pb_buf, st, "name", "title");
  2711. if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
  2712. avio_wb32(pb, size + 8);
  2713. ffio_wfourcc(pb, "udta");
  2714. avio_write(pb, buf, size);
  2715. }
  2716. av_free(buf);
  2717. return 0;
  2718. }
  2719. static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
  2720. MOVTrack *track, AVStream *st)
  2721. {
  2722. int64_t pos = avio_tell(pb);
  2723. int entry_backup = track->entry;
  2724. int chunk_backup = track->chunkCount;
  2725. int ret;
  2726. /* If we want to have an empty moov, but some samples already have been
  2727. * buffered (delay_moov), pretend that no samples have been written yet. */
  2728. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
  2729. track->chunkCount = track->entry = 0;
  2730. avio_wb32(pb, 0); /* size */
  2731. ffio_wfourcc(pb, "trak");
  2732. mov_write_tkhd_tag(pb, mov, track, st);
  2733. av_assert2(mov->use_editlist >= 0);
  2734. if (track->start_dts != AV_NOPTS_VALUE) {
  2735. if (mov->use_editlist)
  2736. mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
  2737. else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
  2738. av_log(mov->fc, AV_LOG_WARNING,
  2739. "Not writing any edit list even though one would have been required\n");
  2740. }
  2741. if (track->tref_tag)
  2742. mov_write_tref_tag(pb, track);
  2743. if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
  2744. return ret;
  2745. if (track->mode == MODE_PSP)
  2746. mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
  2747. if (track->tag == MKTAG('r','t','p',' '))
  2748. mov_write_udta_sdp(pb, track);
  2749. if (track->mode == MODE_MOV) {
  2750. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  2751. double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
  2752. if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
  2753. mov_write_tapt_tag(pb, track);
  2754. }
  2755. }
  2756. if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
  2757. mov_write_tapt_tag(pb, track);
  2758. }
  2759. }
  2760. mov_write_track_udta_tag(pb, mov, st);
  2761. track->entry = entry_backup;
  2762. track->chunkCount = chunk_backup;
  2763. return update_size(pb, pos);
  2764. }
  2765. static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
  2766. {
  2767. int i, has_audio = 0, has_video = 0;
  2768. int64_t pos = avio_tell(pb);
  2769. int audio_profile = mov->iods_audio_profile;
  2770. int video_profile = mov->iods_video_profile;
  2771. for (i = 0; i < mov->nb_streams; i++) {
  2772. if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  2773. has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
  2774. has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
  2775. }
  2776. }
  2777. if (audio_profile < 0)
  2778. audio_profile = 0xFF - has_audio;
  2779. if (video_profile < 0)
  2780. video_profile = 0xFF - has_video;
  2781. avio_wb32(pb, 0x0); /* size */
  2782. ffio_wfourcc(pb, "iods");
  2783. avio_wb32(pb, 0); /* version & flags */
  2784. put_descr(pb, 0x10, 7);
  2785. avio_wb16(pb, 0x004f);
  2786. avio_w8(pb, 0xff);
  2787. avio_w8(pb, 0xff);
  2788. avio_w8(pb, audio_profile);
  2789. avio_w8(pb, video_profile);
  2790. avio_w8(pb, 0xff);
  2791. return update_size(pb, pos);
  2792. }
  2793. static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
  2794. {
  2795. avio_wb32(pb, 0x20); /* size */
  2796. ffio_wfourcc(pb, "trex");
  2797. avio_wb32(pb, 0); /* version & flags */
  2798. avio_wb32(pb, track->track_id); /* track ID */
  2799. avio_wb32(pb, 1); /* default sample description index */
  2800. avio_wb32(pb, 0); /* default sample duration */
  2801. avio_wb32(pb, 0); /* default sample size */
  2802. avio_wb32(pb, 0); /* default sample flags */
  2803. return 0;
  2804. }
  2805. static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
  2806. {
  2807. int64_t pos = avio_tell(pb);
  2808. int i;
  2809. avio_wb32(pb, 0x0); /* size */
  2810. ffio_wfourcc(pb, "mvex");
  2811. for (i = 0; i < mov->nb_streams; i++)
  2812. mov_write_trex_tag(pb, &mov->tracks[i]);
  2813. return update_size(pb, pos);
  2814. }
  2815. static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  2816. {
  2817. int max_track_id = 1, i;
  2818. int64_t max_track_len = 0;
  2819. int version;
  2820. for (i = 0; i < mov->nb_streams; i++) {
  2821. if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
  2822. int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
  2823. MOV_TIMESCALE,
  2824. mov->tracks[i].timescale,
  2825. AV_ROUND_UP);
  2826. if (max_track_len < max_track_len_temp)
  2827. max_track_len = max_track_len_temp;
  2828. if (max_track_id < mov->tracks[i].track_id)
  2829. max_track_id = mov->tracks[i].track_id;
  2830. }
  2831. }
  2832. /* If using delay_moov, make sure the output is the same as if no
  2833. * samples had been written yet. */
  2834. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  2835. max_track_len = 0;
  2836. max_track_id = 1;
  2837. }
  2838. version = max_track_len < UINT32_MAX ? 0 : 1;
  2839. avio_wb32(pb, version == 1 ? 120 : 108); /* size */
  2840. ffio_wfourcc(pb, "mvhd");
  2841. avio_w8(pb, version);
  2842. avio_wb24(pb, 0); /* flags */
  2843. if (version == 1) {
  2844. avio_wb64(pb, mov->time);
  2845. avio_wb64(pb, mov->time);
  2846. } else {
  2847. avio_wb32(pb, mov->time); /* creation time */
  2848. avio_wb32(pb, mov->time); /* modification time */
  2849. }
  2850. avio_wb32(pb, MOV_TIMESCALE);
  2851. (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
  2852. avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
  2853. avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
  2854. avio_wb16(pb, 0); /* reserved */
  2855. avio_wb32(pb, 0); /* reserved */
  2856. avio_wb32(pb, 0); /* reserved */
  2857. /* Matrix structure */
  2858. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  2859. avio_wb32(pb, 0); /* reserved (preview time) */
  2860. avio_wb32(pb, 0); /* reserved (preview duration) */
  2861. avio_wb32(pb, 0); /* reserved (poster time) */
  2862. avio_wb32(pb, 0); /* reserved (selection time) */
  2863. avio_wb32(pb, 0); /* reserved (selection duration) */
  2864. avio_wb32(pb, 0); /* reserved (current time) */
  2865. avio_wb32(pb, max_track_id + 1); /* Next track id */
  2866. return 0x6c;
  2867. }
  2868. static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
  2869. AVFormatContext *s)
  2870. {
  2871. avio_wb32(pb, 33); /* size */
  2872. ffio_wfourcc(pb, "hdlr");
  2873. avio_wb32(pb, 0);
  2874. avio_wb32(pb, 0);
  2875. ffio_wfourcc(pb, "mdir");
  2876. ffio_wfourcc(pb, "appl");
  2877. avio_wb32(pb, 0);
  2878. avio_wb32(pb, 0);
  2879. avio_w8(pb, 0);
  2880. return 33;
  2881. }
  2882. /* helper function to write a data tag with the specified string as data */
  2883. static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
  2884. {
  2885. if (long_style) {
  2886. int size = 16 + strlen(data);
  2887. avio_wb32(pb, size); /* size */
  2888. ffio_wfourcc(pb, "data");
  2889. avio_wb32(pb, 1);
  2890. avio_wb32(pb, 0);
  2891. avio_write(pb, data, strlen(data));
  2892. return size;
  2893. } else {
  2894. if (!lang)
  2895. lang = ff_mov_iso639_to_lang("und", 1);
  2896. avio_wb16(pb, strlen(data)); /* string length */
  2897. avio_wb16(pb, lang);
  2898. avio_write(pb, data, strlen(data));
  2899. return strlen(data) + 4;
  2900. }
  2901. }
  2902. static int mov_write_string_tag(AVIOContext *pb, const char *name,
  2903. const char *value, int lang, int long_style)
  2904. {
  2905. int size = 0;
  2906. if (value && value[0]) {
  2907. int64_t pos = avio_tell(pb);
  2908. avio_wb32(pb, 0); /* size */
  2909. ffio_wfourcc(pb, name);
  2910. mov_write_string_data_tag(pb, value, lang, long_style);
  2911. size = update_size(pb, pos);
  2912. }
  2913. return size;
  2914. }
  2915. static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
  2916. const char *tag, int *lang)
  2917. {
  2918. int l, len, len2;
  2919. AVDictionaryEntry *t, *t2 = NULL;
  2920. char tag2[16];
  2921. *lang = 0;
  2922. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  2923. return NULL;
  2924. len = strlen(t->key);
  2925. snprintf(tag2, sizeof(tag2), "%s-", tag);
  2926. while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
  2927. len2 = strlen(t2->key);
  2928. if (len2 == len + 4 && !strcmp(t->value, t2->value)
  2929. && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
  2930. *lang = l;
  2931. return t;
  2932. }
  2933. }
  2934. return t;
  2935. }
  2936. static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
  2937. const char *name, const char *tag,
  2938. int long_style)
  2939. {
  2940. int lang;
  2941. AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
  2942. if (!t)
  2943. return 0;
  2944. return mov_write_string_tag(pb, name, t->value, lang, long_style);
  2945. }
  2946. /* iTunes bpm number */
  2947. static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
  2948. {
  2949. AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
  2950. int size = 0, tmpo = t ? atoi(t->value) : 0;
  2951. if (tmpo) {
  2952. size = 26;
  2953. avio_wb32(pb, size);
  2954. ffio_wfourcc(pb, "tmpo");
  2955. avio_wb32(pb, size-8); /* size */
  2956. ffio_wfourcc(pb, "data");
  2957. avio_wb32(pb, 0x15); //type specifier
  2958. avio_wb32(pb, 0);
  2959. avio_wb16(pb, tmpo); // data
  2960. }
  2961. return size;
  2962. }
  2963. /* 3GPP TS 26.244 */
  2964. static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
  2965. {
  2966. int lang;
  2967. int64_t pos = avio_tell(pb);
  2968. double latitude, longitude, altitude;
  2969. int32_t latitude_fix, longitude_fix, altitude_fix;
  2970. AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
  2971. const char *ptr, *place = "";
  2972. char *end;
  2973. static const char *astronomical_body = "earth";
  2974. if (!t)
  2975. return 0;
  2976. ptr = t->value;
  2977. longitude = strtod(ptr, &end);
  2978. if (end == ptr) {
  2979. av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
  2980. return 0;
  2981. }
  2982. ptr = end;
  2983. latitude = strtod(ptr, &end);
  2984. if (end == ptr) {
  2985. av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
  2986. return 0;
  2987. }
  2988. ptr = end;
  2989. altitude = strtod(ptr, &end);
  2990. /* If no altitude was present, the default 0 should be fine */
  2991. if (*end == '/')
  2992. place = end + 1;
  2993. latitude_fix = (int32_t) ((1 << 16) * latitude);
  2994. longitude_fix = (int32_t) ((1 << 16) * longitude);
  2995. altitude_fix = (int32_t) ((1 << 16) * altitude);
  2996. avio_wb32(pb, 0); /* size */
  2997. ffio_wfourcc(pb, "loci"); /* type */
  2998. avio_wb32(pb, 0); /* version + flags */
  2999. avio_wb16(pb, lang);
  3000. avio_write(pb, place, strlen(place) + 1);
  3001. avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
  3002. avio_wb32(pb, latitude_fix);
  3003. avio_wb32(pb, longitude_fix);
  3004. avio_wb32(pb, altitude_fix);
  3005. avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
  3006. avio_w8(pb, 0); /* additional notes, null terminated string */
  3007. return update_size(pb, pos);
  3008. }
  3009. /* iTunes track or disc number */
  3010. static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
  3011. AVFormatContext *s, int disc)
  3012. {
  3013. AVDictionaryEntry *t = av_dict_get(s->metadata,
  3014. disc ? "disc" : "track",
  3015. NULL, 0);
  3016. int size = 0, track = t ? atoi(t->value) : 0;
  3017. if (track) {
  3018. int tracks = 0;
  3019. char *slash = strchr(t->value, '/');
  3020. if (slash)
  3021. tracks = atoi(slash + 1);
  3022. avio_wb32(pb, 32); /* size */
  3023. ffio_wfourcc(pb, disc ? "disk" : "trkn");
  3024. avio_wb32(pb, 24); /* size */
  3025. ffio_wfourcc(pb, "data");
  3026. avio_wb32(pb, 0); // 8 bytes empty
  3027. avio_wb32(pb, 0);
  3028. avio_wb16(pb, 0); // empty
  3029. avio_wb16(pb, track); // track / disc number
  3030. avio_wb16(pb, tracks); // total track / disc number
  3031. avio_wb16(pb, 0); // empty
  3032. size = 32;
  3033. }
  3034. return size;
  3035. }
  3036. static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
  3037. const char *name, const char *tag,
  3038. int len)
  3039. {
  3040. AVDictionaryEntry *t = NULL;
  3041. uint8_t num;
  3042. int size = 24 + len;
  3043. if (len != 1 && len != 4)
  3044. return -1;
  3045. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  3046. return 0;
  3047. num = atoi(t->value);
  3048. avio_wb32(pb, size);
  3049. ffio_wfourcc(pb, name);
  3050. avio_wb32(pb, size - 8);
  3051. ffio_wfourcc(pb, "data");
  3052. avio_wb32(pb, 0x15);
  3053. avio_wb32(pb, 0);
  3054. if (len==4) avio_wb32(pb, num);
  3055. else avio_w8 (pb, num);
  3056. return size;
  3057. }
  3058. /* iTunes meta data list */
  3059. static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
  3060. AVFormatContext *s)
  3061. {
  3062. int64_t pos = avio_tell(pb);
  3063. avio_wb32(pb, 0); /* size */
  3064. ffio_wfourcc(pb, "ilst");
  3065. mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
  3066. mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
  3067. mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
  3068. mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
  3069. mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
  3070. mov_write_string_metadata(s, pb, "\251day", "date" , 1);
  3071. if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
  3072. if (!(s->flags & AVFMT_FLAG_BITEXACT))
  3073. mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
  3074. }
  3075. mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
  3076. mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
  3077. mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
  3078. mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
  3079. mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
  3080. mov_write_string_metadata(s, pb, "desc", "description",1);
  3081. mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
  3082. mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
  3083. mov_write_string_metadata(s, pb, "tven", "episode_id",1);
  3084. mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
  3085. mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
  3086. mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
  3087. mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
  3088. mov_write_int8_metadata (s, pb, "stik", "media_type",1);
  3089. mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
  3090. mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
  3091. mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
  3092. mov_write_trkn_tag(pb, mov, s, 0); // track number
  3093. mov_write_trkn_tag(pb, mov, s, 1); // disc number
  3094. mov_write_tmpo_tag(pb, s);
  3095. return update_size(pb, pos);
  3096. }
  3097. static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
  3098. AVFormatContext *s)
  3099. {
  3100. avio_wb32(pb, 33); /* size */
  3101. ffio_wfourcc(pb, "hdlr");
  3102. avio_wb32(pb, 0);
  3103. avio_wb32(pb, 0);
  3104. ffio_wfourcc(pb, "mdta");
  3105. avio_wb32(pb, 0);
  3106. avio_wb32(pb, 0);
  3107. avio_wb32(pb, 0);
  3108. avio_w8(pb, 0);
  3109. return 33;
  3110. }
  3111. static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
  3112. AVFormatContext *s)
  3113. {
  3114. AVDictionaryEntry *t = NULL;
  3115. int64_t pos = avio_tell(pb);
  3116. int64_t curpos, entry_pos;
  3117. int count = 0;
  3118. avio_wb32(pb, 0); /* size */
  3119. ffio_wfourcc(pb, "keys");
  3120. avio_wb32(pb, 0);
  3121. entry_pos = avio_tell(pb);
  3122. avio_wb32(pb, 0); /* entry count */
  3123. while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
  3124. avio_wb32(pb, strlen(t->key) + 8);
  3125. ffio_wfourcc(pb, "mdta");
  3126. avio_write(pb, t->key, strlen(t->key));
  3127. count += 1;
  3128. }
  3129. curpos = avio_tell(pb);
  3130. avio_seek(pb, entry_pos, SEEK_SET);
  3131. avio_wb32(pb, count); // rewrite entry count
  3132. avio_seek(pb, curpos, SEEK_SET);
  3133. return update_size(pb, pos);
  3134. }
  3135. static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
  3136. AVFormatContext *s)
  3137. {
  3138. AVDictionaryEntry *t = NULL;
  3139. int64_t pos = avio_tell(pb);
  3140. int count = 1; /* keys are 1-index based */
  3141. avio_wb32(pb, 0); /* size */
  3142. ffio_wfourcc(pb, "ilst");
  3143. while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
  3144. int64_t entry_pos = avio_tell(pb);
  3145. avio_wb32(pb, 0); /* size */
  3146. avio_wb32(pb, count); /* key */
  3147. mov_write_string_data_tag(pb, t->value, 0, 1);
  3148. update_size(pb, entry_pos);
  3149. count += 1;
  3150. }
  3151. return update_size(pb, pos);
  3152. }
  3153. /* meta data tags */
  3154. static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
  3155. AVFormatContext *s)
  3156. {
  3157. int size = 0;
  3158. int64_t pos = avio_tell(pb);
  3159. avio_wb32(pb, 0); /* size */
  3160. ffio_wfourcc(pb, "meta");
  3161. avio_wb32(pb, 0);
  3162. if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
  3163. mov_write_mdta_hdlr_tag(pb, mov, s);
  3164. mov_write_mdta_keys_tag(pb, mov, s);
  3165. mov_write_mdta_ilst_tag(pb, mov, s);
  3166. }
  3167. else {
  3168. /* iTunes metadata tag */
  3169. mov_write_itunes_hdlr_tag(pb, mov, s);
  3170. mov_write_ilst_tag(pb, mov, s);
  3171. }
  3172. size = update_size(pb, pos);
  3173. return size;
  3174. }
  3175. static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
  3176. const char *name, const char *key)
  3177. {
  3178. int len;
  3179. AVDictionaryEntry *t;
  3180. if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
  3181. return 0;
  3182. len = strlen(t->value);
  3183. if (len > 0) {
  3184. int size = len + 8;
  3185. avio_wb32(pb, size);
  3186. ffio_wfourcc(pb, name);
  3187. avio_write(pb, t->value, len);
  3188. return size;
  3189. }
  3190. return 0;
  3191. }
  3192. static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
  3193. {
  3194. int val;
  3195. while (*b) {
  3196. GET_UTF8(val, *b++, return -1;)
  3197. avio_wb16(pb, val);
  3198. }
  3199. avio_wb16(pb, 0x00);
  3200. return 0;
  3201. }
  3202. static uint16_t language_code(const char *str)
  3203. {
  3204. return (((str[0] - 0x60) & 0x1F) << 10) +
  3205. (((str[1] - 0x60) & 0x1F) << 5) +
  3206. (( str[2] - 0x60) & 0x1F);
  3207. }
  3208. static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
  3209. const char *tag, const char *str)
  3210. {
  3211. int64_t pos = avio_tell(pb);
  3212. AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
  3213. if (!t || !utf8len(t->value))
  3214. return 0;
  3215. avio_wb32(pb, 0); /* size */
  3216. ffio_wfourcc(pb, tag); /* type */
  3217. avio_wb32(pb, 0); /* version + flags */
  3218. if (!strcmp(tag, "yrrc"))
  3219. avio_wb16(pb, atoi(t->value));
  3220. else {
  3221. avio_wb16(pb, language_code("eng")); /* language */
  3222. avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
  3223. if (!strcmp(tag, "albm") &&
  3224. (t = av_dict_get(s->metadata, "track", NULL, 0)))
  3225. avio_w8(pb, atoi(t->value));
  3226. }
  3227. return update_size(pb, pos);
  3228. }
  3229. static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
  3230. {
  3231. int64_t pos = avio_tell(pb);
  3232. int i, nb_chapters = FFMIN(s->nb_chapters, 255);
  3233. avio_wb32(pb, 0); // size
  3234. ffio_wfourcc(pb, "chpl");
  3235. avio_wb32(pb, 0x01000000); // version + flags
  3236. avio_wb32(pb, 0); // unknown
  3237. avio_w8(pb, nb_chapters);
  3238. for (i = 0; i < nb_chapters; i++) {
  3239. AVChapter *c = s->chapters[i];
  3240. AVDictionaryEntry *t;
  3241. avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
  3242. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  3243. int len = FFMIN(strlen(t->value), 255);
  3244. avio_w8(pb, len);
  3245. avio_write(pb, t->value, len);
  3246. } else
  3247. avio_w8(pb, 0);
  3248. }
  3249. return update_size(pb, pos);
  3250. }
  3251. static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
  3252. AVFormatContext *s)
  3253. {
  3254. AVIOContext *pb_buf;
  3255. int ret, size;
  3256. uint8_t *buf;
  3257. ret = avio_open_dyn_buf(&pb_buf);
  3258. if (ret < 0)
  3259. return ret;
  3260. if (mov->mode & MODE_3GP) {
  3261. mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
  3262. mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
  3263. mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
  3264. mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
  3265. mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
  3266. mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
  3267. mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
  3268. mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
  3269. mov_write_loci_tag(s, pb_buf);
  3270. } 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
  3271. mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
  3272. mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
  3273. mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
  3274. mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
  3275. mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
  3276. mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
  3277. // currently ignored by mov.c
  3278. mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
  3279. // add support for libquicktime, this atom is also actually read by mov.c
  3280. mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
  3281. mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
  3282. mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
  3283. mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
  3284. mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
  3285. mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
  3286. mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
  3287. mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
  3288. } else {
  3289. /* iTunes meta data */
  3290. mov_write_meta_tag(pb_buf, mov, s);
  3291. mov_write_loci_tag(s, pb_buf);
  3292. }
  3293. if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
  3294. mov_write_chpl_tag(pb_buf, s);
  3295. if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
  3296. avio_wb32(pb, size + 8);
  3297. ffio_wfourcc(pb, "udta");
  3298. avio_write(pb, buf, size);
  3299. }
  3300. av_free(buf);
  3301. return 0;
  3302. }
  3303. static void mov_write_psp_udta_tag(AVIOContext *pb,
  3304. const char *str, const char *lang, int type)
  3305. {
  3306. int len = utf8len(str) + 1;
  3307. if (len <= 0)
  3308. return;
  3309. avio_wb16(pb, len * 2 + 10); /* size */
  3310. avio_wb32(pb, type); /* type */
  3311. avio_wb16(pb, language_code(lang)); /* language */
  3312. avio_wb16(pb, 0x01); /* ? */
  3313. ascii_to_wc(pb, str);
  3314. }
  3315. static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
  3316. {
  3317. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  3318. int64_t pos, pos2;
  3319. if (title) {
  3320. pos = avio_tell(pb);
  3321. avio_wb32(pb, 0); /* size placeholder*/
  3322. ffio_wfourcc(pb, "uuid");
  3323. ffio_wfourcc(pb, "USMT");
  3324. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  3325. avio_wb32(pb, 0xbb88695c);
  3326. avio_wb32(pb, 0xfac9c740);
  3327. pos2 = avio_tell(pb);
  3328. avio_wb32(pb, 0); /* size placeholder*/
  3329. ffio_wfourcc(pb, "MTDT");
  3330. avio_wb16(pb, 4);
  3331. // ?
  3332. avio_wb16(pb, 0x0C); /* size */
  3333. avio_wb32(pb, 0x0B); /* type */
  3334. avio_wb16(pb, language_code("und")); /* language */
  3335. avio_wb16(pb, 0x0); /* ? */
  3336. avio_wb16(pb, 0x021C); /* data */
  3337. if (!(s->flags & AVFMT_FLAG_BITEXACT))
  3338. mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
  3339. mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
  3340. mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
  3341. update_size(pb, pos2);
  3342. return update_size(pb, pos);
  3343. }
  3344. return 0;
  3345. }
  3346. static void build_chunks(MOVTrack *trk)
  3347. {
  3348. int i;
  3349. MOVIentry *chunk = &trk->cluster[0];
  3350. uint64_t chunkSize = chunk->size;
  3351. chunk->chunkNum = 1;
  3352. if (trk->chunkCount)
  3353. return;
  3354. trk->chunkCount = 1;
  3355. for (i = 1; i<trk->entry; i++){
  3356. if (chunk->pos + chunkSize == trk->cluster[i].pos &&
  3357. chunkSize + trk->cluster[i].size < (1<<20)){
  3358. chunkSize += trk->cluster[i].size;
  3359. chunk->samples_in_chunk += trk->cluster[i].entries;
  3360. } else {
  3361. trk->cluster[i].chunkNum = chunk->chunkNum+1;
  3362. chunk=&trk->cluster[i];
  3363. chunkSize = chunk->size;
  3364. trk->chunkCount++;
  3365. }
  3366. }
  3367. }
  3368. /**
  3369. * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
  3370. * the stream ids are used as track ids.
  3371. *
  3372. * This assumes mov->tracks and s->streams are in the same order and
  3373. * there are no gaps in either of them (so mov->tracks[n] refers to
  3374. * s->streams[n]).
  3375. *
  3376. * As an exception, there can be more entries in
  3377. * s->streams than in mov->tracks, in which case new track ids are
  3378. * generated (starting after the largest found stream id).
  3379. */
  3380. static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
  3381. {
  3382. int i;
  3383. if (mov->track_ids_ok)
  3384. return 0;
  3385. if (mov->use_stream_ids_as_track_ids) {
  3386. int next_generated_track_id = 0;
  3387. for (i = 0; i < s->nb_streams; i++) {
  3388. if (s->streams[i]->id > next_generated_track_id)
  3389. next_generated_track_id = s->streams[i]->id;
  3390. }
  3391. for (i = 0; i < mov->nb_streams; i++) {
  3392. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3393. continue;
  3394. mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
  3395. }
  3396. } else {
  3397. for (i = 0; i < mov->nb_streams; i++) {
  3398. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3399. continue;
  3400. mov->tracks[i].track_id = i + 1;
  3401. }
  3402. }
  3403. mov->track_ids_ok = 1;
  3404. return 0;
  3405. }
  3406. static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
  3407. AVFormatContext *s)
  3408. {
  3409. int i;
  3410. int64_t pos = avio_tell(pb);
  3411. avio_wb32(pb, 0); /* size placeholder*/
  3412. ffio_wfourcc(pb, "moov");
  3413. mov_setup_track_ids(mov, s);
  3414. for (i = 0; i < mov->nb_streams; i++) {
  3415. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3416. continue;
  3417. mov->tracks[i].time = mov->time;
  3418. if (mov->tracks[i].entry)
  3419. build_chunks(&mov->tracks[i]);
  3420. }
  3421. if (mov->chapter_track)
  3422. for (i = 0; i < s->nb_streams; i++) {
  3423. mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
  3424. mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
  3425. }
  3426. for (i = 0; i < mov->nb_streams; i++) {
  3427. MOVTrack *track = &mov->tracks[i];
  3428. if (track->tag == MKTAG('r','t','p',' ')) {
  3429. track->tref_tag = MKTAG('h','i','n','t');
  3430. track->tref_id = mov->tracks[track->src_track].track_id;
  3431. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  3432. int * fallback, size;
  3433. fallback = (int*)av_stream_get_side_data(track->st,
  3434. AV_PKT_DATA_FALLBACK_TRACK,
  3435. &size);
  3436. if (fallback != NULL && size == sizeof(int)) {
  3437. if (*fallback >= 0 && *fallback < mov->nb_streams) {
  3438. track->tref_tag = MKTAG('f','a','l','l');
  3439. track->tref_id = mov->tracks[*fallback].track_id;
  3440. }
  3441. }
  3442. }
  3443. }
  3444. for (i = 0; i < mov->nb_streams; i++) {
  3445. if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
  3446. int src_trk = mov->tracks[i].src_track;
  3447. mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
  3448. mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
  3449. //src_trk may have a different timescale than the tmcd track
  3450. mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
  3451. mov->tracks[i].timescale,
  3452. mov->tracks[src_trk].timescale);
  3453. }
  3454. }
  3455. mov_write_mvhd_tag(pb, mov);
  3456. if (mov->mode != MODE_MOV && !mov->iods_skip)
  3457. mov_write_iods_tag(pb, mov);
  3458. for (i = 0; i < mov->nb_streams; i++) {
  3459. if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
  3460. int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
  3461. if (ret < 0)
  3462. return ret;
  3463. }
  3464. }
  3465. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  3466. mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
  3467. if (mov->mode == MODE_PSP)
  3468. mov_write_uuidusmt_tag(pb, s);
  3469. else
  3470. mov_write_udta_tag(pb, mov, s);
  3471. return update_size(pb, pos);
  3472. }
  3473. static void param_write_int(AVIOContext *pb, const char *name, int value)
  3474. {
  3475. avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
  3476. }
  3477. static void param_write_string(AVIOContext *pb, const char *name, const char *value)
  3478. {
  3479. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
  3480. }
  3481. static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
  3482. {
  3483. char buf[150];
  3484. len = FFMIN(sizeof(buf) / 2 - 1, len);
  3485. ff_data_to_hex(buf, value, len, 0);
  3486. buf[2 * len] = '\0';
  3487. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
  3488. }
  3489. static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
  3490. {
  3491. int64_t pos = avio_tell(pb);
  3492. int i;
  3493. int64_t manifest_bit_rate = 0;
  3494. AVCPBProperties *props = NULL;
  3495. static const uint8_t uuid[] = {
  3496. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  3497. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  3498. };
  3499. avio_wb32(pb, 0);
  3500. ffio_wfourcc(pb, "uuid");
  3501. avio_write(pb, uuid, sizeof(uuid));
  3502. avio_wb32(pb, 0);
  3503. avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  3504. avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
  3505. avio_printf(pb, "<head>\n");
  3506. if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
  3507. avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
  3508. LIBAVFORMAT_IDENT);
  3509. avio_printf(pb, "</head>\n");
  3510. avio_printf(pb, "<body>\n");
  3511. avio_printf(pb, "<switch>\n");
  3512. mov_setup_track_ids(mov, s);
  3513. for (i = 0; i < mov->nb_streams; i++) {
  3514. MOVTrack *track = &mov->tracks[i];
  3515. const char *type;
  3516. int track_id = track->track_id;
  3517. char track_name_buf[32] = { 0 };
  3518. AVStream *st = track->st;
  3519. AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
  3520. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  3521. type = "video";
  3522. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  3523. type = "audio";
  3524. } else {
  3525. continue;
  3526. }
  3527. props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
  3528. if (track->par->bit_rate) {
  3529. manifest_bit_rate = track->par->bit_rate;
  3530. } else if (props) {
  3531. manifest_bit_rate = props->max_bitrate;
  3532. }
  3533. avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
  3534. manifest_bit_rate);
  3535. param_write_int(pb, "systemBitrate", manifest_bit_rate);
  3536. param_write_int(pb, "trackID", track_id);
  3537. param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
  3538. /* Build track name piece by piece: */
  3539. /* 1. track type */
  3540. av_strlcat(track_name_buf, type, sizeof(track_name_buf));
  3541. /* 2. track language, if available */
  3542. if (lang)
  3543. av_strlcatf(track_name_buf, sizeof(track_name_buf),
  3544. "_%s", lang->value);
  3545. /* 3. special type suffix */
  3546. /* "_cc" = closed captions, "_ad" = audio_description */
  3547. if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
  3548. av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
  3549. else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
  3550. av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
  3551. param_write_string(pb, "trackName", track_name_buf);
  3552. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  3553. if (track->par->codec_id == AV_CODEC_ID_H264) {
  3554. uint8_t *ptr;
  3555. int size = track->par->extradata_size;
  3556. if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
  3557. &size)) {
  3558. param_write_hex(pb, "CodecPrivateData",
  3559. ptr ? ptr : track->par->extradata,
  3560. size);
  3561. av_free(ptr);
  3562. }
  3563. param_write_string(pb, "FourCC", "H264");
  3564. } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
  3565. param_write_string(pb, "FourCC", "WVC1");
  3566. param_write_hex(pb, "CodecPrivateData", track->par->extradata,
  3567. track->par->extradata_size);
  3568. }
  3569. param_write_int(pb, "MaxWidth", track->par->width);
  3570. param_write_int(pb, "MaxHeight", track->par->height);
  3571. param_write_int(pb, "DisplayWidth", track->par->width);
  3572. param_write_int(pb, "DisplayHeight", track->par->height);
  3573. } else {
  3574. if (track->par->codec_id == AV_CODEC_ID_AAC) {
  3575. switch (track->par->profile)
  3576. {
  3577. case FF_PROFILE_AAC_HE_V2:
  3578. param_write_string(pb, "FourCC", "AACP");
  3579. break;
  3580. case FF_PROFILE_AAC_HE:
  3581. param_write_string(pb, "FourCC", "AACH");
  3582. break;
  3583. default:
  3584. param_write_string(pb, "FourCC", "AACL");
  3585. }
  3586. } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
  3587. param_write_string(pb, "FourCC", "WMAP");
  3588. }
  3589. param_write_hex(pb, "CodecPrivateData", track->par->extradata,
  3590. track->par->extradata_size);
  3591. param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
  3592. track->par->codec_id));
  3593. param_write_int(pb, "Channels", track->par->channels);
  3594. param_write_int(pb, "SamplingRate", track->par->sample_rate);
  3595. param_write_int(pb, "BitsPerSample", 16);
  3596. param_write_int(pb, "PacketSize", track->par->block_align ?
  3597. track->par->block_align : 4);
  3598. }
  3599. avio_printf(pb, "</%s>\n", type);
  3600. }
  3601. avio_printf(pb, "</switch>\n");
  3602. avio_printf(pb, "</body>\n");
  3603. avio_printf(pb, "</smil>\n");
  3604. return update_size(pb, pos);
  3605. }
  3606. static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  3607. {
  3608. avio_wb32(pb, 16);
  3609. ffio_wfourcc(pb, "mfhd");
  3610. avio_wb32(pb, 0);
  3611. avio_wb32(pb, mov->fragments);
  3612. return 0;
  3613. }
  3614. static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
  3615. {
  3616. return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
  3617. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
  3618. }
  3619. static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  3620. MOVTrack *track, int64_t moof_offset)
  3621. {
  3622. int64_t pos = avio_tell(pb);
  3623. uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  3624. MOV_TFHD_BASE_DATA_OFFSET;
  3625. if (!track->entry) {
  3626. flags |= MOV_TFHD_DURATION_IS_EMPTY;
  3627. } else {
  3628. flags |= MOV_TFHD_DEFAULT_FLAGS;
  3629. }
  3630. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
  3631. flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
  3632. if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
  3633. flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
  3634. flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
  3635. }
  3636. /* Don't set a default sample size, the silverlight player refuses
  3637. * to play files with that set. Don't set a default sample duration,
  3638. * WMP freaks out if it is set. Don't set a base data offset, PIFF
  3639. * file format says it MUST NOT be set. */
  3640. if (track->mode == MODE_ISM)
  3641. flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  3642. MOV_TFHD_BASE_DATA_OFFSET);
  3643. avio_wb32(pb, 0); /* size placeholder */
  3644. ffio_wfourcc(pb, "tfhd");
  3645. avio_w8(pb, 0); /* version */
  3646. avio_wb24(pb, flags);
  3647. avio_wb32(pb, track->track_id); /* track-id */
  3648. if (flags & MOV_TFHD_BASE_DATA_OFFSET)
  3649. avio_wb64(pb, moof_offset);
  3650. if (flags & MOV_TFHD_DEFAULT_DURATION) {
  3651. track->default_duration = get_cluster_duration(track, 0);
  3652. avio_wb32(pb, track->default_duration);
  3653. }
  3654. if (flags & MOV_TFHD_DEFAULT_SIZE) {
  3655. track->default_size = track->entry ? track->cluster[0].size : 1;
  3656. avio_wb32(pb, track->default_size);
  3657. } else
  3658. track->default_size = -1;
  3659. if (flags & MOV_TFHD_DEFAULT_FLAGS) {
  3660. /* Set the default flags based on the second sample, if available.
  3661. * If the first sample is different, that can be signaled via a separate field. */
  3662. if (track->entry > 1)
  3663. track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
  3664. else
  3665. track->default_sample_flags =
  3666. track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
  3667. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
  3668. MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
  3669. avio_wb32(pb, track->default_sample_flags);
  3670. }
  3671. return update_size(pb, pos);
  3672. }
  3673. static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
  3674. MOVTrack *track, int moof_size,
  3675. int first, int end)
  3676. {
  3677. int64_t pos = avio_tell(pb);
  3678. uint32_t flags = MOV_TRUN_DATA_OFFSET;
  3679. int i;
  3680. for (i = first; i < end; i++) {
  3681. if (get_cluster_duration(track, i) != track->default_duration)
  3682. flags |= MOV_TRUN_SAMPLE_DURATION;
  3683. if (track->cluster[i].size != track->default_size)
  3684. flags |= MOV_TRUN_SAMPLE_SIZE;
  3685. if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
  3686. flags |= MOV_TRUN_SAMPLE_FLAGS;
  3687. }
  3688. if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
  3689. get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
  3690. flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
  3691. if (track->flags & MOV_TRACK_CTTS)
  3692. flags |= MOV_TRUN_SAMPLE_CTS;
  3693. avio_wb32(pb, 0); /* size placeholder */
  3694. ffio_wfourcc(pb, "trun");
  3695. if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
  3696. avio_w8(pb, 1); /* version */
  3697. else
  3698. avio_w8(pb, 0); /* version */
  3699. avio_wb24(pb, flags);
  3700. avio_wb32(pb, end - first); /* sample count */
  3701. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
  3702. !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
  3703. !mov->first_trun)
  3704. avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
  3705. else
  3706. avio_wb32(pb, moof_size + 8 + track->data_offset +
  3707. track->cluster[first].pos); /* data offset */
  3708. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
  3709. avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
  3710. for (i = first; i < end; i++) {
  3711. if (flags & MOV_TRUN_SAMPLE_DURATION)
  3712. avio_wb32(pb, get_cluster_duration(track, i));
  3713. if (flags & MOV_TRUN_SAMPLE_SIZE)
  3714. avio_wb32(pb, track->cluster[i].size);
  3715. if (flags & MOV_TRUN_SAMPLE_FLAGS)
  3716. avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
  3717. if (flags & MOV_TRUN_SAMPLE_CTS)
  3718. avio_wb32(pb, track->cluster[i].cts);
  3719. }
  3720. mov->first_trun = 0;
  3721. return update_size(pb, pos);
  3722. }
  3723. static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
  3724. {
  3725. int64_t pos = avio_tell(pb);
  3726. static const uint8_t uuid[] = {
  3727. 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
  3728. 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
  3729. };
  3730. avio_wb32(pb, 0); /* size placeholder */
  3731. ffio_wfourcc(pb, "uuid");
  3732. avio_write(pb, uuid, sizeof(uuid));
  3733. avio_w8(pb, 1);
  3734. avio_wb24(pb, 0);
  3735. avio_wb64(pb, track->start_dts + track->frag_start +
  3736. track->cluster[0].cts);
  3737. avio_wb64(pb, track->end_pts -
  3738. (track->cluster[0].dts + track->cluster[0].cts));
  3739. return update_size(pb, pos);
  3740. }
  3741. static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
  3742. MOVTrack *track, int entry)
  3743. {
  3744. int n = track->nb_frag_info - 1 - entry, i;
  3745. int size = 8 + 16 + 4 + 1 + 16*n;
  3746. static const uint8_t uuid[] = {
  3747. 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
  3748. 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
  3749. };
  3750. if (entry < 0)
  3751. return 0;
  3752. avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
  3753. avio_wb32(pb, size);
  3754. ffio_wfourcc(pb, "uuid");
  3755. avio_write(pb, uuid, sizeof(uuid));
  3756. avio_w8(pb, 1);
  3757. avio_wb24(pb, 0);
  3758. avio_w8(pb, n);
  3759. for (i = 0; i < n; i++) {
  3760. int index = entry + 1 + i;
  3761. avio_wb64(pb, track->frag_info[index].time);
  3762. avio_wb64(pb, track->frag_info[index].duration);
  3763. }
  3764. if (n < mov->ism_lookahead) {
  3765. int free_size = 16 * (mov->ism_lookahead - n);
  3766. avio_wb32(pb, free_size);
  3767. ffio_wfourcc(pb, "free");
  3768. ffio_fill(pb, 0, free_size - 8);
  3769. }
  3770. return 0;
  3771. }
  3772. static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
  3773. MOVTrack *track)
  3774. {
  3775. int64_t pos = avio_tell(pb);
  3776. int i;
  3777. for (i = 0; i < mov->ism_lookahead; i++) {
  3778. /* Update the tfrf tag for the last ism_lookahead fragments,
  3779. * nb_frag_info - 1 is the next fragment to be written. */
  3780. mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
  3781. }
  3782. avio_seek(pb, pos, SEEK_SET);
  3783. return 0;
  3784. }
  3785. static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
  3786. int size)
  3787. {
  3788. int i;
  3789. for (i = 0; i < mov->nb_streams; i++) {
  3790. MOVTrack *track = &mov->tracks[i];
  3791. MOVFragmentInfo *info;
  3792. if ((tracks >= 0 && i != tracks) || !track->entry)
  3793. continue;
  3794. track->nb_frag_info++;
  3795. if (track->nb_frag_info >= track->frag_info_capacity) {
  3796. unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
  3797. if (av_reallocp_array(&track->frag_info,
  3798. new_capacity,
  3799. sizeof(*track->frag_info)))
  3800. return AVERROR(ENOMEM);
  3801. track->frag_info_capacity = new_capacity;
  3802. }
  3803. info = &track->frag_info[track->nb_frag_info - 1];
  3804. info->offset = avio_tell(pb);
  3805. info->size = size;
  3806. // Try to recreate the original pts for the first packet
  3807. // from the fields we have stored
  3808. info->time = track->start_dts + track->frag_start +
  3809. track->cluster[0].cts;
  3810. info->duration = track->end_pts -
  3811. (track->cluster[0].dts + track->cluster[0].cts);
  3812. // If the pts is less than zero, we will have trimmed
  3813. // away parts of the media track using an edit list,
  3814. // and the corresponding start presentation time is zero.
  3815. if (info->time < 0) {
  3816. info->duration += info->time;
  3817. info->time = 0;
  3818. }
  3819. info->tfrf_offset = 0;
  3820. mov_write_tfrf_tags(pb, mov, track);
  3821. }
  3822. return 0;
  3823. }
  3824. static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
  3825. {
  3826. int i;
  3827. for (i = 0; i < mov->nb_streams; i++) {
  3828. MOVTrack *track = &mov->tracks[i];
  3829. if ((tracks >= 0 && i != tracks) || !track->entry)
  3830. continue;
  3831. if (track->nb_frag_info > max) {
  3832. memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
  3833. track->nb_frag_info = max;
  3834. }
  3835. }
  3836. }
  3837. static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
  3838. {
  3839. int64_t pos = avio_tell(pb);
  3840. avio_wb32(pb, 0); /* size */
  3841. ffio_wfourcc(pb, "tfdt");
  3842. avio_w8(pb, 1); /* version */
  3843. avio_wb24(pb, 0);
  3844. avio_wb64(pb, track->frag_start);
  3845. return update_size(pb, pos);
  3846. }
  3847. static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
  3848. MOVTrack *track, int64_t moof_offset,
  3849. int moof_size)
  3850. {
  3851. int64_t pos = avio_tell(pb);
  3852. int i, start = 0;
  3853. avio_wb32(pb, 0); /* size placeholder */
  3854. ffio_wfourcc(pb, "traf");
  3855. mov_write_tfhd_tag(pb, mov, track, moof_offset);
  3856. if (mov->mode != MODE_ISM)
  3857. mov_write_tfdt_tag(pb, track);
  3858. for (i = 1; i < track->entry; i++) {
  3859. if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
  3860. mov_write_trun_tag(pb, mov, track, moof_size, start, i);
  3861. start = i;
  3862. }
  3863. }
  3864. mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
  3865. if (mov->mode == MODE_ISM) {
  3866. mov_write_tfxd_tag(pb, track);
  3867. if (mov->ism_lookahead) {
  3868. int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
  3869. if (track->nb_frag_info > 0) {
  3870. MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
  3871. if (!info->tfrf_offset)
  3872. info->tfrf_offset = avio_tell(pb);
  3873. }
  3874. avio_wb32(pb, 8 + size);
  3875. ffio_wfourcc(pb, "free");
  3876. for (i = 0; i < size; i++)
  3877. avio_w8(pb, 0);
  3878. }
  3879. }
  3880. return update_size(pb, pos);
  3881. }
  3882. static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
  3883. int tracks, int moof_size)
  3884. {
  3885. int64_t pos = avio_tell(pb);
  3886. int i;
  3887. avio_wb32(pb, 0); /* size placeholder */
  3888. ffio_wfourcc(pb, "moof");
  3889. mov->first_trun = 1;
  3890. mov_write_mfhd_tag(pb, mov);
  3891. for (i = 0; i < mov->nb_streams; i++) {
  3892. MOVTrack *track = &mov->tracks[i];
  3893. if (tracks >= 0 && i != tracks)
  3894. continue;
  3895. if (!track->entry)
  3896. continue;
  3897. mov_write_traf_tag(pb, mov, track, pos, moof_size);
  3898. }
  3899. return update_size(pb, pos);
  3900. }
  3901. static int mov_write_sidx_tag(AVIOContext *pb,
  3902. MOVTrack *track, int ref_size, int total_sidx_size)
  3903. {
  3904. int64_t pos = avio_tell(pb), offset_pos, end_pos;
  3905. int64_t presentation_time, duration, offset;
  3906. int starts_with_SAP, i, entries;
  3907. if (track->entry) {
  3908. entries = 1;
  3909. presentation_time = track->start_dts + track->frag_start +
  3910. track->cluster[0].cts;
  3911. duration = track->end_pts -
  3912. (track->cluster[0].dts + track->cluster[0].cts);
  3913. starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
  3914. // pts<0 should be cut away using edts
  3915. if (presentation_time < 0) {
  3916. duration += presentation_time;
  3917. presentation_time = 0;
  3918. }
  3919. } else {
  3920. entries = track->nb_frag_info;
  3921. if (entries <= 0)
  3922. return 0;
  3923. presentation_time = track->frag_info[0].time;
  3924. }
  3925. avio_wb32(pb, 0); /* size */
  3926. ffio_wfourcc(pb, "sidx");
  3927. avio_w8(pb, 1); /* version */
  3928. avio_wb24(pb, 0);
  3929. avio_wb32(pb, track->track_id); /* reference_ID */
  3930. avio_wb32(pb, track->timescale); /* timescale */
  3931. avio_wb64(pb, presentation_time); /* earliest_presentation_time */
  3932. offset_pos = avio_tell(pb);
  3933. avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
  3934. avio_wb16(pb, 0); /* reserved */
  3935. avio_wb16(pb, entries); /* reference_count */
  3936. for (i = 0; i < entries; i++) {
  3937. if (!track->entry) {
  3938. if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
  3939. av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
  3940. }
  3941. duration = track->frag_info[i].duration;
  3942. ref_size = track->frag_info[i].size;
  3943. starts_with_SAP = 1;
  3944. }
  3945. avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
  3946. avio_wb32(pb, duration); /* subsegment_duration */
  3947. avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
  3948. }
  3949. end_pos = avio_tell(pb);
  3950. offset = pos + total_sidx_size - end_pos;
  3951. avio_seek(pb, offset_pos, SEEK_SET);
  3952. avio_wb64(pb, offset);
  3953. avio_seek(pb, end_pos, SEEK_SET);
  3954. return update_size(pb, pos);
  3955. }
  3956. static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
  3957. int tracks, int ref_size)
  3958. {
  3959. int i, round, ret;
  3960. AVIOContext *avio_buf;
  3961. int total_size = 0;
  3962. for (round = 0; round < 2; round++) {
  3963. // First run one round to calculate the total size of all
  3964. // sidx atoms.
  3965. // This would be much simpler if we'd only write one sidx
  3966. // atom, for the first track in the moof.
  3967. if (round == 0) {
  3968. if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
  3969. return ret;
  3970. } else {
  3971. avio_buf = pb;
  3972. }
  3973. for (i = 0; i < mov->nb_streams; i++) {
  3974. MOVTrack *track = &mov->tracks[i];
  3975. if (tracks >= 0 && i != tracks)
  3976. continue;
  3977. // When writing a sidx for the full file, entry is 0, but
  3978. // we want to include all tracks. ref_size is 0 in this case,
  3979. // since we read it from frag_info instead.
  3980. if (!track->entry && ref_size > 0)
  3981. continue;
  3982. total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
  3983. total_size);
  3984. }
  3985. if (round == 0)
  3986. total_size = ffio_close_null_buf(avio_buf);
  3987. }
  3988. return 0;
  3989. }
  3990. static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
  3991. int64_t mdat_size)
  3992. {
  3993. AVIOContext *avio_buf;
  3994. int ret, moof_size;
  3995. if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
  3996. return ret;
  3997. mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
  3998. moof_size = ffio_close_null_buf(avio_buf);
  3999. if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
  4000. mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
  4001. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
  4002. !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
  4003. mov->ism_lookahead) {
  4004. if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
  4005. return ret;
  4006. if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
  4007. mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
  4008. mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
  4009. }
  4010. }
  4011. return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
  4012. }
  4013. static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
  4014. {
  4015. int64_t pos = avio_tell(pb);
  4016. int i;
  4017. avio_wb32(pb, 0); /* size placeholder */
  4018. ffio_wfourcc(pb, "tfra");
  4019. avio_w8(pb, 1); /* version */
  4020. avio_wb24(pb, 0);
  4021. avio_wb32(pb, track->track_id);
  4022. avio_wb32(pb, 0); /* length of traf/trun/sample num */
  4023. avio_wb32(pb, track->nb_frag_info);
  4024. for (i = 0; i < track->nb_frag_info; i++) {
  4025. avio_wb64(pb, track->frag_info[i].time);
  4026. avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
  4027. avio_w8(pb, 1); /* traf number */
  4028. avio_w8(pb, 1); /* trun number */
  4029. avio_w8(pb, 1); /* sample number */
  4030. }
  4031. return update_size(pb, pos);
  4032. }
  4033. static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
  4034. {
  4035. int64_t pos = avio_tell(pb);
  4036. int i;
  4037. avio_wb32(pb, 0); /* size placeholder */
  4038. ffio_wfourcc(pb, "mfra");
  4039. /* An empty mfra atom is enough to indicate to the publishing point that
  4040. * the stream has ended. */
  4041. if (mov->flags & FF_MOV_FLAG_ISML)
  4042. return update_size(pb, pos);
  4043. for (i = 0; i < mov->nb_streams; i++) {
  4044. MOVTrack *track = &mov->tracks[i];
  4045. if (track->nb_frag_info)
  4046. mov_write_tfra_tag(pb, track);
  4047. }
  4048. avio_wb32(pb, 16);
  4049. ffio_wfourcc(pb, "mfro");
  4050. avio_wb32(pb, 0); /* version + flags */
  4051. avio_wb32(pb, avio_tell(pb) + 4 - pos);
  4052. return update_size(pb, pos);
  4053. }
  4054. static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
  4055. {
  4056. avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
  4057. ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
  4058. mov->mdat_pos = avio_tell(pb);
  4059. avio_wb32(pb, 0); /* size placeholder*/
  4060. ffio_wfourcc(pb, "mdat");
  4061. return 0;
  4062. }
  4063. /* TODO: This needs to be more general */
  4064. static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
  4065. {
  4066. MOVMuxContext *mov = s->priv_data;
  4067. int64_t pos = avio_tell(pb);
  4068. int has_h264 = 0, has_video = 0;
  4069. int minor = 0x200;
  4070. int i;
  4071. for (i = 0; i < s->nb_streams; i++) {
  4072. AVStream *st = s->streams[i];
  4073. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  4074. has_video = 1;
  4075. if (st->codecpar->codec_id == AV_CODEC_ID_H264)
  4076. has_h264 = 1;
  4077. }
  4078. avio_wb32(pb, 0); /* size */
  4079. ffio_wfourcc(pb, "ftyp");
  4080. if (mov->major_brand && strlen(mov->major_brand) >= 4)
  4081. ffio_wfourcc(pb, mov->major_brand);
  4082. else if (mov->mode == MODE_3GP) {
  4083. ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
  4084. minor = has_h264 ? 0x100 : 0x200;
  4085. } else if (mov->mode & MODE_3G2) {
  4086. ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
  4087. minor = has_h264 ? 0x20000 : 0x10000;
  4088. } else if (mov->mode == MODE_PSP)
  4089. ffio_wfourcc(pb, "MSNV");
  4090. else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
  4091. ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
  4092. else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
  4093. ffio_wfourcc(pb, "iso4");
  4094. else if (mov->mode == MODE_MP4)
  4095. ffio_wfourcc(pb, "isom");
  4096. else if (mov->mode == MODE_IPOD)
  4097. ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
  4098. else if (mov->mode == MODE_ISM)
  4099. ffio_wfourcc(pb, "isml");
  4100. else if (mov->mode == MODE_F4V)
  4101. ffio_wfourcc(pb, "f4v ");
  4102. else
  4103. ffio_wfourcc(pb, "qt ");
  4104. avio_wb32(pb, minor);
  4105. if (mov->mode == MODE_MOV)
  4106. ffio_wfourcc(pb, "qt ");
  4107. else if (mov->mode == MODE_ISM) {
  4108. ffio_wfourcc(pb, "piff");
  4109. } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
  4110. ffio_wfourcc(pb, "isom");
  4111. ffio_wfourcc(pb, "iso2");
  4112. if (has_h264)
  4113. ffio_wfourcc(pb, "avc1");
  4114. }
  4115. // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
  4116. // brand. This is compatible with users that don't understand tfdt.
  4117. if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
  4118. ffio_wfourcc(pb, "iso6");
  4119. if (mov->mode == MODE_3GP)
  4120. ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
  4121. else if (mov->mode & MODE_3G2)
  4122. ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
  4123. else if (mov->mode == MODE_PSP)
  4124. ffio_wfourcc(pb, "MSNV");
  4125. else if (mov->mode == MODE_MP4)
  4126. ffio_wfourcc(pb, "mp41");
  4127. if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  4128. ffio_wfourcc(pb, "dash");
  4129. return update_size(pb, pos);
  4130. }
  4131. static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
  4132. {
  4133. AVStream *video_st = s->streams[0];
  4134. AVCodecParameters *video_par = s->streams[0]->codecpar;
  4135. AVCodecParameters *audio_par = s->streams[1]->codecpar;
  4136. int audio_rate = audio_par->sample_rate;
  4137. int64_t frame_rate = video_st->avg_frame_rate.den ?
  4138. (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
  4139. 0;
  4140. int audio_kbitrate = audio_par->bit_rate / 1000;
  4141. int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
  4142. if (frame_rate < 0 || frame_rate > INT32_MAX) {
  4143. av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
  4144. return AVERROR(EINVAL);
  4145. }
  4146. avio_wb32(pb, 0x94); /* size */
  4147. ffio_wfourcc(pb, "uuid");
  4148. ffio_wfourcc(pb, "PROF");
  4149. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  4150. avio_wb32(pb, 0xbb88695c);
  4151. avio_wb32(pb, 0xfac9c740);
  4152. avio_wb32(pb, 0x0); /* ? */
  4153. avio_wb32(pb, 0x3); /* 3 sections ? */
  4154. avio_wb32(pb, 0x14); /* size */
  4155. ffio_wfourcc(pb, "FPRF");
  4156. avio_wb32(pb, 0x0); /* ? */
  4157. avio_wb32(pb, 0x0); /* ? */
  4158. avio_wb32(pb, 0x0); /* ? */
  4159. avio_wb32(pb, 0x2c); /* size */
  4160. ffio_wfourcc(pb, "APRF"); /* audio */
  4161. avio_wb32(pb, 0x0);
  4162. avio_wb32(pb, 0x2); /* TrackID */
  4163. ffio_wfourcc(pb, "mp4a");
  4164. avio_wb32(pb, 0x20f);
  4165. avio_wb32(pb, 0x0);
  4166. avio_wb32(pb, audio_kbitrate);
  4167. avio_wb32(pb, audio_kbitrate);
  4168. avio_wb32(pb, audio_rate);
  4169. avio_wb32(pb, audio_par->channels);
  4170. avio_wb32(pb, 0x34); /* size */
  4171. ffio_wfourcc(pb, "VPRF"); /* video */
  4172. avio_wb32(pb, 0x0);
  4173. avio_wb32(pb, 0x1); /* TrackID */
  4174. if (video_par->codec_id == AV_CODEC_ID_H264) {
  4175. ffio_wfourcc(pb, "avc1");
  4176. avio_wb16(pb, 0x014D);
  4177. avio_wb16(pb, 0x0015);
  4178. } else {
  4179. ffio_wfourcc(pb, "mp4v");
  4180. avio_wb16(pb, 0x0000);
  4181. avio_wb16(pb, 0x0103);
  4182. }
  4183. avio_wb32(pb, 0x0);
  4184. avio_wb32(pb, video_kbitrate);
  4185. avio_wb32(pb, video_kbitrate);
  4186. avio_wb32(pb, frame_rate);
  4187. avio_wb32(pb, frame_rate);
  4188. avio_wb16(pb, video_par->width);
  4189. avio_wb16(pb, video_par->height);
  4190. avio_wb32(pb, 0x010001); /* ? */
  4191. return 0;
  4192. }
  4193. static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
  4194. {
  4195. MOVMuxContext *mov = s->priv_data;
  4196. int i;
  4197. mov_write_ftyp_tag(pb,s);
  4198. if (mov->mode == MODE_PSP) {
  4199. int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
  4200. for (i = 0; i < s->nb_streams; i++) {
  4201. AVStream *st = s->streams[i];
  4202. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  4203. video_streams_nb++;
  4204. else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  4205. audio_streams_nb++;
  4206. else
  4207. other_streams_nb++;
  4208. }
  4209. if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
  4210. av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
  4211. return AVERROR(EINVAL);
  4212. }
  4213. return mov_write_uuidprof_tag(pb, s);
  4214. }
  4215. return 0;
  4216. }
  4217. static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
  4218. {
  4219. uint32_t c = -1;
  4220. int i, closed_gop = 0;
  4221. for (i = 0; i < pkt->size - 4; i++) {
  4222. c = (c << 8) + pkt->data[i];
  4223. if (c == 0x1b8) { // gop
  4224. closed_gop = pkt->data[i + 4] >> 6 & 0x01;
  4225. } else if (c == 0x100) { // pic
  4226. int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
  4227. if (!temp_ref || closed_gop) // I picture is not reordered
  4228. *flags = MOV_SYNC_SAMPLE;
  4229. else
  4230. *flags = MOV_PARTIAL_SYNC_SAMPLE;
  4231. break;
  4232. }
  4233. }
  4234. return 0;
  4235. }
  4236. static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
  4237. {
  4238. const uint8_t *start, *next, *end = pkt->data + pkt->size;
  4239. int seq = 0, entry = 0;
  4240. int key = pkt->flags & AV_PKT_FLAG_KEY;
  4241. start = find_next_marker(pkt->data, end);
  4242. for (next = start; next < end; start = next) {
  4243. next = find_next_marker(start + 4, end);
  4244. switch (AV_RB32(start)) {
  4245. case VC1_CODE_SEQHDR:
  4246. seq = 1;
  4247. break;
  4248. case VC1_CODE_ENTRYPOINT:
  4249. entry = 1;
  4250. break;
  4251. case VC1_CODE_SLICE:
  4252. trk->vc1_info.slices = 1;
  4253. break;
  4254. }
  4255. }
  4256. if (!trk->entry && trk->vc1_info.first_packet_seen)
  4257. trk->vc1_info.first_frag_written = 1;
  4258. if (!trk->entry && !trk->vc1_info.first_frag_written) {
  4259. /* First packet in first fragment */
  4260. trk->vc1_info.first_packet_seq = seq;
  4261. trk->vc1_info.first_packet_entry = entry;
  4262. trk->vc1_info.first_packet_seen = 1;
  4263. } else if ((seq && !trk->vc1_info.packet_seq) ||
  4264. (entry && !trk->vc1_info.packet_entry)) {
  4265. int i;
  4266. for (i = 0; i < trk->entry; i++)
  4267. trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
  4268. trk->has_keyframes = 0;
  4269. if (seq)
  4270. trk->vc1_info.packet_seq = 1;
  4271. if (entry)
  4272. trk->vc1_info.packet_entry = 1;
  4273. if (!trk->vc1_info.first_frag_written) {
  4274. /* First fragment */
  4275. if ((!seq || trk->vc1_info.first_packet_seq) &&
  4276. (!entry || trk->vc1_info.first_packet_entry)) {
  4277. /* First packet had the same headers as this one, readd the
  4278. * sync sample flag. */
  4279. trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
  4280. trk->has_keyframes = 1;
  4281. }
  4282. }
  4283. }
  4284. if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
  4285. key = seq && entry;
  4286. else if (trk->vc1_info.packet_seq)
  4287. key = seq;
  4288. else if (trk->vc1_info.packet_entry)
  4289. key = entry;
  4290. if (key) {
  4291. trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
  4292. trk->has_keyframes++;
  4293. }
  4294. }
  4295. static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
  4296. {
  4297. MOVMuxContext *mov = s->priv_data;
  4298. int ret, buf_size;
  4299. uint8_t *buf;
  4300. int i, offset;
  4301. if (!track->mdat_buf)
  4302. return 0;
  4303. if (!mov->mdat_buf) {
  4304. if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
  4305. return ret;
  4306. }
  4307. buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
  4308. track->mdat_buf = NULL;
  4309. offset = avio_tell(mov->mdat_buf);
  4310. avio_write(mov->mdat_buf, buf, buf_size);
  4311. av_free(buf);
  4312. for (i = track->entries_flushed; i < track->entry; i++)
  4313. track->cluster[i].pos += offset;
  4314. track->entries_flushed = track->entry;
  4315. return 0;
  4316. }
  4317. static int mov_flush_fragment(AVFormatContext *s, int force)
  4318. {
  4319. MOVMuxContext *mov = s->priv_data;
  4320. int i, first_track = -1;
  4321. int64_t mdat_size = 0;
  4322. int ret;
  4323. int has_video = 0, starts_with_key = 0, first_video_track = 1;
  4324. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
  4325. return 0;
  4326. // Try to fill in the duration of the last packet in each stream
  4327. // from queued packets in the interleave queues. If the flushing
  4328. // of fragments was triggered automatically by an AVPacket, we
  4329. // already have reliable info for the end of that track, but other
  4330. // tracks may need to be filled in.
  4331. for (i = 0; i < s->nb_streams; i++) {
  4332. MOVTrack *track = &mov->tracks[i];
  4333. if (!track->end_reliable) {
  4334. AVPacket pkt;
  4335. if (!ff_interleaved_peek(s, i, &pkt, 1)) {
  4336. if (track->dts_shift != AV_NOPTS_VALUE)
  4337. pkt.dts += track->dts_shift;
  4338. track->track_duration = pkt.dts - track->start_dts;
  4339. if (pkt.pts != AV_NOPTS_VALUE)
  4340. track->end_pts = pkt.pts;
  4341. else
  4342. track->end_pts = pkt.dts;
  4343. }
  4344. }
  4345. }
  4346. for (i = 0; i < mov->nb_streams; i++) {
  4347. MOVTrack *track = &mov->tracks[i];
  4348. if (track->entry <= 1)
  4349. continue;
  4350. // Sample durations are calculated as the diff of dts values,
  4351. // but for the last sample in a fragment, we don't know the dts
  4352. // of the first sample in the next fragment, so we have to rely
  4353. // on what was set as duration in the AVPacket. Not all callers
  4354. // set this though, so we might want to replace it with an
  4355. // estimate if it currently is zero.
  4356. if (get_cluster_duration(track, track->entry - 1) != 0)
  4357. continue;
  4358. // Use the duration (i.e. dts diff) of the second last sample for
  4359. // the last one. This is a wild guess (and fatal if it turns out
  4360. // to be too long), but probably the best we can do - having a zero
  4361. // duration is bad as well.
  4362. track->track_duration += get_cluster_duration(track, track->entry - 2);
  4363. track->end_pts += get_cluster_duration(track, track->entry - 2);
  4364. if (!mov->missing_duration_warned) {
  4365. av_log(s, AV_LOG_WARNING,
  4366. "Estimating the duration of the last packet in a "
  4367. "fragment, consider setting the duration field in "
  4368. "AVPacket instead.\n");
  4369. mov->missing_duration_warned = 1;
  4370. }
  4371. }
  4372. if (!mov->moov_written) {
  4373. int64_t pos = avio_tell(s->pb);
  4374. uint8_t *buf;
  4375. int buf_size, moov_size;
  4376. for (i = 0; i < mov->nb_streams; i++)
  4377. if (!mov->tracks[i].entry)
  4378. break;
  4379. /* Don't write the initial moov unless all tracks have data */
  4380. if (i < mov->nb_streams && !force)
  4381. return 0;
  4382. moov_size = get_moov_size(s);
  4383. for (i = 0; i < mov->nb_streams; i++)
  4384. mov->tracks[i].data_offset = pos + moov_size + 8;
  4385. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
  4386. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  4387. mov_write_identification(s->pb, s);
  4388. if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
  4389. return ret;
  4390. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
  4391. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  4392. mov->reserved_header_pos = avio_tell(s->pb);
  4393. avio_flush(s->pb);
  4394. mov->moov_written = 1;
  4395. return 0;
  4396. }
  4397. buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
  4398. mov->mdat_buf = NULL;
  4399. avio_wb32(s->pb, buf_size + 8);
  4400. ffio_wfourcc(s->pb, "mdat");
  4401. avio_write(s->pb, buf, buf_size);
  4402. av_free(buf);
  4403. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  4404. mov->reserved_header_pos = avio_tell(s->pb);
  4405. mov->moov_written = 1;
  4406. mov->mdat_size = 0;
  4407. for (i = 0; i < mov->nb_streams; i++) {
  4408. if (mov->tracks[i].entry)
  4409. mov->tracks[i].frag_start += mov->tracks[i].start_dts +
  4410. mov->tracks[i].track_duration -
  4411. mov->tracks[i].cluster[0].dts;
  4412. mov->tracks[i].entry = 0;
  4413. mov->tracks[i].end_reliable = 0;
  4414. }
  4415. avio_flush(s->pb);
  4416. return 0;
  4417. }
  4418. if (mov->frag_interleave) {
  4419. for (i = 0; i < mov->nb_streams; i++) {
  4420. MOVTrack *track = &mov->tracks[i];
  4421. int ret;
  4422. if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
  4423. return ret;
  4424. }
  4425. if (!mov->mdat_buf)
  4426. return 0;
  4427. mdat_size = avio_tell(mov->mdat_buf);
  4428. }
  4429. for (i = 0; i < mov->nb_streams; i++) {
  4430. MOVTrack *track = &mov->tracks[i];
  4431. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
  4432. track->data_offset = 0;
  4433. else
  4434. track->data_offset = mdat_size;
  4435. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  4436. has_video = 1;
  4437. if (first_video_track) {
  4438. if (track->entry)
  4439. starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
  4440. first_video_track = 0;
  4441. }
  4442. }
  4443. if (!track->entry)
  4444. continue;
  4445. if (track->mdat_buf)
  4446. mdat_size += avio_tell(track->mdat_buf);
  4447. if (first_track < 0)
  4448. first_track = i;
  4449. }
  4450. if (!mdat_size)
  4451. return 0;
  4452. avio_write_marker(s->pb,
  4453. av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
  4454. (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);
  4455. for (i = 0; i < mov->nb_streams; i++) {
  4456. MOVTrack *track = &mov->tracks[i];
  4457. int buf_size, write_moof = 1, moof_tracks = -1;
  4458. uint8_t *buf;
  4459. int64_t duration = 0;
  4460. if (track->entry)
  4461. duration = track->start_dts + track->track_duration -
  4462. track->cluster[0].dts;
  4463. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
  4464. if (!track->mdat_buf)
  4465. continue;
  4466. mdat_size = avio_tell(track->mdat_buf);
  4467. moof_tracks = i;
  4468. } else {
  4469. write_moof = i == first_track;
  4470. }
  4471. if (write_moof) {
  4472. avio_flush(s->pb);
  4473. mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
  4474. mov->fragments++;
  4475. avio_wb32(s->pb, mdat_size + 8);
  4476. ffio_wfourcc(s->pb, "mdat");
  4477. }
  4478. if (track->entry)
  4479. track->frag_start += duration;
  4480. track->entry = 0;
  4481. track->entries_flushed = 0;
  4482. track->end_reliable = 0;
  4483. if (!mov->frag_interleave) {
  4484. if (!track->mdat_buf)
  4485. continue;
  4486. buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
  4487. track->mdat_buf = NULL;
  4488. } else {
  4489. if (!mov->mdat_buf)
  4490. continue;
  4491. buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
  4492. mov->mdat_buf = NULL;
  4493. }
  4494. avio_write(s->pb, buf, buf_size);
  4495. av_free(buf);
  4496. }
  4497. mov->mdat_size = 0;
  4498. avio_flush(s->pb);
  4499. return 0;
  4500. }
  4501. static int mov_auto_flush_fragment(AVFormatContext *s, int force)
  4502. {
  4503. MOVMuxContext *mov = s->priv_data;
  4504. int had_moov = mov->moov_written;
  4505. int ret = mov_flush_fragment(s, force);
  4506. if (ret < 0)
  4507. return ret;
  4508. // If using delay_moov, the first flush only wrote the moov,
  4509. // not the actual moof+mdat pair, thus flush once again.
  4510. if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  4511. ret = mov_flush_fragment(s, force);
  4512. return ret;
  4513. }
  4514. static int check_pkt(AVFormatContext *s, AVPacket *pkt)
  4515. {
  4516. MOVMuxContext *mov = s->priv_data;
  4517. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4518. int64_t ref;
  4519. uint64_t duration;
  4520. if (trk->entry) {
  4521. ref = trk->cluster[trk->entry - 1].dts;
  4522. } else if ( trk->start_dts != AV_NOPTS_VALUE
  4523. && !trk->frag_discont) {
  4524. ref = trk->start_dts + trk->track_duration;
  4525. } else
  4526. ref = pkt->dts; // Skip tests for the first packet
  4527. if (trk->dts_shift != AV_NOPTS_VALUE) {
  4528. /* With negative CTS offsets we have set an offset to the DTS,
  4529. * reverse this for the check. */
  4530. ref -= trk->dts_shift;
  4531. }
  4532. duration = pkt->dts - ref;
  4533. if (pkt->dts < ref || duration >= INT_MAX) {
  4534. av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
  4535. duration, pkt->dts
  4536. );
  4537. pkt->dts = ref + 1;
  4538. pkt->pts = AV_NOPTS_VALUE;
  4539. }
  4540. if (pkt->duration < 0 || pkt->duration > INT_MAX) {
  4541. av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
  4542. return AVERROR(EINVAL);
  4543. }
  4544. return 0;
  4545. }
  4546. int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  4547. {
  4548. MOVMuxContext *mov = s->priv_data;
  4549. AVIOContext *pb = s->pb;
  4550. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4551. AVCodecParameters *par = trk->par;
  4552. unsigned int samples_in_chunk = 0;
  4553. int size = pkt->size, ret = 0;
  4554. uint8_t *reformatted_data = NULL;
  4555. ret = check_pkt(s, pkt);
  4556. if (ret < 0)
  4557. return ret;
  4558. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  4559. int ret;
  4560. if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  4561. if (mov->frag_interleave && mov->fragments > 0) {
  4562. if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
  4563. if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
  4564. return ret;
  4565. }
  4566. }
  4567. if (!trk->mdat_buf) {
  4568. if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
  4569. return ret;
  4570. }
  4571. pb = trk->mdat_buf;
  4572. } else {
  4573. if (!mov->mdat_buf) {
  4574. if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
  4575. return ret;
  4576. }
  4577. pb = mov->mdat_buf;
  4578. }
  4579. }
  4580. if (par->codec_id == AV_CODEC_ID_AMR_NB) {
  4581. /* We must find out how many AMR blocks there are in one packet */
  4582. static const uint16_t packed_size[16] =
  4583. {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
  4584. int len = 0;
  4585. while (len < size && samples_in_chunk < 100) {
  4586. len += packed_size[(pkt->data[len] >> 3) & 0x0F];
  4587. samples_in_chunk++;
  4588. }
  4589. if (samples_in_chunk > 1) {
  4590. av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
  4591. return -1;
  4592. }
  4593. } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
  4594. par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
  4595. samples_in_chunk = trk->par->frame_size;
  4596. } else if (trk->sample_size)
  4597. samples_in_chunk = size / trk->sample_size;
  4598. else
  4599. samples_in_chunk = 1;
  4600. /* copy extradata if it exists */
  4601. if (trk->vos_len == 0 && par->extradata_size > 0 &&
  4602. !TAG_IS_AVCI(trk->tag) &&
  4603. (par->codec_id != AV_CODEC_ID_DNXHD)) {
  4604. trk->vos_len = par->extradata_size;
  4605. trk->vos_data = av_malloc(trk->vos_len);
  4606. if (!trk->vos_data) {
  4607. ret = AVERROR(ENOMEM);
  4608. goto err;
  4609. }
  4610. memcpy(trk->vos_data, par->extradata, trk->vos_len);
  4611. }
  4612. if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
  4613. (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
  4614. if (!s->streams[pkt->stream_index]->nb_frames) {
  4615. av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
  4616. "use the audio bitstream filter 'aac_adtstoasc' to fix it "
  4617. "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
  4618. return -1;
  4619. }
  4620. av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
  4621. }
  4622. if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
  4623. /* from x264 or from bytestream H.264 */
  4624. /* NAL reformatting needed */
  4625. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  4626. ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
  4627. &size);
  4628. avio_write(pb, reformatted_data, size);
  4629. } else {
  4630. if (trk->cenc.aes_ctr) {
  4631. size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
  4632. if (size < 0) {
  4633. ret = size;
  4634. goto err;
  4635. }
  4636. } else {
  4637. size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
  4638. }
  4639. }
  4640. } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
  4641. (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
  4642. /* extradata is Annex B, assume the bitstream is too and convert it */
  4643. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  4644. ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
  4645. avio_write(pb, reformatted_data, size);
  4646. } else {
  4647. size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
  4648. }
  4649. #if CONFIG_AC3_PARSER
  4650. } else if (par->codec_id == AV_CODEC_ID_EAC3) {
  4651. size = handle_eac3(mov, pkt, trk);
  4652. if (size < 0)
  4653. return size;
  4654. else if (!size)
  4655. goto end;
  4656. avio_write(pb, pkt->data, size);
  4657. #endif
  4658. } else {
  4659. if (trk->cenc.aes_ctr) {
  4660. if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
  4661. int nal_size_length = (par->extradata[4] & 0x3) + 1;
  4662. ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
  4663. } else {
  4664. ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
  4665. }
  4666. if (ret) {
  4667. goto err;
  4668. }
  4669. } else {
  4670. avio_write(pb, pkt->data, size);
  4671. }
  4672. }
  4673. if ((par->codec_id == AV_CODEC_ID_DNXHD ||
  4674. par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
  4675. /* copy frame to create needed atoms */
  4676. trk->vos_len = size;
  4677. trk->vos_data = av_malloc(size);
  4678. if (!trk->vos_data) {
  4679. ret = AVERROR(ENOMEM);
  4680. goto err;
  4681. }
  4682. memcpy(trk->vos_data, pkt->data, size);
  4683. }
  4684. if (trk->entry >= trk->cluster_capacity) {
  4685. unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
  4686. if (av_reallocp_array(&trk->cluster, new_capacity,
  4687. sizeof(*trk->cluster))) {
  4688. ret = AVERROR(ENOMEM);
  4689. goto err;
  4690. }
  4691. trk->cluster_capacity = new_capacity;
  4692. }
  4693. trk->cluster[trk->entry].pos = avio_tell(pb) - size;
  4694. trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
  4695. trk->cluster[trk->entry].chunkNum = 0;
  4696. trk->cluster[trk->entry].size = size;
  4697. trk->cluster[trk->entry].entries = samples_in_chunk;
  4698. trk->cluster[trk->entry].dts = pkt->dts;
  4699. if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
  4700. if (!trk->frag_discont) {
  4701. /* First packet of a new fragment. We already wrote the duration
  4702. * of the last packet of the previous fragment based on track_duration,
  4703. * which might not exactly match our dts. Therefore adjust the dts
  4704. * of this packet to be what the previous packets duration implies. */
  4705. trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
  4706. /* We also may have written the pts and the corresponding duration
  4707. * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
  4708. * the next fragment. This means the cts of the first sample must
  4709. * be the same in all fragments, unless end_pts was updated by
  4710. * the packet causing the fragment to be written. */
  4711. if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
  4712. mov->mode == MODE_ISM)
  4713. pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
  4714. } else {
  4715. /* New fragment, but discontinuous from previous fragments.
  4716. * Pretend the duration sum of the earlier fragments is
  4717. * pkt->dts - trk->start_dts. */
  4718. trk->frag_start = pkt->dts - trk->start_dts;
  4719. trk->end_pts = AV_NOPTS_VALUE;
  4720. trk->frag_discont = 0;
  4721. }
  4722. }
  4723. if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
  4724. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
  4725. /* Not using edit lists and shifting the first track to start from zero.
  4726. * If the other streams start from a later timestamp, we won't be able
  4727. * to signal the difference in starting time without an edit list.
  4728. * Thus move the timestamp for this first sample to 0, increasing
  4729. * its duration instead. */
  4730. trk->cluster[trk->entry].dts = trk->start_dts = 0;
  4731. }
  4732. if (trk->start_dts == AV_NOPTS_VALUE) {
  4733. trk->start_dts = pkt->dts;
  4734. if (trk->frag_discont) {
  4735. if (mov->use_editlist) {
  4736. /* Pretend the whole stream started at pts=0, with earlier fragments
  4737. * already written. If the stream started at pts=0, the duration sum
  4738. * of earlier fragments would have been pkt->pts. */
  4739. trk->frag_start = pkt->pts;
  4740. trk->start_dts = pkt->dts - pkt->pts;
  4741. } else {
  4742. /* Pretend the whole stream started at dts=0, with earlier fragments
  4743. * already written, with a duration summing up to pkt->dts. */
  4744. trk->frag_start = pkt->dts;
  4745. trk->start_dts = 0;
  4746. }
  4747. trk->frag_discont = 0;
  4748. } else if (pkt->dts && mov->moov_written)
  4749. av_log(s, AV_LOG_WARNING,
  4750. "Track %d starts with a nonzero dts %"PRId64", while the moov "
  4751. "already has been written. Set the delay_moov flag to handle "
  4752. "this case.\n",
  4753. pkt->stream_index, pkt->dts);
  4754. }
  4755. trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
  4756. trk->last_sample_is_subtitle_end = 0;
  4757. if (pkt->pts == AV_NOPTS_VALUE) {
  4758. av_log(s, AV_LOG_WARNING, "pts has no value\n");
  4759. pkt->pts = pkt->dts;
  4760. }
  4761. if (pkt->dts != pkt->pts)
  4762. trk->flags |= MOV_TRACK_CTTS;
  4763. trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
  4764. trk->cluster[trk->entry].flags = 0;
  4765. if (trk->start_cts == AV_NOPTS_VALUE)
  4766. trk->start_cts = pkt->pts - pkt->dts;
  4767. if (trk->end_pts == AV_NOPTS_VALUE)
  4768. trk->end_pts = trk->cluster[trk->entry].dts +
  4769. trk->cluster[trk->entry].cts + pkt->duration;
  4770. else
  4771. trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
  4772. trk->cluster[trk->entry].cts +
  4773. pkt->duration);
  4774. if (par->codec_id == AV_CODEC_ID_VC1) {
  4775. mov_parse_vc1_frame(pkt, trk);
  4776. } else if (pkt->flags & AV_PKT_FLAG_KEY) {
  4777. if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
  4778. trk->entry > 0) { // force sync sample for the first key frame
  4779. mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
  4780. if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
  4781. trk->flags |= MOV_TRACK_STPS;
  4782. } else {
  4783. trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
  4784. }
  4785. if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
  4786. trk->has_keyframes++;
  4787. }
  4788. if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
  4789. trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
  4790. trk->has_disposable++;
  4791. }
  4792. trk->entry++;
  4793. trk->sample_count += samples_in_chunk;
  4794. mov->mdat_size += size;
  4795. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
  4796. ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
  4797. reformatted_data, size);
  4798. end:
  4799. err:
  4800. av_free(reformatted_data);
  4801. return ret;
  4802. }
  4803. static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
  4804. {
  4805. MOVMuxContext *mov = s->priv_data;
  4806. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4807. AVCodecParameters *par = trk->par;
  4808. int64_t frag_duration = 0;
  4809. int size = pkt->size;
  4810. int ret = check_pkt(s, pkt);
  4811. if (ret < 0)
  4812. return ret;
  4813. if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
  4814. int i;
  4815. for (i = 0; i < s->nb_streams; i++)
  4816. mov->tracks[i].frag_discont = 1;
  4817. mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
  4818. }
  4819. if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
  4820. if (trk->dts_shift == AV_NOPTS_VALUE)
  4821. trk->dts_shift = pkt->pts - pkt->dts;
  4822. pkt->dts += trk->dts_shift;
  4823. }
  4824. if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
  4825. trk->par->codec_id == AV_CODEC_ID_AAC ||
  4826. trk->par->codec_id == AV_CODEC_ID_FLAC) {
  4827. int side_size = 0;
  4828. uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
  4829. if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
  4830. void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
  4831. if (!newextra)
  4832. return AVERROR(ENOMEM);
  4833. av_free(par->extradata);
  4834. par->extradata = newextra;
  4835. memcpy(par->extradata, side, side_size);
  4836. par->extradata_size = side_size;
  4837. if (!pkt->size) // Flush packet
  4838. mov->need_rewrite_extradata = 1;
  4839. }
  4840. }
  4841. if (!pkt->size) {
  4842. if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
  4843. trk->start_dts = pkt->dts;
  4844. if (pkt->pts != AV_NOPTS_VALUE)
  4845. trk->start_cts = pkt->pts - pkt->dts;
  4846. else
  4847. trk->start_cts = 0;
  4848. }
  4849. return 0; /* Discard 0 sized packets */
  4850. }
  4851. if (trk->entry && pkt->stream_index < s->nb_streams)
  4852. frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
  4853. s->streams[pkt->stream_index]->time_base,
  4854. AV_TIME_BASE_Q);
  4855. if ((mov->max_fragment_duration &&
  4856. frag_duration >= mov->max_fragment_duration) ||
  4857. (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
  4858. (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
  4859. par->codec_type == AVMEDIA_TYPE_VIDEO &&
  4860. trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
  4861. if (frag_duration >= mov->min_fragment_duration) {
  4862. // Set the duration of this track to line up with the next
  4863. // sample in this track. This avoids relying on AVPacket
  4864. // duration, but only helps for this particular track, not
  4865. // for the other ones that are flushed at the same time.
  4866. trk->track_duration = pkt->dts - trk->start_dts;
  4867. if (pkt->pts != AV_NOPTS_VALUE)
  4868. trk->end_pts = pkt->pts;
  4869. else
  4870. trk->end_pts = pkt->dts;
  4871. trk->end_reliable = 1;
  4872. mov_auto_flush_fragment(s, 0);
  4873. }
  4874. }
  4875. return ff_mov_write_packet(s, pkt);
  4876. }
  4877. static int mov_write_subtitle_end_packet(AVFormatContext *s,
  4878. int stream_index,
  4879. int64_t dts) {
  4880. AVPacket end;
  4881. uint8_t data[2] = {0};
  4882. int ret;
  4883. av_init_packet(&end);
  4884. end.size = sizeof(data);
  4885. end.data = data;
  4886. end.pts = dts;
  4887. end.dts = dts;
  4888. end.duration = 0;
  4889. end.stream_index = stream_index;
  4890. ret = mov_write_single_packet(s, &end);
  4891. av_packet_unref(&end);
  4892. return ret;
  4893. }
  4894. static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  4895. {
  4896. if (!pkt) {
  4897. mov_flush_fragment(s, 1);
  4898. return 1;
  4899. } else {
  4900. int i;
  4901. MOVMuxContext *mov = s->priv_data;
  4902. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4903. if (!pkt->size)
  4904. return mov_write_single_packet(s, pkt); /* Passthrough. */
  4905. /*
  4906. * Subtitles require special handling.
  4907. *
  4908. * 1) For full complaince, every track must have a sample at
  4909. * dts == 0, which is rarely true for subtitles. So, as soon
  4910. * as we see any packet with dts > 0, write an empty subtitle
  4911. * at dts == 0 for any subtitle track with no samples in it.
  4912. *
  4913. * 2) For each subtitle track, check if the current packet's
  4914. * dts is past the duration of the last subtitle sample. If
  4915. * so, we now need to write an end sample for that subtitle.
  4916. *
  4917. * This must be done conditionally to allow for subtitles that
  4918. * immediately replace each other, in which case an end sample
  4919. * is not needed, and is, in fact, actively harmful.
  4920. *
  4921. * 3) See mov_write_trailer for how the final end sample is
  4922. * handled.
  4923. */
  4924. for (i = 0; i < mov->nb_streams; i++) {
  4925. MOVTrack *trk = &mov->tracks[i];
  4926. int ret;
  4927. if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
  4928. trk->track_duration < pkt->dts &&
  4929. (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
  4930. ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
  4931. if (ret < 0) return ret;
  4932. trk->last_sample_is_subtitle_end = 1;
  4933. }
  4934. }
  4935. if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  4936. AVPacket *opkt = pkt;
  4937. int reshuffle_ret, ret;
  4938. if (trk->is_unaligned_qt_rgb) {
  4939. int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
  4940. int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
  4941. reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
  4942. if (reshuffle_ret < 0)
  4943. return reshuffle_ret;
  4944. } else
  4945. reshuffle_ret = 0;
  4946. if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
  4947. ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
  4948. if (ret < 0)
  4949. goto fail;
  4950. if (ret)
  4951. trk->pal_done++;
  4952. } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
  4953. (trk->par->format == AV_PIX_FMT_GRAY8 ||
  4954. trk->par->format == AV_PIX_FMT_MONOBLACK)) {
  4955. for (i = 0; i < pkt->size; i++)
  4956. pkt->data[i] = ~pkt->data[i];
  4957. }
  4958. if (reshuffle_ret) {
  4959. ret = mov_write_single_packet(s, pkt);
  4960. fail:
  4961. if (reshuffle_ret)
  4962. av_packet_free(&pkt);
  4963. return ret;
  4964. }
  4965. }
  4966. return mov_write_single_packet(s, pkt);
  4967. }
  4968. }
  4969. // QuickTime chapters involve an additional text track with the chapter names
  4970. // as samples, and a tref pointing from the other tracks to the chapter one.
  4971. static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
  4972. {
  4973. AVIOContext *pb;
  4974. MOVMuxContext *mov = s->priv_data;
  4975. MOVTrack *track = &mov->tracks[tracknum];
  4976. AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
  4977. int i, len;
  4978. track->mode = mov->mode;
  4979. track->tag = MKTAG('t','e','x','t');
  4980. track->timescale = MOV_TIMESCALE;
  4981. track->par = avcodec_parameters_alloc();
  4982. if (!track->par)
  4983. return AVERROR(ENOMEM);
  4984. track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
  4985. #if 0
  4986. // These properties are required to make QT recognize the chapter track
  4987. uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
  4988. if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
  4989. return AVERROR(ENOMEM);
  4990. memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
  4991. #else
  4992. if (avio_open_dyn_buf(&pb) >= 0) {
  4993. int size;
  4994. uint8_t *buf;
  4995. /* Stub header (usually for Quicktime chapter track) */
  4996. // TextSampleEntry
  4997. avio_wb32(pb, 0x01); // displayFlags
  4998. avio_w8(pb, 0x00); // horizontal justification
  4999. avio_w8(pb, 0x00); // vertical justification
  5000. avio_w8(pb, 0x00); // bgColourRed
  5001. avio_w8(pb, 0x00); // bgColourGreen
  5002. avio_w8(pb, 0x00); // bgColourBlue
  5003. avio_w8(pb, 0x00); // bgColourAlpha
  5004. // BoxRecord
  5005. avio_wb16(pb, 0x00); // defTextBoxTop
  5006. avio_wb16(pb, 0x00); // defTextBoxLeft
  5007. avio_wb16(pb, 0x00); // defTextBoxBottom
  5008. avio_wb16(pb, 0x00); // defTextBoxRight
  5009. // StyleRecord
  5010. avio_wb16(pb, 0x00); // startChar
  5011. avio_wb16(pb, 0x00); // endChar
  5012. avio_wb16(pb, 0x01); // fontID
  5013. avio_w8(pb, 0x00); // fontStyleFlags
  5014. avio_w8(pb, 0x00); // fontSize
  5015. avio_w8(pb, 0x00); // fgColourRed
  5016. avio_w8(pb, 0x00); // fgColourGreen
  5017. avio_w8(pb, 0x00); // fgColourBlue
  5018. avio_w8(pb, 0x00); // fgColourAlpha
  5019. // FontTableBox
  5020. avio_wb32(pb, 0x0D); // box size
  5021. ffio_wfourcc(pb, "ftab"); // box atom name
  5022. avio_wb16(pb, 0x01); // entry count
  5023. // FontRecord
  5024. avio_wb16(pb, 0x01); // font ID
  5025. avio_w8(pb, 0x00); // font name length
  5026. if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
  5027. track->par->extradata = buf;
  5028. track->par->extradata_size = size;
  5029. } else {
  5030. av_freep(&buf);
  5031. }
  5032. }
  5033. #endif
  5034. for (i = 0; i < s->nb_chapters; i++) {
  5035. AVChapter *c = s->chapters[i];
  5036. AVDictionaryEntry *t;
  5037. int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
  5038. pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
  5039. pkt.duration = end - pkt.dts;
  5040. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  5041. static const char encd[12] = {
  5042. 0x00, 0x00, 0x00, 0x0C,
  5043. 'e', 'n', 'c', 'd',
  5044. 0x00, 0x00, 0x01, 0x00 };
  5045. len = strlen(t->value);
  5046. pkt.size = len + 2 + 12;
  5047. pkt.data = av_malloc(pkt.size);
  5048. if (!pkt.data)
  5049. return AVERROR(ENOMEM);
  5050. AV_WB16(pkt.data, len);
  5051. memcpy(pkt.data + 2, t->value, len);
  5052. memcpy(pkt.data + len + 2, encd, sizeof(encd));
  5053. ff_mov_write_packet(s, &pkt);
  5054. av_freep(&pkt.data);
  5055. }
  5056. }
  5057. return 0;
  5058. }
  5059. static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
  5060. {
  5061. int ret;
  5062. /* compute the frame number */
  5063. ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
  5064. return ret;
  5065. }
  5066. static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
  5067. {
  5068. int ret;
  5069. MOVMuxContext *mov = s->priv_data;
  5070. MOVTrack *track = &mov->tracks[index];
  5071. AVStream *src_st = s->streams[src_index];
  5072. AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
  5073. AVRational rate = find_fps(s, src_st);
  5074. /* tmcd track based on video stream */
  5075. track->mode = mov->mode;
  5076. track->tag = MKTAG('t','m','c','d');
  5077. track->src_track = src_index;
  5078. track->timescale = mov->tracks[src_index].timescale;
  5079. if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
  5080. track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
  5081. /* set st to src_st for metadata access*/
  5082. track->st = src_st;
  5083. /* encode context: tmcd data stream */
  5084. track->par = avcodec_parameters_alloc();
  5085. if (!track->par)
  5086. return AVERROR(ENOMEM);
  5087. track->par->codec_type = AVMEDIA_TYPE_DATA;
  5088. track->par->codec_tag = track->tag;
  5089. track->st->avg_frame_rate = av_inv_q(rate);
  5090. /* the tmcd track just contains one packet with the frame number */
  5091. pkt.data = av_malloc(pkt.size);
  5092. if (!pkt.data)
  5093. return AVERROR(ENOMEM);
  5094. AV_WB32(pkt.data, tc.start);
  5095. ret = ff_mov_write_packet(s, &pkt);
  5096. av_free(pkt.data);
  5097. return ret;
  5098. }
  5099. /*
  5100. * st->disposition controls the "enabled" flag in the tkhd tag.
  5101. * QuickTime will not play a track if it is not enabled. So make sure
  5102. * that one track of each type (audio, video, subtitle) is enabled.
  5103. *
  5104. * Subtitles are special. For audio and video, setting "enabled" also
  5105. * makes the track "default" (i.e. it is rendered when played). For
  5106. * subtitles, an "enabled" subtitle is not rendered by default, but
  5107. * if no subtitle is enabled, the subtitle menu in QuickTime will be
  5108. * empty!
  5109. */
  5110. static void enable_tracks(AVFormatContext *s)
  5111. {
  5112. MOVMuxContext *mov = s->priv_data;
  5113. int i;
  5114. int enabled[AVMEDIA_TYPE_NB];
  5115. int first[AVMEDIA_TYPE_NB];
  5116. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  5117. enabled[i] = 0;
  5118. first[i] = -1;
  5119. }
  5120. for (i = 0; i < s->nb_streams; i++) {
  5121. AVStream *st = s->streams[i];
  5122. if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
  5123. st->codecpar->codec_type >= AVMEDIA_TYPE_NB)
  5124. continue;
  5125. if (first[st->codecpar->codec_type] < 0)
  5126. first[st->codecpar->codec_type] = i;
  5127. if (st->disposition & AV_DISPOSITION_DEFAULT) {
  5128. mov->tracks[i].flags |= MOV_TRACK_ENABLED;
  5129. enabled[st->codecpar->codec_type]++;
  5130. }
  5131. }
  5132. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  5133. switch (i) {
  5134. case AVMEDIA_TYPE_VIDEO:
  5135. case AVMEDIA_TYPE_AUDIO:
  5136. case AVMEDIA_TYPE_SUBTITLE:
  5137. if (enabled[i] > 1)
  5138. mov->per_stream_grouping = 1;
  5139. if (!enabled[i] && first[i] >= 0)
  5140. mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
  5141. break;
  5142. }
  5143. }
  5144. }
  5145. static void mov_free(AVFormatContext *s)
  5146. {
  5147. MOVMuxContext *mov = s->priv_data;
  5148. int i;
  5149. if (mov->chapter_track) {
  5150. if (mov->tracks[mov->chapter_track].par)
  5151. av_freep(&mov->tracks[mov->chapter_track].par->extradata);
  5152. av_freep(&mov->tracks[mov->chapter_track].par);
  5153. }
  5154. for (i = 0; i < mov->nb_streams; i++) {
  5155. if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
  5156. ff_mov_close_hinting(&mov->tracks[i]);
  5157. else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
  5158. av_freep(&mov->tracks[i].par);
  5159. av_freep(&mov->tracks[i].cluster);
  5160. av_freep(&mov->tracks[i].frag_info);
  5161. if (mov->tracks[i].vos_len)
  5162. av_freep(&mov->tracks[i].vos_data);
  5163. ff_mov_cenc_free(&mov->tracks[i].cenc);
  5164. }
  5165. av_freep(&mov->tracks);
  5166. }
  5167. static uint32_t rgb_to_yuv(uint32_t rgb)
  5168. {
  5169. uint8_t r, g, b;
  5170. int y, cb, cr;
  5171. r = (rgb >> 16) & 0xFF;
  5172. g = (rgb >> 8) & 0xFF;
  5173. b = (rgb ) & 0xFF;
  5174. y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
  5175. cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
  5176. cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
  5177. return (y << 16) | (cr << 8) | cb;
  5178. }
  5179. static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
  5180. AVStream *st)
  5181. {
  5182. int i, width = 720, height = 480;
  5183. int have_palette = 0, have_size = 0;
  5184. uint32_t palette[16];
  5185. char *cur = st->codecpar->extradata;
  5186. while (cur && *cur) {
  5187. if (strncmp("palette:", cur, 8) == 0) {
  5188. int i, count;
  5189. count = sscanf(cur + 8,
  5190. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  5191. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  5192. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  5193. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
  5194. &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
  5195. &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
  5196. &palette[ 8], &palette[ 9], &palette[10], &palette[11],
  5197. &palette[12], &palette[13], &palette[14], &palette[15]);
  5198. for (i = 0; i < count; i++) {
  5199. palette[i] = rgb_to_yuv(palette[i]);
  5200. }
  5201. have_palette = 1;
  5202. } else if (!strncmp("size:", cur, 5)) {
  5203. sscanf(cur + 5, "%dx%d", &width, &height);
  5204. have_size = 1;
  5205. }
  5206. if (have_palette && have_size)
  5207. break;
  5208. cur += strcspn(cur, "\n\r");
  5209. cur += strspn(cur, "\n\r");
  5210. }
  5211. if (have_palette) {
  5212. track->vos_data = av_malloc(16*4);
  5213. if (!track->vos_data)
  5214. return AVERROR(ENOMEM);
  5215. for (i = 0; i < 16; i++) {
  5216. AV_WB32(track->vos_data + i * 4, palette[i]);
  5217. }
  5218. track->vos_len = 16 * 4;
  5219. }
  5220. st->codecpar->width = width;
  5221. st->codecpar->height = track->height = height;
  5222. return 0;
  5223. }
  5224. static int mov_init(AVFormatContext *s)
  5225. {
  5226. MOVMuxContext *mov = s->priv_data;
  5227. AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  5228. int i, ret;
  5229. mov->fc = s;
  5230. /* Default mode == MP4 */
  5231. mov->mode = MODE_MP4;
  5232. if (s->oformat) {
  5233. if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
  5234. else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
  5235. else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
  5236. else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
  5237. else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
  5238. else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
  5239. else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
  5240. }
  5241. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  5242. mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
  5243. /* Set the FRAGMENT flag if any of the fragmentation methods are
  5244. * enabled. */
  5245. if (mov->max_fragment_duration || mov->max_fragment_size ||
  5246. mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
  5247. FF_MOV_FLAG_FRAG_KEYFRAME |
  5248. FF_MOV_FLAG_FRAG_CUSTOM))
  5249. mov->flags |= FF_MOV_FLAG_FRAGMENT;
  5250. /* Set other implicit flags immediately */
  5251. if (mov->mode == MODE_ISM)
  5252. mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
  5253. FF_MOV_FLAG_FRAGMENT;
  5254. if (mov->flags & FF_MOV_FLAG_DASH)
  5255. mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
  5256. FF_MOV_FLAG_DEFAULT_BASE_MOOF;
  5257. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
  5258. av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
  5259. s->flags &= ~AVFMT_FLAG_AUTO_BSF;
  5260. }
  5261. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  5262. mov->reserved_moov_size = -1;
  5263. }
  5264. if (mov->use_editlist < 0) {
  5265. mov->use_editlist = 1;
  5266. if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
  5267. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  5268. // If we can avoid needing an edit list by shifting the
  5269. // tracks, prefer that over (trying to) write edit lists
  5270. // in fragmented output.
  5271. if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
  5272. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
  5273. mov->use_editlist = 0;
  5274. }
  5275. }
  5276. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
  5277. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
  5278. av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
  5279. if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
  5280. s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
  5281. /* Clear the omit_tfhd_offset flag if default_base_moof is set;
  5282. * if the latter is set that's enough and omit_tfhd_offset doesn't
  5283. * add anything extra on top of that. */
  5284. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
  5285. mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
  5286. mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
  5287. if (mov->frag_interleave &&
  5288. mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
  5289. av_log(s, AV_LOG_ERROR,
  5290. "Sample interleaving in fragments is mutually exclusive with "
  5291. "omit_tfhd_offset and separate_moof\n");
  5292. return AVERROR(EINVAL);
  5293. }
  5294. /* Non-seekable output is ok if using fragmentation. If ism_lookahead
  5295. * is enabled, we don't support non-seekable output at all. */
  5296. if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
  5297. (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
  5298. av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
  5299. return AVERROR(EINVAL);
  5300. }
  5301. mov->nb_streams = s->nb_streams;
  5302. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
  5303. mov->chapter_track = mov->nb_streams++;
  5304. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  5305. /* Add hint tracks for each audio and video stream */
  5306. for (i = 0; i < s->nb_streams; i++) {
  5307. AVStream *st = s->streams[i];
  5308. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
  5309. st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  5310. mov->nb_streams++;
  5311. }
  5312. }
  5313. }
  5314. if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
  5315. || mov->write_tmcd == 1) {
  5316. /* +1 tmcd track for each video stream with a timecode */
  5317. for (i = 0; i < s->nb_streams; i++) {
  5318. AVStream *st = s->streams[i];
  5319. AVDictionaryEntry *t = global_tcr;
  5320. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  5321. (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
  5322. AVTimecode tc;
  5323. ret = mov_check_timecode_track(s, &tc, i, t->value);
  5324. if (ret >= 0)
  5325. mov->nb_meta_tmcd++;
  5326. }
  5327. }
  5328. /* check if there is already a tmcd track to remux */
  5329. if (mov->nb_meta_tmcd) {
  5330. for (i = 0; i < s->nb_streams; i++) {
  5331. AVStream *st = s->streams[i];
  5332. if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
  5333. av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
  5334. "so timecode metadata are now ignored\n");
  5335. mov->nb_meta_tmcd = 0;
  5336. }
  5337. }
  5338. }
  5339. mov->nb_streams += mov->nb_meta_tmcd;
  5340. }
  5341. // Reserve an extra stream for chapters for the case where chapters
  5342. // are written in the trailer
  5343. mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
  5344. if (!mov->tracks)
  5345. return AVERROR(ENOMEM);
  5346. if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
  5347. if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
  5348. mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
  5349. if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
  5350. av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
  5351. mov->encryption_key_len, AES_CTR_KEY_SIZE);
  5352. return AVERROR(EINVAL);
  5353. }
  5354. if (mov->encryption_kid_len != CENC_KID_SIZE) {
  5355. av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
  5356. mov->encryption_kid_len, CENC_KID_SIZE);
  5357. return AVERROR(EINVAL);
  5358. }
  5359. } else {
  5360. av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
  5361. mov->encryption_scheme_str);
  5362. return AVERROR(EINVAL);
  5363. }
  5364. }
  5365. for (i = 0; i < s->nb_streams; i++) {
  5366. AVStream *st= s->streams[i];
  5367. MOVTrack *track= &mov->tracks[i];
  5368. AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
  5369. track->st = st;
  5370. track->par = st->codecpar;
  5371. track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
  5372. if (track->language < 0)
  5373. track->language = 0;
  5374. track->mode = mov->mode;
  5375. track->tag = mov_find_codec_tag(s, track);
  5376. if (!track->tag) {
  5377. av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
  5378. "codec not currently supported in container\n",
  5379. avcodec_get_name(st->codecpar->codec_id), i);
  5380. return AVERROR(EINVAL);
  5381. }
  5382. /* If hinting of this track is enabled by a later hint track,
  5383. * this is updated. */
  5384. track->hint_track = -1;
  5385. track->start_dts = AV_NOPTS_VALUE;
  5386. track->start_cts = AV_NOPTS_VALUE;
  5387. track->end_pts = AV_NOPTS_VALUE;
  5388. track->dts_shift = AV_NOPTS_VALUE;
  5389. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  5390. if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
  5391. track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
  5392. track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
  5393. if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
  5394. av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
  5395. return AVERROR(EINVAL);
  5396. }
  5397. track->height = track->tag >> 24 == 'n' ? 486 : 576;
  5398. }
  5399. if (mov->video_track_timescale) {
  5400. track->timescale = mov->video_track_timescale;
  5401. } else {
  5402. track->timescale = st->time_base.den;
  5403. while(track->timescale < 10000)
  5404. track->timescale *= 2;
  5405. }
  5406. if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
  5407. av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
  5408. return AVERROR(EINVAL);
  5409. }
  5410. if (track->mode == MODE_MOV && track->timescale > 100000)
  5411. av_log(s, AV_LOG_WARNING,
  5412. "WARNING codec timebase is very high. If duration is too long,\n"
  5413. "file may not be playable by quicktime. Specify a shorter timebase\n"
  5414. "or choose different container.\n");
  5415. if (track->mode == MODE_MOV &&
  5416. track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
  5417. track->tag == MKTAG('r','a','w',' ')) {
  5418. enum AVPixelFormat pix_fmt = track->par->format;
  5419. if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
  5420. pix_fmt = AV_PIX_FMT_MONOWHITE;
  5421. track->is_unaligned_qt_rgb =
  5422. pix_fmt == AV_PIX_FMT_RGB24 ||
  5423. pix_fmt == AV_PIX_FMT_BGR24 ||
  5424. pix_fmt == AV_PIX_FMT_PAL8 ||
  5425. pix_fmt == AV_PIX_FMT_GRAY8 ||
  5426. pix_fmt == AV_PIX_FMT_MONOWHITE ||
  5427. pix_fmt == AV_PIX_FMT_MONOBLACK;
  5428. }
  5429. if (track->par->codec_id == AV_CODEC_ID_VP9) {
  5430. if (track->mode != MODE_MP4) {
  5431. av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
  5432. return AVERROR(EINVAL);
  5433. }
  5434. }
  5435. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  5436. track->timescale = st->codecpar->sample_rate;
  5437. if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
  5438. av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
  5439. track->audio_vbr = 1;
  5440. }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
  5441. st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  5442. st->codecpar->codec_id == AV_CODEC_ID_ILBC){
  5443. if (!st->codecpar->block_align) {
  5444. av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
  5445. return AVERROR(EINVAL);
  5446. }
  5447. track->sample_size = st->codecpar->block_align;
  5448. }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
  5449. track->audio_vbr = 1;
  5450. }else{
  5451. track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
  5452. }
  5453. if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
  5454. st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
  5455. track->audio_vbr = 1;
  5456. }
  5457. if (track->mode != MODE_MOV &&
  5458. track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
  5459. if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
  5460. av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
  5461. i, track->par->sample_rate);
  5462. return AVERROR(EINVAL);
  5463. } else {
  5464. av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
  5465. i, track->par->sample_rate);
  5466. }
  5467. }
  5468. if (track->par->codec_id == AV_CODEC_ID_FLAC ||
  5469. track->par->codec_id == AV_CODEC_ID_OPUS) {
  5470. if (track->mode != MODE_MP4) {
  5471. av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
  5472. return AVERROR(EINVAL);
  5473. }
  5474. if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  5475. av_log(s, AV_LOG_ERROR,
  5476. "%s in MP4 support is experimental, add "
  5477. "'-strict %d' if you want to use it.\n",
  5478. avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
  5479. return AVERROR_EXPERIMENTAL;
  5480. }
  5481. }
  5482. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  5483. track->timescale = st->time_base.den;
  5484. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
  5485. track->timescale = st->time_base.den;
  5486. } else {
  5487. track->timescale = MOV_TIMESCALE;
  5488. }
  5489. if (!track->height)
  5490. track->height = st->codecpar->height;
  5491. /* The ism specific timescale isn't mandatory, but is assumed by
  5492. * some tools, such as mp4split. */
  5493. if (mov->mode == MODE_ISM)
  5494. track->timescale = 10000000;
  5495. avpriv_set_pts_info(st, 64, 1, track->timescale);
  5496. if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
  5497. ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
  5498. track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
  5499. if (ret)
  5500. return ret;
  5501. }
  5502. }
  5503. enable_tracks(s);
  5504. return 0;
  5505. }
  5506. static int mov_write_header(AVFormatContext *s)
  5507. {
  5508. AVIOContext *pb = s->pb;
  5509. MOVMuxContext *mov = s->priv_data;
  5510. AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  5511. int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
  5512. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
  5513. nb_tracks++;
  5514. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  5515. /* Add hint tracks for each audio and video stream */
  5516. hint_track = nb_tracks;
  5517. for (i = 0; i < s->nb_streams; i++) {
  5518. AVStream *st = s->streams[i];
  5519. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
  5520. st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  5521. nb_tracks++;
  5522. }
  5523. }
  5524. }
  5525. if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
  5526. tmcd_track = nb_tracks;
  5527. for (i = 0; i < s->nb_streams; i++) {
  5528. int j;
  5529. AVStream *st= s->streams[i];
  5530. MOVTrack *track= &mov->tracks[i];
  5531. /* copy extradata if it exists */
  5532. if (st->codecpar->extradata_size) {
  5533. if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  5534. mov_create_dvd_sub_decoder_specific_info(track, st);
  5535. else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
  5536. track->vos_len = st->codecpar->extradata_size;
  5537. track->vos_data = av_malloc(track->vos_len);
  5538. if (!track->vos_data) {
  5539. return AVERROR(ENOMEM);
  5540. }
  5541. memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
  5542. }
  5543. }
  5544. if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
  5545. track->par->channel_layout != AV_CH_LAYOUT_MONO)
  5546. continue;
  5547. for (j = 0; j < s->nb_streams; j++) {
  5548. AVStream *stj= s->streams[j];
  5549. MOVTrack *trackj= &mov->tracks[j];
  5550. if (j == i)
  5551. continue;
  5552. if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
  5553. trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
  5554. trackj->language != track->language ||
  5555. trackj->tag != track->tag
  5556. )
  5557. continue;
  5558. track->multichannel_as_mono++;
  5559. }
  5560. }
  5561. if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  5562. if ((ret = mov_write_identification(pb, s)) < 0)
  5563. return ret;
  5564. }
  5565. if (mov->reserved_moov_size){
  5566. mov->reserved_header_pos = avio_tell(pb);
  5567. if (mov->reserved_moov_size > 0)
  5568. avio_skip(pb, mov->reserved_moov_size);
  5569. }
  5570. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  5571. /* If no fragmentation options have been set, set a default. */
  5572. if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
  5573. FF_MOV_FLAG_FRAG_CUSTOM)) &&
  5574. !mov->max_fragment_duration && !mov->max_fragment_size)
  5575. mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
  5576. } else {
  5577. if (mov->flags & FF_MOV_FLAG_FASTSTART)
  5578. mov->reserved_header_pos = avio_tell(pb);
  5579. mov_write_mdat_tag(pb, mov);
  5580. }
  5581. ff_parse_creation_time_metadata(s, &mov->time, 1);
  5582. if (mov->time)
  5583. mov->time += 0x7C25B080; // 1970 based -> 1904 based
  5584. if (mov->chapter_track)
  5585. if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  5586. return ret;
  5587. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  5588. /* Initialize the hint tracks for each audio and video stream */
  5589. for (i = 0; i < s->nb_streams; i++) {
  5590. AVStream *st = s->streams[i];
  5591. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
  5592. st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  5593. if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
  5594. return ret;
  5595. hint_track++;
  5596. }
  5597. }
  5598. }
  5599. if (mov->nb_meta_tmcd) {
  5600. /* Initialize the tmcd tracks */
  5601. for (i = 0; i < s->nb_streams; i++) {
  5602. AVStream *st = s->streams[i];
  5603. t = global_tcr;
  5604. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  5605. AVTimecode tc;
  5606. if (!t)
  5607. t = av_dict_get(st->metadata, "timecode", NULL, 0);
  5608. if (!t)
  5609. continue;
  5610. if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
  5611. continue;
  5612. if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
  5613. return ret;
  5614. tmcd_track++;
  5615. }
  5616. }
  5617. }
  5618. avio_flush(pb);
  5619. if (mov->flags & FF_MOV_FLAG_ISML)
  5620. mov_write_isml_manifest(pb, mov, s);
  5621. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
  5622. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  5623. if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
  5624. return ret;
  5625. avio_flush(pb);
  5626. mov->moov_written = 1;
  5627. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  5628. mov->reserved_header_pos = avio_tell(pb);
  5629. }
  5630. return 0;
  5631. }
  5632. static int get_moov_size(AVFormatContext *s)
  5633. {
  5634. int ret;
  5635. AVIOContext *moov_buf;
  5636. MOVMuxContext *mov = s->priv_data;
  5637. if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
  5638. return ret;
  5639. if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
  5640. return ret;
  5641. return ffio_close_null_buf(moov_buf);
  5642. }
  5643. static int get_sidx_size(AVFormatContext *s)
  5644. {
  5645. int ret;
  5646. AVIOContext *buf;
  5647. MOVMuxContext *mov = s->priv_data;
  5648. if ((ret = ffio_open_null_buf(&buf)) < 0)
  5649. return ret;
  5650. mov_write_sidx_tags(buf, mov, -1, 0);
  5651. return ffio_close_null_buf(buf);
  5652. }
  5653. /*
  5654. * This function gets the moov size if moved to the top of the file: the chunk
  5655. * offset table can switch between stco (32-bit entries) to co64 (64-bit
  5656. * entries) when the moov is moved to the beginning, so the size of the moov
  5657. * would change. It also updates the chunk offset tables.
  5658. */
  5659. static int compute_moov_size(AVFormatContext *s)
  5660. {
  5661. int i, moov_size, moov_size2;
  5662. MOVMuxContext *mov = s->priv_data;
  5663. moov_size = get_moov_size(s);
  5664. if (moov_size < 0)
  5665. return moov_size;
  5666. for (i = 0; i < mov->nb_streams; i++)
  5667. mov->tracks[i].data_offset += moov_size;
  5668. moov_size2 = get_moov_size(s);
  5669. if (moov_size2 < 0)
  5670. return moov_size2;
  5671. /* if the size changed, we just switched from stco to co64 and need to
  5672. * update the offsets */
  5673. if (moov_size2 != moov_size)
  5674. for (i = 0; i < mov->nb_streams; i++)
  5675. mov->tracks[i].data_offset += moov_size2 - moov_size;
  5676. return moov_size2;
  5677. }
  5678. static int compute_sidx_size(AVFormatContext *s)
  5679. {
  5680. int i, sidx_size;
  5681. MOVMuxContext *mov = s->priv_data;
  5682. sidx_size = get_sidx_size(s);
  5683. if (sidx_size < 0)
  5684. return sidx_size;
  5685. for (i = 0; i < mov->nb_streams; i++)
  5686. mov->tracks[i].data_offset += sidx_size;
  5687. return sidx_size;
  5688. }
  5689. static int shift_data(AVFormatContext *s)
  5690. {
  5691. int ret = 0, moov_size;
  5692. MOVMuxContext *mov = s->priv_data;
  5693. int64_t pos, pos_end = avio_tell(s->pb);
  5694. uint8_t *buf, *read_buf[2];
  5695. int read_buf_id = 0;
  5696. int read_size[2];
  5697. AVIOContext *read_pb;
  5698. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  5699. moov_size = compute_sidx_size(s);
  5700. else
  5701. moov_size = compute_moov_size(s);
  5702. if (moov_size < 0)
  5703. return moov_size;
  5704. buf = av_malloc(moov_size * 2);
  5705. if (!buf)
  5706. return AVERROR(ENOMEM);
  5707. read_buf[0] = buf;
  5708. read_buf[1] = buf + moov_size;
  5709. /* Shift the data: the AVIO context of the output can only be used for
  5710. * writing, so we re-open the same output, but for reading. It also avoids
  5711. * a read/seek/write/seek back and forth. */
  5712. avio_flush(s->pb);
  5713. ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
  5714. if (ret < 0) {
  5715. av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
  5716. "the second pass (faststart)\n", s->filename);
  5717. goto end;
  5718. }
  5719. /* mark the end of the shift to up to the last data we wrote, and get ready
  5720. * for writing */
  5721. pos_end = avio_tell(s->pb);
  5722. avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
  5723. /* start reading at where the new moov will be placed */
  5724. avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
  5725. pos = avio_tell(read_pb);
  5726. #define READ_BLOCK do { \
  5727. read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
  5728. read_buf_id ^= 1; \
  5729. } while (0)
  5730. /* shift data by chunk of at most moov_size */
  5731. READ_BLOCK;
  5732. do {
  5733. int n;
  5734. READ_BLOCK;
  5735. n = read_size[read_buf_id];
  5736. if (n <= 0)
  5737. break;
  5738. avio_write(s->pb, read_buf[read_buf_id], n);
  5739. pos += n;
  5740. } while (pos < pos_end);
  5741. ff_format_io_close(s, &read_pb);
  5742. end:
  5743. av_free(buf);
  5744. return ret;
  5745. }
  5746. static int mov_write_trailer(AVFormatContext *s)
  5747. {
  5748. MOVMuxContext *mov = s->priv_data;
  5749. AVIOContext *pb = s->pb;
  5750. int res = 0;
  5751. int i;
  5752. int64_t moov_pos;
  5753. if (mov->need_rewrite_extradata) {
  5754. for (i = 0; i < s->nb_streams; i++) {
  5755. MOVTrack *track = &mov->tracks[i];
  5756. AVCodecParameters *par = track->par;
  5757. track->vos_len = par->extradata_size;
  5758. track->vos_data = av_malloc(track->vos_len);
  5759. if (!track->vos_data)
  5760. return AVERROR(ENOMEM);
  5761. memcpy(track->vos_data, par->extradata, track->vos_len);
  5762. }
  5763. mov->need_rewrite_extradata = 0;
  5764. }
  5765. /*
  5766. * Before actually writing the trailer, make sure that there are no
  5767. * dangling subtitles, that need a terminating sample.
  5768. */
  5769. for (i = 0; i < mov->nb_streams; i++) {
  5770. MOVTrack *trk = &mov->tracks[i];
  5771. if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
  5772. !trk->last_sample_is_subtitle_end) {
  5773. mov_write_subtitle_end_packet(s, i, trk->track_duration);
  5774. trk->last_sample_is_subtitle_end = 1;
  5775. }
  5776. }
  5777. // If there were no chapters when the header was written, but there
  5778. // are chapters now, write them in the trailer. This only works
  5779. // when we are not doing fragments.
  5780. if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  5781. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
  5782. mov->chapter_track = mov->nb_streams++;
  5783. if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  5784. return res;
  5785. }
  5786. }
  5787. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  5788. moov_pos = avio_tell(pb);
  5789. /* Write size of mdat tag */
  5790. if (mov->mdat_size + 8 <= UINT32_MAX) {
  5791. avio_seek(pb, mov->mdat_pos, SEEK_SET);
  5792. avio_wb32(pb, mov->mdat_size + 8);
  5793. } else {
  5794. /* overwrite 'wide' placeholder atom */
  5795. avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
  5796. /* special value: real atom size will be 64 bit value after
  5797. * tag field */
  5798. avio_wb32(pb, 1);
  5799. ffio_wfourcc(pb, "mdat");
  5800. avio_wb64(pb, mov->mdat_size + 16);
  5801. }
  5802. avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
  5803. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  5804. av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
  5805. res = shift_data(s);
  5806. if (res < 0)
  5807. return res;
  5808. avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
  5809. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  5810. return res;
  5811. } else if (mov->reserved_moov_size > 0) {
  5812. int64_t size;
  5813. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  5814. return res;
  5815. size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
  5816. if (size < 8){
  5817. av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
  5818. return AVERROR(EINVAL);
  5819. }
  5820. avio_wb32(pb, size);
  5821. ffio_wfourcc(pb, "free");
  5822. ffio_fill(pb, 0, size - 8);
  5823. avio_seek(pb, moov_pos, SEEK_SET);
  5824. } else {
  5825. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  5826. return res;
  5827. }
  5828. res = 0;
  5829. } else {
  5830. mov_auto_flush_fragment(s, 1);
  5831. for (i = 0; i < mov->nb_streams; i++)
  5832. mov->tracks[i].data_offset = 0;
  5833. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
  5834. int64_t end;
  5835. av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
  5836. res = shift_data(s);
  5837. if (res < 0)
  5838. return res;
  5839. end = avio_tell(pb);
  5840. avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
  5841. mov_write_sidx_tags(pb, mov, -1, 0);
  5842. avio_seek(pb, end, SEEK_SET);
  5843. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
  5844. mov_write_mfra_tag(pb, mov);
  5845. } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
  5846. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
  5847. mov_write_mfra_tag(pb, mov);
  5848. }
  5849. }
  5850. return res;
  5851. }
  5852. static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
  5853. {
  5854. int ret = 1;
  5855. AVStream *st = s->streams[pkt->stream_index];
  5856. if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
  5857. if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
  5858. ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
  5859. } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
  5860. ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
  5861. }
  5862. return ret;
  5863. }
  5864. static const AVCodecTag codec_3gp_tags[] = {
  5865. { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
  5866. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  5867. { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
  5868. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  5869. { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
  5870. { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
  5871. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
  5872. { AV_CODEC_ID_NONE, 0 },
  5873. };
  5874. const AVCodecTag codec_mp4_tags[] = {
  5875. { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
  5876. { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
  5877. { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') },
  5878. { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
  5879. { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
  5880. { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
  5881. { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
  5882. { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
  5883. { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
  5884. { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
  5885. { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
  5886. { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
  5887. { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
  5888. { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
  5889. { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
  5890. { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
  5891. { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
  5892. { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
  5893. { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
  5894. { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
  5895. { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
  5896. { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
  5897. { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
  5898. { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
  5899. { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
  5900. { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
  5901. { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
  5902. { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
  5903. { AV_CODEC_ID_NONE , 0 },
  5904. };
  5905. const AVCodecTag codec_ism_tags[] = {
  5906. { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
  5907. { AV_CODEC_ID_NONE , 0 },
  5908. };
  5909. static const AVCodecTag codec_ipod_tags[] = {
  5910. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  5911. { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
  5912. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  5913. { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
  5914. { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
  5915. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
  5916. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
  5917. { AV_CODEC_ID_NONE, 0 },
  5918. };
  5919. static const AVCodecTag codec_f4v_tags[] = {
  5920. { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
  5921. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  5922. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  5923. { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
  5924. { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
  5925. { AV_CODEC_ID_NONE, 0 },
  5926. };
  5927. #if CONFIG_MOV_MUXER
  5928. MOV_CLASS(mov)
  5929. AVOutputFormat ff_mov_muxer = {
  5930. .name = "mov",
  5931. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  5932. .extensions = "mov",
  5933. .priv_data_size = sizeof(MOVMuxContext),
  5934. .audio_codec = AV_CODEC_ID_AAC,
  5935. .video_codec = CONFIG_LIBX264_ENCODER ?
  5936. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  5937. .init = mov_init,
  5938. .write_header = mov_write_header,
  5939. .write_packet = mov_write_packet,
  5940. .write_trailer = mov_write_trailer,
  5941. .deinit = mov_free,
  5942. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5943. .codec_tag = (const AVCodecTag* const []){
  5944. ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
  5945. },
  5946. .check_bitstream = mov_check_bitstream,
  5947. .priv_class = &mov_muxer_class,
  5948. };
  5949. #endif
  5950. #if CONFIG_TGP_MUXER
  5951. MOV_CLASS(tgp)
  5952. AVOutputFormat ff_tgp_muxer = {
  5953. .name = "3gp",
  5954. .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
  5955. .extensions = "3gp",
  5956. .priv_data_size = sizeof(MOVMuxContext),
  5957. .audio_codec = AV_CODEC_ID_AMR_NB,
  5958. .video_codec = AV_CODEC_ID_H263,
  5959. .init = mov_init,
  5960. .write_header = mov_write_header,
  5961. .write_packet = mov_write_packet,
  5962. .write_trailer = mov_write_trailer,
  5963. .deinit = mov_free,
  5964. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5965. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  5966. .check_bitstream = mov_check_bitstream,
  5967. .priv_class = &tgp_muxer_class,
  5968. };
  5969. #endif
  5970. #if CONFIG_MP4_MUXER
  5971. MOV_CLASS(mp4)
  5972. AVOutputFormat ff_mp4_muxer = {
  5973. .name = "mp4",
  5974. .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
  5975. .mime_type = "video/mp4",
  5976. .extensions = "mp4",
  5977. .priv_data_size = sizeof(MOVMuxContext),
  5978. .audio_codec = AV_CODEC_ID_AAC,
  5979. .video_codec = CONFIG_LIBX264_ENCODER ?
  5980. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  5981. .init = mov_init,
  5982. .write_header = mov_write_header,
  5983. .write_packet = mov_write_packet,
  5984. .write_trailer = mov_write_trailer,
  5985. .deinit = mov_free,
  5986. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5987. .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
  5988. .check_bitstream = mov_check_bitstream,
  5989. .priv_class = &mp4_muxer_class,
  5990. };
  5991. #endif
  5992. #if CONFIG_PSP_MUXER
  5993. MOV_CLASS(psp)
  5994. AVOutputFormat ff_psp_muxer = {
  5995. .name = "psp",
  5996. .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
  5997. .extensions = "mp4,psp",
  5998. .priv_data_size = sizeof(MOVMuxContext),
  5999. .audio_codec = AV_CODEC_ID_AAC,
  6000. .video_codec = CONFIG_LIBX264_ENCODER ?
  6001. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  6002. .init = mov_init,
  6003. .write_header = mov_write_header,
  6004. .write_packet = mov_write_packet,
  6005. .write_trailer = mov_write_trailer,
  6006. .deinit = mov_free,
  6007. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6008. .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
  6009. .check_bitstream = mov_check_bitstream,
  6010. .priv_class = &psp_muxer_class,
  6011. };
  6012. #endif
  6013. #if CONFIG_TG2_MUXER
  6014. MOV_CLASS(tg2)
  6015. AVOutputFormat ff_tg2_muxer = {
  6016. .name = "3g2",
  6017. .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
  6018. .extensions = "3g2",
  6019. .priv_data_size = sizeof(MOVMuxContext),
  6020. .audio_codec = AV_CODEC_ID_AMR_NB,
  6021. .video_codec = AV_CODEC_ID_H263,
  6022. .init = mov_init,
  6023. .write_header = mov_write_header,
  6024. .write_packet = mov_write_packet,
  6025. .write_trailer = mov_write_trailer,
  6026. .deinit = mov_free,
  6027. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6028. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  6029. .check_bitstream = mov_check_bitstream,
  6030. .priv_class = &tg2_muxer_class,
  6031. };
  6032. #endif
  6033. #if CONFIG_IPOD_MUXER
  6034. MOV_CLASS(ipod)
  6035. AVOutputFormat ff_ipod_muxer = {
  6036. .name = "ipod",
  6037. .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
  6038. .mime_type = "video/mp4",
  6039. .extensions = "m4v,m4a,m4b",
  6040. .priv_data_size = sizeof(MOVMuxContext),
  6041. .audio_codec = AV_CODEC_ID_AAC,
  6042. .video_codec = AV_CODEC_ID_H264,
  6043. .init = mov_init,
  6044. .write_header = mov_write_header,
  6045. .write_packet = mov_write_packet,
  6046. .write_trailer = mov_write_trailer,
  6047. .deinit = mov_free,
  6048. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6049. .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
  6050. .check_bitstream = mov_check_bitstream,
  6051. .priv_class = &ipod_muxer_class,
  6052. };
  6053. #endif
  6054. #if CONFIG_ISMV_MUXER
  6055. MOV_CLASS(ismv)
  6056. AVOutputFormat ff_ismv_muxer = {
  6057. .name = "ismv",
  6058. .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
  6059. .mime_type = "video/mp4",
  6060. .extensions = "ismv,isma",
  6061. .priv_data_size = sizeof(MOVMuxContext),
  6062. .audio_codec = AV_CODEC_ID_AAC,
  6063. .video_codec = AV_CODEC_ID_H264,
  6064. .init = mov_init,
  6065. .write_header = mov_write_header,
  6066. .write_packet = mov_write_packet,
  6067. .write_trailer = mov_write_trailer,
  6068. .deinit = mov_free,
  6069. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6070. .codec_tag = (const AVCodecTag* const []){
  6071. codec_mp4_tags, codec_ism_tags, 0 },
  6072. .check_bitstream = mov_check_bitstream,
  6073. .priv_class = &ismv_muxer_class,
  6074. };
  6075. #endif
  6076. #if CONFIG_F4V_MUXER
  6077. MOV_CLASS(f4v)
  6078. AVOutputFormat ff_f4v_muxer = {
  6079. .name = "f4v",
  6080. .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
  6081. .mime_type = "application/f4v",
  6082. .extensions = "f4v",
  6083. .priv_data_size = sizeof(MOVMuxContext),
  6084. .audio_codec = AV_CODEC_ID_AAC,
  6085. .video_codec = AV_CODEC_ID_H264,
  6086. .init = mov_init,
  6087. .write_header = mov_write_header,
  6088. .write_packet = mov_write_packet,
  6089. .write_trailer = mov_write_trailer,
  6090. .deinit = mov_free,
  6091. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
  6092. .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
  6093. .check_bitstream = mov_check_bitstream,
  6094. .priv_class = &f4v_muxer_class,
  6095. };
  6096. #endif