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.

6697 lines
242KB

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