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.

6531 lines
237KB

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