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.

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