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.

6434 lines
233KB

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