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.

6819 lines
247KB

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