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.

6696 lines
243KB

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