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.

6773 lines
245KB

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