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.

6729 lines
244KB

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