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.

5005 lines
177KB

  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/get_bits.h"
  34. #include "libavcodec/put_bits.h"
  35. #include "libavcodec/vc1_common.h"
  36. #include "libavcodec/raw.h"
  37. #include "internal.h"
  38. #include "libavutil/avstring.h"
  39. #include "libavutil/intfloat.h"
  40. #include "libavutil/mathematics.h"
  41. #include "libavutil/opt.h"
  42. #include "libavutil/dict.h"
  43. #include "libavutil/pixdesc.h"
  44. #include "libavutil/timecode.h"
  45. #include "hevc.h"
  46. #include "rtpenc.h"
  47. #include "mov_chan.h"
  48. #undef NDEBUG
  49. #include <assert.h>
  50. static const AVOption options[] = {
  51. { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  52. { "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" },
  53. { "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 },
  54. { "empty_moov", "Make the initial moov atom empty (not supported by QuickTime)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  55. { "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" },
  56. { "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" },
  57. { "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" },
  58. { "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" },
  59. { "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" },
  60. { "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" },
  61. { "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" },
  62. FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
  63. { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  64. { "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},
  65. { "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},
  66. { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
  67. { "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},
  68. { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
  69. { "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},
  70. { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
  71. { "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},
  72. { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
  73. { NULL },
  74. };
  75. #define MOV_CLASS(flavor)\
  76. static const AVClass flavor ## _muxer_class = {\
  77. .class_name = #flavor " muxer",\
  78. .item_name = av_default_item_name,\
  79. .option = options,\
  80. .version = LIBAVUTIL_VERSION_INT,\
  81. };
  82. static int get_moov_size(AVFormatContext *s);
  83. static int utf8len(const uint8_t *b)
  84. {
  85. int len = 0;
  86. int val;
  87. while (*b) {
  88. GET_UTF8(val, *b++, return -1;)
  89. len++;
  90. }
  91. return len;
  92. }
  93. //FIXME support 64 bit variant with wide placeholders
  94. static int64_t update_size(AVIOContext *pb, int64_t pos)
  95. {
  96. int64_t curpos = avio_tell(pb);
  97. avio_seek(pb, pos, SEEK_SET);
  98. avio_wb32(pb, curpos - pos); /* rewrite size */
  99. avio_seek(pb, curpos, SEEK_SET);
  100. return curpos - pos;
  101. }
  102. static int supports_edts(MOVMuxContext *mov)
  103. {
  104. // EDTS with fragments is tricky as we don't know the duration when its written
  105. // also we might end up having to write the EDTS before the first packet, which would fail
  106. return (mov->use_editlist<0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) || mov->use_editlist>0;
  107. }
  108. static int co64_required(const MOVTrack *track)
  109. {
  110. if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
  111. return 1;
  112. return 0;
  113. }
  114. /* Chunk offset atom */
  115. static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
  116. {
  117. int i;
  118. int mode64 = co64_required(track); // use 32 bit size variant if possible
  119. int64_t pos = avio_tell(pb);
  120. avio_wb32(pb, 0); /* size */
  121. if (mode64)
  122. ffio_wfourcc(pb, "co64");
  123. else
  124. ffio_wfourcc(pb, "stco");
  125. avio_wb32(pb, 0); /* version & flags */
  126. avio_wb32(pb, track->chunkCount); /* entry count */
  127. for (i = 0; i < track->entry; i++) {
  128. if (!track->cluster[i].chunkNum)
  129. continue;
  130. if (mode64 == 1)
  131. avio_wb64(pb, track->cluster[i].pos + track->data_offset);
  132. else
  133. avio_wb32(pb, track->cluster[i].pos + track->data_offset);
  134. }
  135. return update_size(pb, pos);
  136. }
  137. /* Sample size atom */
  138. static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
  139. {
  140. int equalChunks = 1;
  141. int i, j, entries = 0, tst = -1, oldtst = -1;
  142. int64_t pos = avio_tell(pb);
  143. avio_wb32(pb, 0); /* size */
  144. ffio_wfourcc(pb, "stsz");
  145. avio_wb32(pb, 0); /* version & flags */
  146. for (i = 0; i < track->entry; i++) {
  147. tst = track->cluster[i].size / track->cluster[i].entries;
  148. if (oldtst != -1 && tst != oldtst)
  149. equalChunks = 0;
  150. oldtst = tst;
  151. entries += track->cluster[i].entries;
  152. }
  153. if (equalChunks && track->entry) {
  154. int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
  155. sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
  156. avio_wb32(pb, sSize); // sample size
  157. avio_wb32(pb, entries); // sample count
  158. } else {
  159. avio_wb32(pb, 0); // sample size
  160. avio_wb32(pb, entries); // sample count
  161. for (i = 0; i < track->entry; i++) {
  162. for (j = 0; j < track->cluster[i].entries; j++) {
  163. avio_wb32(pb, track->cluster[i].size /
  164. track->cluster[i].entries);
  165. }
  166. }
  167. }
  168. return update_size(pb, pos);
  169. }
  170. /* Sample to chunk atom */
  171. static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
  172. {
  173. int index = 0, oldval = -1, i;
  174. int64_t entryPos, curpos;
  175. int64_t pos = avio_tell(pb);
  176. avio_wb32(pb, 0); /* size */
  177. ffio_wfourcc(pb, "stsc");
  178. avio_wb32(pb, 0); // version & flags
  179. entryPos = avio_tell(pb);
  180. avio_wb32(pb, track->chunkCount); // entry count
  181. for (i = 0; i < track->entry; i++) {
  182. if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
  183. avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
  184. avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
  185. avio_wb32(pb, 0x1); // sample description index
  186. oldval = track->cluster[i].samples_in_chunk;
  187. index++;
  188. }
  189. }
  190. curpos = avio_tell(pb);
  191. avio_seek(pb, entryPos, SEEK_SET);
  192. avio_wb32(pb, index); // rewrite size
  193. avio_seek(pb, curpos, SEEK_SET);
  194. return update_size(pb, pos);
  195. }
  196. /* Sync sample atom */
  197. static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
  198. {
  199. int64_t curpos, entryPos;
  200. int i, index = 0;
  201. int64_t pos = avio_tell(pb);
  202. avio_wb32(pb, 0); // size
  203. ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
  204. avio_wb32(pb, 0); // version & flags
  205. entryPos = avio_tell(pb);
  206. avio_wb32(pb, track->entry); // entry count
  207. for (i = 0; i < track->entry; i++) {
  208. if (track->cluster[i].flags & flag) {
  209. avio_wb32(pb, i + 1);
  210. index++;
  211. }
  212. }
  213. curpos = avio_tell(pb);
  214. avio_seek(pb, entryPos, SEEK_SET);
  215. avio_wb32(pb, index); // rewrite size
  216. avio_seek(pb, curpos, SEEK_SET);
  217. return update_size(pb, pos);
  218. }
  219. static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
  220. {
  221. avio_wb32(pb, 0x11); /* size */
  222. if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
  223. else ffio_wfourcc(pb, "damr");
  224. ffio_wfourcc(pb, "FFMP");
  225. avio_w8(pb, 0); /* decoder version */
  226. avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
  227. avio_w8(pb, 0x00); /* Mode change period (no restriction) */
  228. avio_w8(pb, 0x01); /* Frames per sample */
  229. return 0x11;
  230. }
  231. static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
  232. {
  233. GetBitContext gbc;
  234. PutBitContext pbc;
  235. uint8_t buf[3];
  236. int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
  237. if (track->vos_len < 7)
  238. return -1;
  239. avio_wb32(pb, 11);
  240. ffio_wfourcc(pb, "dac3");
  241. init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
  242. fscod = get_bits(&gbc, 2);
  243. frmsizecod = get_bits(&gbc, 6);
  244. bsid = get_bits(&gbc, 5);
  245. bsmod = get_bits(&gbc, 3);
  246. acmod = get_bits(&gbc, 3);
  247. if (acmod == 2) {
  248. skip_bits(&gbc, 2); // dsurmod
  249. } else {
  250. if ((acmod & 1) && acmod != 1)
  251. skip_bits(&gbc, 2); // cmixlev
  252. if (acmod & 4)
  253. skip_bits(&gbc, 2); // surmixlev
  254. }
  255. lfeon = get_bits1(&gbc);
  256. init_put_bits(&pbc, buf, sizeof(buf));
  257. put_bits(&pbc, 2, fscod);
  258. put_bits(&pbc, 5, bsid);
  259. put_bits(&pbc, 3, bsmod);
  260. put_bits(&pbc, 3, acmod);
  261. put_bits(&pbc, 1, lfeon);
  262. put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
  263. put_bits(&pbc, 5, 0); // reserved
  264. flush_put_bits(&pbc);
  265. avio_write(pb, buf, sizeof(buf));
  266. return 11;
  267. }
  268. struct eac3_info {
  269. AVPacket pkt;
  270. uint8_t ec3_done;
  271. uint8_t num_blocks;
  272. /* Layout of the EC3SpecificBox */
  273. /* maximum bitrate */
  274. uint16_t data_rate;
  275. /* number of independent substreams */
  276. uint8_t num_ind_sub;
  277. struct {
  278. /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
  279. uint8_t fscod;
  280. /* bit stream identification 5 bits */
  281. uint8_t bsid;
  282. /* one bit reserved */
  283. /* audio service mixing (not supported yet) 1 bit */
  284. /* bit stream mode 3 bits */
  285. uint8_t bsmod;
  286. /* audio coding mode 3 bits */
  287. uint8_t acmod;
  288. /* sub woofer on 1 bit */
  289. uint8_t lfeon;
  290. /* 3 bits reserved */
  291. /* number of dependent substreams associated with this substream 4 bits */
  292. uint8_t num_dep_sub;
  293. /* channel locations of the dependent substream(s), if any, 9 bits */
  294. uint16_t chan_loc;
  295. /* if there is no dependent substream, then one bit reserved instead */
  296. } substream[1]; /* TODO: support 8 independent substreams */
  297. };
  298. static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
  299. {
  300. GetBitContext gbc;
  301. AC3HeaderInfo tmp, *hdr = &tmp;
  302. struct eac3_info *info;
  303. int num_blocks;
  304. if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
  305. return AVERROR(ENOMEM);
  306. info = track->eac3_priv;
  307. init_get_bits(&gbc, pkt->data, pkt->size * 8);
  308. if (avpriv_ac3_parse_header2(&gbc, &hdr) < 0) {
  309. /* drop the packets until we see a good one */
  310. if (!track->entry) {
  311. av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
  312. return 0;
  313. }
  314. return AVERROR_INVALIDDATA;
  315. }
  316. info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
  317. num_blocks = hdr->num_blocks;
  318. if (!info->ec3_done) {
  319. /* AC-3 substream must be the first one */
  320. if (hdr->bitstream_id <= 10 && hdr->substreamid != 0)
  321. return AVERROR(EINVAL);
  322. /* this should always be the case, given that our AC-3 parser
  323. * concatenates dependent frames to their independent parent */
  324. if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
  325. /* substream ids must be incremental */
  326. if (hdr->substreamid > info->num_ind_sub + 1)
  327. return AVERROR(EINVAL);
  328. if (hdr->substreamid == info->num_ind_sub + 1) {
  329. //info->num_ind_sub++;
  330. avpriv_request_sample(track->enc, "Multiple independent substreams");
  331. return AVERROR_PATCHWELCOME;
  332. } else if (hdr->substreamid < info->num_ind_sub ||
  333. hdr->substreamid == 0 && info->substream[0].bsid) {
  334. info->ec3_done = 1;
  335. goto concatenate;
  336. }
  337. }
  338. /* fill the info needed for the "dec3" atom */
  339. info->substream[hdr->substreamid].fscod = hdr->sr_code;
  340. info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
  341. info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
  342. info->substream[hdr->substreamid].acmod = hdr->channel_mode;
  343. info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
  344. /* Parse dependent substream(s), if any */
  345. if (pkt->size != hdr->frame_size) {
  346. int cumul_size = hdr->frame_size;
  347. int parent = hdr->substreamid;
  348. while (cumul_size != pkt->size) {
  349. int i;
  350. init_get_bits(&gbc, pkt->data + cumul_size, (pkt->size - cumul_size) * 8);
  351. if (avpriv_ac3_parse_header2(&gbc, &hdr) < 0)
  352. return AVERROR_INVALIDDATA;
  353. if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT)
  354. return AVERROR(EINVAL);
  355. cumul_size += hdr->frame_size;
  356. info->substream[parent].num_dep_sub++;
  357. /* header is parsed up to lfeon, but custom channel map may be needed */
  358. /* skip bsid */
  359. skip_bits(&gbc, 5);
  360. /* skip volume control params */
  361. for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
  362. skip_bits(&gbc, 5); // skip dialog normalization
  363. if (get_bits1(&gbc)) {
  364. skip_bits(&gbc, 8); // skip compression gain word
  365. }
  366. }
  367. /* get the dependent stream channel map, if exists */
  368. if (get_bits1(&gbc))
  369. info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
  370. else
  371. info->substream[parent].chan_loc |= hdr->channel_mode;
  372. }
  373. }
  374. }
  375. concatenate:
  376. if (!info->num_blocks && num_blocks == 6)
  377. return pkt->size;
  378. else if (info->num_blocks + num_blocks > 6)
  379. return AVERROR_INVALIDDATA;
  380. if (!info->num_blocks) {
  381. int ret;
  382. if ((ret = av_copy_packet(&info->pkt, pkt)) < 0)
  383. return ret;
  384. info->num_blocks = num_blocks;
  385. return 0;
  386. } else {
  387. int ret;
  388. if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
  389. return ret;
  390. memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
  391. info->num_blocks += num_blocks;
  392. info->pkt.duration += pkt->duration;
  393. if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
  394. return ret;
  395. if (info->num_blocks != 6)
  396. return 0;
  397. av_free_packet(pkt);
  398. if ((ret = av_copy_packet(pkt, &info->pkt)) < 0)
  399. return ret;
  400. av_free_packet(&info->pkt);
  401. info->num_blocks = 0;
  402. }
  403. return pkt->size;
  404. }
  405. static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
  406. {
  407. PutBitContext pbc;
  408. uint8_t *buf;
  409. struct eac3_info *info;
  410. int size, i;
  411. if (!track->eac3_priv)
  412. return AVERROR(EINVAL);
  413. info = track->eac3_priv;
  414. size = 2 + 4 * (info->num_ind_sub + 1);
  415. buf = av_malloc(size);
  416. if (!buf) {
  417. size = AVERROR(ENOMEM);
  418. goto end;
  419. }
  420. init_put_bits(&pbc, buf, size);
  421. put_bits(&pbc, 13, info->data_rate);
  422. put_bits(&pbc, 3, info->num_ind_sub);
  423. for (i = 0; i <= info->num_ind_sub; i++) {
  424. put_bits(&pbc, 2, info->substream[i].fscod);
  425. put_bits(&pbc, 5, info->substream[i].bsid);
  426. put_bits(&pbc, 1, 0); /* reserved */
  427. put_bits(&pbc, 1, 0); /* asvc */
  428. put_bits(&pbc, 3, info->substream[i].bsmod);
  429. put_bits(&pbc, 3, info->substream[i].acmod);
  430. put_bits(&pbc, 1, info->substream[i].lfeon);
  431. put_bits(&pbc, 5, 0); /* reserved */
  432. put_bits(&pbc, 4, info->substream[i].num_dep_sub);
  433. if (!info->substream[i].num_dep_sub) {
  434. put_bits(&pbc, 1, 0); /* reserved */
  435. size--;
  436. } else {
  437. put_bits(&pbc, 9, info->substream[i].chan_loc);
  438. }
  439. }
  440. flush_put_bits(&pbc);
  441. avio_wb32(pb, size + 8);
  442. ffio_wfourcc(pb, "dec3");
  443. avio_write(pb, buf, size);
  444. av_free(buf);
  445. end:
  446. av_free_packet(&info->pkt);
  447. av_freep(&track->eac3_priv);
  448. return size;
  449. }
  450. /**
  451. * This function writes extradata "as is".
  452. * Extradata must be formatted like a valid atom (with size and tag).
  453. */
  454. static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
  455. {
  456. avio_write(pb, track->enc->extradata, track->enc->extradata_size);
  457. return track->enc->extradata_size;
  458. }
  459. static int mov_write_enda_tag(AVIOContext *pb)
  460. {
  461. avio_wb32(pb, 10);
  462. ffio_wfourcc(pb, "enda");
  463. avio_wb16(pb, 1); /* little endian */
  464. return 10;
  465. }
  466. static int mov_write_enda_tag_be(AVIOContext *pb)
  467. {
  468. avio_wb32(pb, 10);
  469. ffio_wfourcc(pb, "enda");
  470. avio_wb16(pb, 0); /* big endian */
  471. return 10;
  472. }
  473. static void put_descr(AVIOContext *pb, int tag, unsigned int size)
  474. {
  475. int i = 3;
  476. avio_w8(pb, tag);
  477. for (; i > 0; i--)
  478. avio_w8(pb, (size >> (7 * i)) | 0x80);
  479. avio_w8(pb, size & 0x7F);
  480. }
  481. static unsigned compute_avg_bitrate(MOVTrack *track)
  482. {
  483. uint64_t size = 0;
  484. int i;
  485. if (!track->track_duration)
  486. return 0;
  487. for (i = 0; i < track->entry; i++)
  488. size += track->cluster[i].size;
  489. return size * 8 * track->timescale / track->track_duration;
  490. }
  491. static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
  492. {
  493. int64_t pos = avio_tell(pb);
  494. int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
  495. unsigned avg_bitrate;
  496. avio_wb32(pb, 0); // size
  497. ffio_wfourcc(pb, "esds");
  498. avio_wb32(pb, 0); // Version
  499. // ES descriptor
  500. put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
  501. avio_wb16(pb, track->track_id);
  502. avio_w8(pb, 0x00); // flags (= no flags)
  503. // DecoderConfig descriptor
  504. put_descr(pb, 0x04, 13 + decoder_specific_info_len);
  505. // Object type indication
  506. if ((track->enc->codec_id == AV_CODEC_ID_MP2 ||
  507. track->enc->codec_id == AV_CODEC_ID_MP3) &&
  508. track->enc->sample_rate > 24000)
  509. avio_w8(pb, 0x6B); // 11172-3
  510. else
  511. avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id));
  512. // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
  513. // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
  514. if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  515. avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
  516. else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
  517. avio_w8(pb, 0x15); // flags (= Audiostream)
  518. else
  519. avio_w8(pb, 0x11); // flags (= Visualstream)
  520. avio_wb24(pb, track->enc->rc_buffer_size >> 3); // Buffersize DB
  521. avg_bitrate = compute_avg_bitrate(track);
  522. // maxbitrate (FIXME should be max rate in any 1 sec window)
  523. avio_wb32(pb, FFMAX3(track->enc->bit_rate, track->enc->rc_max_rate, avg_bitrate));
  524. avio_wb32(pb, avg_bitrate);
  525. if (track->vos_len) {
  526. // DecoderSpecific info descriptor
  527. put_descr(pb, 0x05, track->vos_len);
  528. avio_write(pb, track->vos_data, track->vos_len);
  529. }
  530. // SL descriptor
  531. put_descr(pb, 0x06, 1);
  532. avio_w8(pb, 0x02);
  533. return update_size(pb, pos);
  534. }
  535. static int mov_pcm_le_gt16(enum AVCodecID codec_id)
  536. {
  537. return codec_id == AV_CODEC_ID_PCM_S24LE ||
  538. codec_id == AV_CODEC_ID_PCM_S32LE ||
  539. codec_id == AV_CODEC_ID_PCM_F32LE ||
  540. codec_id == AV_CODEC_ID_PCM_F64LE;
  541. }
  542. static int mov_pcm_be_gt16(enum AVCodecID codec_id)
  543. {
  544. return codec_id == AV_CODEC_ID_PCM_S24BE ||
  545. codec_id == AV_CODEC_ID_PCM_S32BE ||
  546. codec_id == AV_CODEC_ID_PCM_F32BE ||
  547. codec_id == AV_CODEC_ID_PCM_F64BE;
  548. }
  549. static int mov_write_ms_tag(AVIOContext *pb, MOVTrack *track)
  550. {
  551. int ret;
  552. int64_t pos = avio_tell(pb);
  553. avio_wb32(pb, 0);
  554. avio_wl32(pb, track->tag); // store it byteswapped
  555. track->enc->codec_tag = av_bswap16(track->tag >> 16);
  556. if ((ret = ff_put_wav_header(pb, track->enc, 0)) < 0)
  557. return ret;
  558. return update_size(pb, pos);
  559. }
  560. static int mov_write_wfex_tag(AVIOContext *pb, MOVTrack *track)
  561. {
  562. int ret;
  563. int64_t pos = avio_tell(pb);
  564. avio_wb32(pb, 0);
  565. ffio_wfourcc(pb, "wfex");
  566. if ((ret = ff_put_wav_header(pb, track->enc, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
  567. return ret;
  568. return update_size(pb, pos);
  569. }
  570. static int mov_write_chan_tag(AVIOContext *pb, MOVTrack *track)
  571. {
  572. uint32_t layout_tag, bitmap;
  573. int64_t pos = avio_tell(pb);
  574. layout_tag = ff_mov_get_channel_layout_tag(track->enc->codec_id,
  575. track->enc->channel_layout,
  576. &bitmap);
  577. if (!layout_tag) {
  578. av_log(track->enc, AV_LOG_WARNING, "not writing 'chan' tag due to "
  579. "lack of channel information\n");
  580. return 0;
  581. }
  582. if (track->multichannel_as_mono)
  583. return 0;
  584. avio_wb32(pb, 0); // Size
  585. ffio_wfourcc(pb, "chan"); // Type
  586. avio_w8(pb, 0); // Version
  587. avio_wb24(pb, 0); // Flags
  588. avio_wb32(pb, layout_tag); // mChannelLayoutTag
  589. avio_wb32(pb, bitmap); // mChannelBitmap
  590. avio_wb32(pb, 0); // mNumberChannelDescriptions
  591. return update_size(pb, pos);
  592. }
  593. static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)
  594. {
  595. int64_t pos = avio_tell(pb);
  596. avio_wb32(pb, 0); /* size */
  597. ffio_wfourcc(pb, "wave");
  598. if (track->enc->codec_id != AV_CODEC_ID_QDM2) {
  599. avio_wb32(pb, 12); /* size */
  600. ffio_wfourcc(pb, "frma");
  601. avio_wl32(pb, track->tag);
  602. }
  603. if (track->enc->codec_id == AV_CODEC_ID_AAC) {
  604. /* useless atom needed by mplayer, ipod, not needed by quicktime */
  605. avio_wb32(pb, 12); /* size */
  606. ffio_wfourcc(pb, "mp4a");
  607. avio_wb32(pb, 0);
  608. mov_write_esds_tag(pb, track);
  609. } else if (mov_pcm_le_gt16(track->enc->codec_id)) {
  610. mov_write_enda_tag(pb);
  611. } else if (mov_pcm_be_gt16(track->enc->codec_id)) {
  612. mov_write_enda_tag_be(pb);
  613. } else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB) {
  614. mov_write_amr_tag(pb, track);
  615. } else if (track->enc->codec_id == AV_CODEC_ID_AC3) {
  616. mov_write_ac3_tag(pb, track);
  617. } else if (track->enc->codec_id == AV_CODEC_ID_EAC3) {
  618. mov_write_eac3_tag(pb, track);
  619. } else if (track->enc->codec_id == AV_CODEC_ID_ALAC ||
  620. track->enc->codec_id == AV_CODEC_ID_QDM2) {
  621. mov_write_extradata_tag(pb, track);
  622. } else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
  623. track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
  624. mov_write_ms_tag(pb, track);
  625. }
  626. avio_wb32(pb, 8); /* size */
  627. avio_wb32(pb, 0); /* null tag */
  628. return update_size(pb, pos);
  629. }
  630. static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
  631. {
  632. uint8_t *unescaped;
  633. const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
  634. int unescaped_size, seq_found = 0;
  635. int level = 0, interlace = 0;
  636. int packet_seq = track->vc1_info.packet_seq;
  637. int packet_entry = track->vc1_info.packet_entry;
  638. int slices = track->vc1_info.slices;
  639. PutBitContext pbc;
  640. if (track->start_dts == AV_NOPTS_VALUE) {
  641. /* No packets written yet, vc1_info isn't authoritative yet. */
  642. /* Assume inline sequence and entry headers. This will be
  643. * overwritten at the end if the file is seekable. */
  644. packet_seq = packet_entry = 1;
  645. }
  646. unescaped = av_mallocz(track->vos_len + FF_INPUT_BUFFER_PADDING_SIZE);
  647. if (!unescaped)
  648. return AVERROR(ENOMEM);
  649. start = find_next_marker(track->vos_data, end);
  650. for (next = start; next < end; start = next) {
  651. GetBitContext gb;
  652. int size;
  653. next = find_next_marker(start + 4, end);
  654. size = next - start - 4;
  655. if (size <= 0)
  656. continue;
  657. unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
  658. init_get_bits(&gb, unescaped, 8 * unescaped_size);
  659. if (AV_RB32(start) == VC1_CODE_SEQHDR) {
  660. int profile = get_bits(&gb, 2);
  661. if (profile != PROFILE_ADVANCED) {
  662. av_free(unescaped);
  663. return AVERROR(ENOSYS);
  664. }
  665. seq_found = 1;
  666. level = get_bits(&gb, 3);
  667. /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
  668. * width, height */
  669. skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
  670. skip_bits(&gb, 1); /* broadcast */
  671. interlace = get_bits1(&gb);
  672. skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
  673. }
  674. }
  675. if (!seq_found) {
  676. av_free(unescaped);
  677. return AVERROR(ENOSYS);
  678. }
  679. init_put_bits(&pbc, buf, 7);
  680. /* VC1DecSpecStruc */
  681. put_bits(&pbc, 4, 12); /* profile - advanced */
  682. put_bits(&pbc, 3, level);
  683. put_bits(&pbc, 1, 0); /* reserved */
  684. /* VC1AdvDecSpecStruc */
  685. put_bits(&pbc, 3, level);
  686. put_bits(&pbc, 1, 0); /* cbr */
  687. put_bits(&pbc, 6, 0); /* reserved */
  688. put_bits(&pbc, 1, !interlace); /* no interlace */
  689. put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
  690. put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
  691. put_bits(&pbc, 1, !slices); /* no slice code */
  692. put_bits(&pbc, 1, 0); /* no bframe */
  693. put_bits(&pbc, 1, 0); /* reserved */
  694. /* framerate */
  695. if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
  696. put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
  697. else
  698. put_bits32(&pbc, 0xffffffff);
  699. flush_put_bits(&pbc);
  700. av_free(unescaped);
  701. return 0;
  702. }
  703. static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
  704. {
  705. uint8_t buf[7] = { 0 };
  706. int ret;
  707. if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
  708. return ret;
  709. avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
  710. ffio_wfourcc(pb, "dvc1");
  711. track->vc1_info.struct_offset = avio_tell(pb);
  712. avio_write(pb, buf, sizeof(buf));
  713. avio_write(pb, track->vos_data, track->vos_len);
  714. return 0;
  715. }
  716. static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
  717. {
  718. avio_wb32(pb, track->vos_len + 8);
  719. ffio_wfourcc(pb, "glbl");
  720. avio_write(pb, track->vos_data, track->vos_len);
  721. return 8 + track->vos_len;
  722. }
  723. /**
  724. * Compute flags for 'lpcm' tag.
  725. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  726. */
  727. static int mov_get_lpcm_flags(enum AVCodecID codec_id)
  728. {
  729. switch (codec_id) {
  730. case AV_CODEC_ID_PCM_F32BE:
  731. case AV_CODEC_ID_PCM_F64BE:
  732. return 11;
  733. case AV_CODEC_ID_PCM_F32LE:
  734. case AV_CODEC_ID_PCM_F64LE:
  735. return 9;
  736. case AV_CODEC_ID_PCM_U8:
  737. return 10;
  738. case AV_CODEC_ID_PCM_S16BE:
  739. case AV_CODEC_ID_PCM_S24BE:
  740. case AV_CODEC_ID_PCM_S32BE:
  741. return 14;
  742. case AV_CODEC_ID_PCM_S8:
  743. case AV_CODEC_ID_PCM_S16LE:
  744. case AV_CODEC_ID_PCM_S24LE:
  745. case AV_CODEC_ID_PCM_S32LE:
  746. return 12;
  747. default:
  748. return 0;
  749. }
  750. }
  751. static int get_cluster_duration(MOVTrack *track, int cluster_idx)
  752. {
  753. int64_t next_dts;
  754. if (cluster_idx >= track->entry)
  755. return 0;
  756. if (cluster_idx + 1 == track->entry)
  757. next_dts = track->track_duration + track->start_dts;
  758. else
  759. next_dts = track->cluster[cluster_idx + 1].dts;
  760. next_dts -= track->cluster[cluster_idx].dts;
  761. av_assert0(next_dts >= 0);
  762. av_assert0(next_dts <= INT_MAX);
  763. return next_dts;
  764. }
  765. static int get_samples_per_packet(MOVTrack *track)
  766. {
  767. int i, first_duration;
  768. // return track->enc->frame_size;
  769. /* use 1 for raw PCM */
  770. if (!track->audio_vbr)
  771. return 1;
  772. /* check to see if duration is constant for all clusters */
  773. if (!track->entry)
  774. return 0;
  775. first_duration = get_cluster_duration(track, 0);
  776. for (i = 1; i < track->entry; i++) {
  777. if (get_cluster_duration(track, i) != first_duration)
  778. return 0;
  779. }
  780. return first_duration;
  781. }
  782. static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)
  783. {
  784. int64_t pos = avio_tell(pb);
  785. int version = 0;
  786. uint32_t tag = track->tag;
  787. if (track->mode == MODE_MOV) {
  788. if (track->timescale > UINT16_MAX) {
  789. if (mov_get_lpcm_flags(track->enc->codec_id))
  790. tag = AV_RL32("lpcm");
  791. version = 2;
  792. } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||
  793. mov_pcm_be_gt16(track->enc->codec_id) ||
  794. track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
  795. track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  796. track->enc->codec_id == AV_CODEC_ID_QDM2) {
  797. version = 1;
  798. }
  799. }
  800. avio_wb32(pb, 0); /* size */
  801. avio_wl32(pb, tag); // store it byteswapped
  802. avio_wb32(pb, 0); /* Reserved */
  803. avio_wb16(pb, 0); /* Reserved */
  804. avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
  805. /* SoundDescription */
  806. avio_wb16(pb, version); /* Version */
  807. avio_wb16(pb, 0); /* Revision level */
  808. avio_wb32(pb, 0); /* Reserved */
  809. if (version == 2) {
  810. avio_wb16(pb, 3);
  811. avio_wb16(pb, 16);
  812. avio_wb16(pb, 0xfffe);
  813. avio_wb16(pb, 0);
  814. avio_wb32(pb, 0x00010000);
  815. avio_wb32(pb, 72);
  816. avio_wb64(pb, av_double2int(track->enc->sample_rate));
  817. avio_wb32(pb, track->enc->channels);
  818. avio_wb32(pb, 0x7F000000);
  819. avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));
  820. avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));
  821. avio_wb32(pb, track->sample_size);
  822. avio_wb32(pb, get_samples_per_packet(track));
  823. } else {
  824. if (track->mode == MODE_MOV) {
  825. avio_wb16(pb, track->enc->channels);
  826. if (track->enc->codec_id == AV_CODEC_ID_PCM_U8 ||
  827. track->enc->codec_id == AV_CODEC_ID_PCM_S8)
  828. avio_wb16(pb, 8); /* bits per sample */
  829. else
  830. avio_wb16(pb, 16);
  831. avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
  832. } else { /* reserved for mp4/3gp */
  833. avio_wb16(pb, 2);
  834. avio_wb16(pb, 16);
  835. avio_wb16(pb, 0);
  836. }
  837. avio_wb16(pb, 0); /* packet size (= 0) */
  838. avio_wb16(pb, track->enc->sample_rate <= UINT16_MAX ?
  839. track->enc->sample_rate : 0);
  840. avio_wb16(pb, 0); /* Reserved */
  841. }
  842. if (version == 1) { /* SoundDescription V1 extended info */
  843. if (mov_pcm_le_gt16(track->enc->codec_id) ||
  844. mov_pcm_be_gt16(track->enc->codec_id))
  845. avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
  846. else
  847. avio_wb32(pb, track->enc->frame_size); /* Samples per packet */
  848. avio_wb32(pb, track->sample_size / track->enc->channels); /* Bytes per packet */
  849. avio_wb32(pb, track->sample_size); /* Bytes per frame */
  850. avio_wb32(pb, 2); /* Bytes per sample */
  851. }
  852. if (track->mode == MODE_MOV &&
  853. (track->enc->codec_id == AV_CODEC_ID_AAC ||
  854. track->enc->codec_id == AV_CODEC_ID_AC3 ||
  855. track->enc->codec_id == AV_CODEC_ID_EAC3 ||
  856. track->enc->codec_id == AV_CODEC_ID_AMR_NB ||
  857. track->enc->codec_id == AV_CODEC_ID_ALAC ||
  858. track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
  859. track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  860. track->enc->codec_id == AV_CODEC_ID_QDM2 ||
  861. (mov_pcm_le_gt16(track->enc->codec_id) && version==1) ||
  862. (mov_pcm_be_gt16(track->enc->codec_id) && version==1)))
  863. mov_write_wave_tag(pb, track);
  864. else if (track->tag == MKTAG('m','p','4','a'))
  865. mov_write_esds_tag(pb, track);
  866. else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB)
  867. mov_write_amr_tag(pb, track);
  868. else if (track->enc->codec_id == AV_CODEC_ID_AC3)
  869. mov_write_ac3_tag(pb, track);
  870. else if (track->enc->codec_id == AV_CODEC_ID_EAC3)
  871. mov_write_eac3_tag(pb, track);
  872. else if (track->enc->codec_id == AV_CODEC_ID_ALAC)
  873. mov_write_extradata_tag(pb, track);
  874. else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO)
  875. mov_write_wfex_tag(pb, track);
  876. else if (track->vos_len > 0)
  877. mov_write_glbl_tag(pb, track);
  878. if (track->mode == MODE_MOV && track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
  879. mov_write_chan_tag(pb, track);
  880. return update_size(pb, pos);
  881. }
  882. static int mov_write_d263_tag(AVIOContext *pb)
  883. {
  884. avio_wb32(pb, 0xf); /* size */
  885. ffio_wfourcc(pb, "d263");
  886. ffio_wfourcc(pb, "FFMP");
  887. avio_w8(pb, 0); /* decoder version */
  888. /* FIXME use AVCodecContext level/profile, when encoder will set values */
  889. avio_w8(pb, 0xa); /* level */
  890. avio_w8(pb, 0); /* profile */
  891. return 0xf;
  892. }
  893. static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
  894. {
  895. int64_t pos = avio_tell(pb);
  896. avio_wb32(pb, 0);
  897. ffio_wfourcc(pb, "avcC");
  898. ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
  899. return update_size(pb, pos);
  900. }
  901. static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
  902. {
  903. int64_t pos = avio_tell(pb);
  904. avio_wb32(pb, 0);
  905. ffio_wfourcc(pb, "hvcC");
  906. ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
  907. return update_size(pb, pos);
  908. }
  909. /* also used by all avid codecs (dv, imx, meridien) and their variants */
  910. static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
  911. {
  912. int i;
  913. avio_wb32(pb, 24); /* size */
  914. ffio_wfourcc(pb, "ACLR");
  915. ffio_wfourcc(pb, "ACLR");
  916. ffio_wfourcc(pb, "0001");
  917. if (track->enc->color_range == AVCOL_RANGE_MPEG) { /* Legal range (16-235) */
  918. avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
  919. } else { /* Full range (0-255) */
  920. avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
  921. }
  922. avio_wb32(pb, 0); /* unknown */
  923. avio_wb32(pb, 24); /* size */
  924. ffio_wfourcc(pb, "APRG");
  925. ffio_wfourcc(pb, "APRG");
  926. ffio_wfourcc(pb, "0001");
  927. avio_wb32(pb, 1); /* unknown */
  928. avio_wb32(pb, 0); /* unknown */
  929. avio_wb32(pb, 120); /* size */
  930. ffio_wfourcc(pb, "ARES");
  931. ffio_wfourcc(pb, "ARES");
  932. ffio_wfourcc(pb, "0001");
  933. avio_wb32(pb, AV_RB32(track->vos_data + 0x28)); /* dnxhd cid, some id ? */
  934. avio_wb32(pb, track->enc->width);
  935. /* values below are based on samples created with quicktime and avid codecs */
  936. if (track->vos_data[5] & 2) { // interlaced
  937. avio_wb32(pb, track->enc->height / 2);
  938. avio_wb32(pb, 2); /* unknown */
  939. avio_wb32(pb, 0); /* unknown */
  940. avio_wb32(pb, 4); /* unknown */
  941. } else {
  942. avio_wb32(pb, track->enc->height);
  943. avio_wb32(pb, 1); /* unknown */
  944. avio_wb32(pb, 0); /* unknown */
  945. if (track->enc->height == 1080)
  946. avio_wb32(pb, 5); /* unknown */
  947. else
  948. avio_wb32(pb, 6); /* unknown */
  949. }
  950. /* padding */
  951. for (i = 0; i < 10; i++)
  952. avio_wb64(pb, 0);
  953. /* extra padding for stsd needed */
  954. avio_wb32(pb, 0);
  955. return 0;
  956. }
  957. static int mp4_get_codec_tag(AVFormatContext *s, MOVTrack *track)
  958. {
  959. int tag = track->enc->codec_tag;
  960. if (!ff_codec_get_tag(ff_mp4_obj_type, track->enc->codec_id))
  961. return 0;
  962. if (track->enc->codec_id == AV_CODEC_ID_H264) tag = MKTAG('a','v','c','1');
  963. else if (track->enc->codec_id == AV_CODEC_ID_HEVC) tag = MKTAG('h','e','v','1');
  964. else if (track->enc->codec_id == AV_CODEC_ID_AC3) tag = MKTAG('a','c','-','3');
  965. else if (track->enc->codec_id == AV_CODEC_ID_EAC3) tag = MKTAG('e','c','-','3');
  966. else if (track->enc->codec_id == AV_CODEC_ID_DIRAC) tag = MKTAG('d','r','a','c');
  967. else if (track->enc->codec_id == AV_CODEC_ID_MOV_TEXT) tag = MKTAG('t','x','3','g');
  968. else if (track->enc->codec_id == AV_CODEC_ID_VC1) tag = MKTAG('v','c','-','1');
  969. else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) tag = MKTAG('m','p','4','v');
  970. else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) tag = MKTAG('m','p','4','a');
  971. else if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE) tag = MKTAG('m','p','4','s');
  972. return tag;
  973. }
  974. static const AVCodecTag codec_ipod_tags[] = {
  975. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  976. { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
  977. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  978. { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
  979. { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
  980. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
  981. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
  982. { AV_CODEC_ID_NONE, 0 },
  983. };
  984. static int ipod_get_codec_tag(AVFormatContext *s, MOVTrack *track)
  985. {
  986. int tag = track->enc->codec_tag;
  987. // keep original tag for subs, ipod supports both formats
  988. if (!(track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  989. (tag == MKTAG('t', 'x', '3', 'g') ||
  990. tag == MKTAG('t', 'e', 'x', 't'))))
  991. tag = ff_codec_get_tag(codec_ipod_tags, track->enc->codec_id);
  992. if (!av_match_ext(s->filename, "m4a") &&
  993. !av_match_ext(s->filename, "m4b") &&
  994. !av_match_ext(s->filename, "m4v"))
  995. av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a, .m4v nor .m4b "
  996. "Quicktime/Ipod might not play the file\n");
  997. return tag;
  998. }
  999. static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
  1000. {
  1001. int tag;
  1002. if (track->enc->width == 720) { /* SD */
  1003. if (track->enc->height == 480) { /* NTSC */
  1004. if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
  1005. else tag = MKTAG('d','v','c',' ');
  1006. }else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
  1007. else if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
  1008. else tag = MKTAG('d','v','p','p');
  1009. } else if (track->enc->height == 720) { /* HD 720 line */
  1010. if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
  1011. else tag = MKTAG('d','v','h','p');
  1012. } else if (track->enc->height == 1080) { /* HD 1080 line */
  1013. if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
  1014. else tag = MKTAG('d','v','h','6');
  1015. } else {
  1016. av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
  1017. return 0;
  1018. }
  1019. return tag;
  1020. }
  1021. static AVRational find_fps(AVFormatContext *s, AVStream *st)
  1022. {
  1023. AVRational rate = {st->codec->time_base.den, st->codec->time_base.num};
  1024. /* if the codec time base makes no sense, try to fallback on stream frame rate */
  1025. if (av_timecode_check_frame_rate(rate) < 0) {
  1026. av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
  1027. rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
  1028. rate = st->avg_frame_rate;
  1029. }
  1030. return rate;
  1031. }
  1032. static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
  1033. {
  1034. int tag = track->enc->codec_tag;
  1035. int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
  1036. AVStream *st = track->st;
  1037. int rate = av_q2d(find_fps(s, st));
  1038. if (!tag)
  1039. tag = MKTAG('m', '2', 'v', '1'); //fallback tag
  1040. if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P) {
  1041. if (track->enc->width == 1280 && track->enc->height == 720) {
  1042. if (!interlaced) {
  1043. if (rate == 24) tag = MKTAG('x','d','v','4');
  1044. else if (rate == 25) tag = MKTAG('x','d','v','5');
  1045. else if (rate == 30) tag = MKTAG('x','d','v','1');
  1046. else if (rate == 50) tag = MKTAG('x','d','v','a');
  1047. else if (rate == 60) tag = MKTAG('x','d','v','9');
  1048. }
  1049. } else if (track->enc->width == 1440 && track->enc->height == 1080) {
  1050. if (!interlaced) {
  1051. if (rate == 24) tag = MKTAG('x','d','v','6');
  1052. else if (rate == 25) tag = MKTAG('x','d','v','7');
  1053. else if (rate == 30) tag = MKTAG('x','d','v','8');
  1054. } else {
  1055. if (rate == 25) tag = MKTAG('x','d','v','3');
  1056. else if (rate == 30) tag = MKTAG('x','d','v','2');
  1057. }
  1058. } else if (track->enc->width == 1920 && track->enc->height == 1080) {
  1059. if (!interlaced) {
  1060. if (rate == 24) tag = MKTAG('x','d','v','d');
  1061. else if (rate == 25) tag = MKTAG('x','d','v','e');
  1062. else if (rate == 30) tag = MKTAG('x','d','v','f');
  1063. } else {
  1064. if (rate == 25) tag = MKTAG('x','d','v','c');
  1065. else if (rate == 30) tag = MKTAG('x','d','v','b');
  1066. }
  1067. }
  1068. } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
  1069. if (track->enc->width == 1280 && track->enc->height == 720) {
  1070. if (!interlaced) {
  1071. if (rate == 24) tag = MKTAG('x','d','5','4');
  1072. else if (rate == 25) tag = MKTAG('x','d','5','5');
  1073. else if (rate == 30) tag = MKTAG('x','d','5','1');
  1074. else if (rate == 50) tag = MKTAG('x','d','5','a');
  1075. else if (rate == 60) tag = MKTAG('x','d','5','9');
  1076. }
  1077. } else if (track->enc->width == 1920 && track->enc->height == 1080) {
  1078. if (!interlaced) {
  1079. if (rate == 24) tag = MKTAG('x','d','5','d');
  1080. else if (rate == 25) tag = MKTAG('x','d','5','e');
  1081. else if (rate == 30) tag = MKTAG('x','d','5','f');
  1082. } else {
  1083. if (rate == 25) tag = MKTAG('x','d','5','c');
  1084. else if (rate == 30) tag = MKTAG('x','d','5','b');
  1085. }
  1086. }
  1087. }
  1088. return tag;
  1089. }
  1090. static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
  1091. {
  1092. int tag = track->enc->codec_tag;
  1093. int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
  1094. AVStream *st = track->st;
  1095. int rate = av_q2d(find_fps(s, st));
  1096. if (!tag)
  1097. tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
  1098. if (track->enc->pix_fmt == AV_PIX_FMT_YUV420P10) {
  1099. if (track->enc->width == 960 && track->enc->height == 720) {
  1100. if (!interlaced) {
  1101. if (rate == 24) tag = MKTAG('a','i','5','p');
  1102. else if (rate == 25) tag = MKTAG('a','i','5','q');
  1103. else if (rate == 30) tag = MKTAG('a','i','5','p');
  1104. else if (rate == 50) tag = MKTAG('a','i','5','q');
  1105. else if (rate == 60) tag = MKTAG('a','i','5','p');
  1106. }
  1107. } else if (track->enc->width == 1440 && track->enc->height == 1080) {
  1108. if (!interlaced) {
  1109. if (rate == 24) tag = MKTAG('a','i','5','3');
  1110. else if (rate == 25) tag = MKTAG('a','i','5','2');
  1111. else if (rate == 30) tag = MKTAG('a','i','5','3');
  1112. } else {
  1113. if (rate == 50) tag = MKTAG('a','i','5','5');
  1114. else if (rate == 60) tag = MKTAG('a','i','5','6');
  1115. }
  1116. }
  1117. } else if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P10) {
  1118. if (track->enc->width == 1280 && track->enc->height == 720) {
  1119. if (!interlaced) {
  1120. if (rate == 24) tag = MKTAG('a','i','1','p');
  1121. else if (rate == 25) tag = MKTAG('a','i','1','q');
  1122. else if (rate == 30) tag = MKTAG('a','i','1','p');
  1123. else if (rate == 50) tag = MKTAG('a','i','1','q');
  1124. else if (rate == 60) tag = MKTAG('a','i','1','p');
  1125. }
  1126. } else if (track->enc->width == 1920 && track->enc->height == 1080) {
  1127. if (!interlaced) {
  1128. if (rate == 24) tag = MKTAG('a','i','1','3');
  1129. else if (rate == 25) tag = MKTAG('a','i','1','2');
  1130. else if (rate == 30) tag = MKTAG('a','i','1','3');
  1131. } else {
  1132. if (rate == 25) tag = MKTAG('a','i','1','5');
  1133. else if (rate == 50) tag = MKTAG('a','i','1','5');
  1134. else if (rate == 60) tag = MKTAG('a','i','1','6');
  1135. }
  1136. }
  1137. }
  1138. return tag;
  1139. }
  1140. static const struct {
  1141. enum AVPixelFormat pix_fmt;
  1142. uint32_t tag;
  1143. unsigned bps;
  1144. } mov_pix_fmt_tags[] = {
  1145. { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
  1146. { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
  1147. { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
  1148. { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
  1149. { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
  1150. { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
  1151. { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
  1152. { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
  1153. { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
  1154. { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
  1155. { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
  1156. { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
  1157. { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
  1158. { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
  1159. { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
  1160. };
  1161. static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
  1162. {
  1163. int tag = track->enc->codec_tag;
  1164. int i;
  1165. enum AVPixelFormat pix_fmt;
  1166. for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
  1167. if (track->enc->pix_fmt == mov_pix_fmt_tags[i].pix_fmt) {
  1168. tag = mov_pix_fmt_tags[i].tag;
  1169. track->enc->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
  1170. if (track->enc->codec_tag == mov_pix_fmt_tags[i].tag)
  1171. break;
  1172. }
  1173. }
  1174. pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
  1175. track->enc->bits_per_coded_sample);
  1176. if (tag == MKTAG('r','a','w',' ') &&
  1177. track->enc->pix_fmt != pix_fmt &&
  1178. track->enc->pix_fmt != AV_PIX_FMT_NONE)
  1179. av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
  1180. av_get_pix_fmt_name(track->enc->pix_fmt));
  1181. return tag;
  1182. }
  1183. static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
  1184. {
  1185. int tag = track->enc->codec_tag;
  1186. if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
  1187. (track->enc->codec_id == AV_CODEC_ID_DVVIDEO ||
  1188. track->enc->codec_id == AV_CODEC_ID_RAWVIDEO ||
  1189. track->enc->codec_id == AV_CODEC_ID_H263 ||
  1190. track->enc->codec_id == AV_CODEC_ID_H264 ||
  1191. track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
  1192. av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio
  1193. if (track->enc->codec_id == AV_CODEC_ID_DVVIDEO)
  1194. tag = mov_get_dv_codec_tag(s, track);
  1195. else if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO)
  1196. tag = mov_get_rawvideo_codec_tag(s, track);
  1197. else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO)
  1198. tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
  1199. else if (track->enc->codec_id == AV_CODEC_ID_H264)
  1200. tag = mov_get_h264_codec_tag(s, track);
  1201. else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1202. tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->enc->codec_id);
  1203. if (!tag) { // if no mac fcc found, try with Microsoft tags
  1204. tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
  1205. if (tag)
  1206. av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
  1207. "the file may be unplayable!\n");
  1208. }
  1209. } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
  1210. tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->enc->codec_id);
  1211. if (!tag) { // if no mac fcc found, try with Microsoft tags
  1212. int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
  1213. if (ms_tag) {
  1214. tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
  1215. av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
  1216. "the file may be unplayable!\n");
  1217. }
  1218. }
  1219. } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
  1220. tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
  1221. }
  1222. return tag;
  1223. }
  1224. static const AVCodecTag codec_3gp_tags[] = {
  1225. { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
  1226. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  1227. { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
  1228. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  1229. { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
  1230. { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
  1231. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
  1232. { AV_CODEC_ID_NONE, 0 },
  1233. };
  1234. static const AVCodecTag codec_f4v_tags[] = { // XXX: add GIF/PNG/JPEG?
  1235. { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
  1236. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  1237. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  1238. { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
  1239. { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
  1240. { AV_CODEC_ID_NONE, 0 },
  1241. };
  1242. static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
  1243. {
  1244. int tag;
  1245. if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
  1246. tag = mp4_get_codec_tag(s, track);
  1247. else if (track->mode == MODE_ISM) {
  1248. tag = mp4_get_codec_tag(s, track);
  1249. if (!tag && track->enc->codec_id == AV_CODEC_ID_WMAPRO)
  1250. tag = MKTAG('w', 'm', 'a', ' ');
  1251. } else if (track->mode == MODE_IPOD)
  1252. tag = ipod_get_codec_tag(s, track);
  1253. else if (track->mode & MODE_3GP)
  1254. tag = ff_codec_get_tag(codec_3gp_tags, track->enc->codec_id);
  1255. else if (track->mode == MODE_F4V)
  1256. tag = ff_codec_get_tag(codec_f4v_tags, track->enc->codec_id);
  1257. else
  1258. tag = mov_get_codec_tag(s, track);
  1259. return tag;
  1260. }
  1261. /** Write uuid atom.
  1262. * Needed to make file play in iPods running newest firmware
  1263. * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
  1264. */
  1265. static int mov_write_uuid_tag_ipod(AVIOContext *pb)
  1266. {
  1267. avio_wb32(pb, 28);
  1268. ffio_wfourcc(pb, "uuid");
  1269. avio_wb32(pb, 0x6b6840f2);
  1270. avio_wb32(pb, 0x5f244fc5);
  1271. avio_wb32(pb, 0xba39a51b);
  1272. avio_wb32(pb, 0xcf0323f3);
  1273. avio_wb32(pb, 0x0);
  1274. return 28;
  1275. }
  1276. static const uint16_t fiel_data[] = {
  1277. 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
  1278. };
  1279. static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track)
  1280. {
  1281. unsigned mov_field_order = 0;
  1282. if (track->enc->field_order < FF_ARRAY_ELEMS(fiel_data))
  1283. mov_field_order = fiel_data[track->enc->field_order];
  1284. else
  1285. return 0;
  1286. avio_wb32(pb, 10);
  1287. ffio_wfourcc(pb, "fiel");
  1288. avio_wb16(pb, mov_field_order);
  1289. return 10;
  1290. }
  1291. static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
  1292. {
  1293. int64_t pos = avio_tell(pb);
  1294. avio_wb32(pb, 0); /* size */
  1295. avio_wl32(pb, track->tag); // store it byteswapped
  1296. avio_wb32(pb, 0); /* Reserved */
  1297. avio_wb16(pb, 0); /* Reserved */
  1298. avio_wb16(pb, 1); /* Data-reference index */
  1299. if (track->enc->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  1300. mov_write_esds_tag(pb, track);
  1301. else if (track->enc->extradata_size)
  1302. avio_write(pb, track->enc->extradata, track->enc->extradata_size);
  1303. return update_size(pb, pos);
  1304. }
  1305. static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
  1306. {
  1307. AVRational sar;
  1308. av_reduce(&sar.num, &sar.den, track->enc->sample_aspect_ratio.num,
  1309. track->enc->sample_aspect_ratio.den, INT_MAX);
  1310. avio_wb32(pb, 16);
  1311. ffio_wfourcc(pb, "pasp");
  1312. avio_wb32(pb, sar.num);
  1313. avio_wb32(pb, sar.den);
  1314. return 16;
  1315. }
  1316. static void find_compressor(char * compressor_name, int len, MOVTrack *track)
  1317. {
  1318. AVDictionaryEntry *encoder;
  1319. int xdcam_res = (track->enc->width == 1280 && track->enc->height == 720)
  1320. || (track->enc->width == 1440 && track->enc->height == 1080)
  1321. || (track->enc->width == 1920 && track->enc->height == 1080);
  1322. if (track->mode == MODE_MOV &&
  1323. (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
  1324. av_strlcpy(compressor_name, encoder->value, 32);
  1325. } else if (track->enc->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
  1326. int interlaced = track->enc->field_order > AV_FIELD_PROGRESSIVE;
  1327. AVStream *st = track->st;
  1328. int rate = av_q2d(find_fps(NULL, st));
  1329. av_strlcatf(compressor_name, len, "XDCAM");
  1330. if (track->enc->pix_fmt == AV_PIX_FMT_YUV422P) {
  1331. av_strlcatf(compressor_name, len, " HD422");
  1332. } else if(track->enc->width == 1440) {
  1333. av_strlcatf(compressor_name, len, " HD");
  1334. } else
  1335. av_strlcatf(compressor_name, len, " EX");
  1336. av_strlcatf(compressor_name, len, " %d%c", track->enc->height, interlaced ? 'i' : 'p');
  1337. av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
  1338. }
  1339. }
  1340. static int mov_write_video_tag(AVIOContext *pb, MOVTrack *track)
  1341. {
  1342. int64_t pos = avio_tell(pb);
  1343. char compressor_name[32] = { 0 };
  1344. avio_wb32(pb, 0); /* size */
  1345. avio_wl32(pb, track->tag); // store it byteswapped
  1346. avio_wb32(pb, 0); /* Reserved */
  1347. avio_wb16(pb, 0); /* Reserved */
  1348. avio_wb16(pb, 1); /* Data-reference index */
  1349. avio_wb16(pb, 0); /* Codec stream version */
  1350. avio_wb16(pb, 0); /* Codec stream revision (=0) */
  1351. if (track->mode == MODE_MOV) {
  1352. ffio_wfourcc(pb, "FFMP"); /* Vendor */
  1353. if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO) {
  1354. avio_wb32(pb, 0); /* Temporal Quality */
  1355. avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
  1356. } else {
  1357. avio_wb32(pb, 0x200); /* Temporal Quality = normal */
  1358. avio_wb32(pb, 0x200); /* Spatial Quality = normal */
  1359. }
  1360. } else {
  1361. avio_wb32(pb, 0); /* Reserved */
  1362. avio_wb32(pb, 0); /* Reserved */
  1363. avio_wb32(pb, 0); /* Reserved */
  1364. }
  1365. avio_wb16(pb, track->enc->width); /* Video width */
  1366. avio_wb16(pb, track->height); /* Video height */
  1367. avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
  1368. avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
  1369. avio_wb32(pb, 0); /* Data size (= 0) */
  1370. avio_wb16(pb, 1); /* Frame count (= 1) */
  1371. /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
  1372. find_compressor(compressor_name, 32, track);
  1373. avio_w8(pb, strlen(compressor_name));
  1374. avio_write(pb, compressor_name, 31);
  1375. if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)
  1376. avio_wb16(pb, track->enc->bits_per_coded_sample);
  1377. else
  1378. avio_wb16(pb, 0x18); /* Reserved */
  1379. avio_wb16(pb, 0xffff); /* Reserved */
  1380. if (track->tag == MKTAG('m','p','4','v'))
  1381. mov_write_esds_tag(pb, track);
  1382. else if (track->enc->codec_id == AV_CODEC_ID_H263)
  1383. mov_write_d263_tag(pb);
  1384. else if (track->enc->codec_id == AV_CODEC_ID_AVUI ||
  1385. track->enc->codec_id == AV_CODEC_ID_SVQ3) {
  1386. mov_write_extradata_tag(pb, track);
  1387. avio_wb32(pb, 0);
  1388. } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD)
  1389. mov_write_avid_tag(pb, track);
  1390. else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
  1391. mov_write_hvcc_tag(pb, track);
  1392. else if (track->enc->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
  1393. mov_write_avcc_tag(pb, track);
  1394. if (track->mode == MODE_IPOD)
  1395. mov_write_uuid_tag_ipod(pb);
  1396. } else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
  1397. mov_write_dvc1_tag(pb, track);
  1398. else if (track->enc->codec_id == AV_CODEC_ID_VP6F ||
  1399. track->enc->codec_id == AV_CODEC_ID_VP6A) {
  1400. /* Don't write any potential extradata here - the cropping
  1401. * is signalled via the normal width/height fields. */
  1402. } else if (track->vos_len > 0)
  1403. mov_write_glbl_tag(pb, track);
  1404. if (track->enc->codec_id != AV_CODEC_ID_H264 &&
  1405. track->enc->codec_id != AV_CODEC_ID_MPEG4 &&
  1406. track->enc->codec_id != AV_CODEC_ID_DNXHD)
  1407. if (track->enc->field_order != AV_FIELD_UNKNOWN)
  1408. mov_write_fiel_tag(pb, track);
  1409. if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
  1410. track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
  1411. mov_write_pasp_tag(pb, track);
  1412. }
  1413. return update_size(pb, pos);
  1414. }
  1415. static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
  1416. {
  1417. int64_t pos = avio_tell(pb);
  1418. avio_wb32(pb, 0); /* size */
  1419. ffio_wfourcc(pb, "rtp ");
  1420. avio_wb32(pb, 0); /* Reserved */
  1421. avio_wb16(pb, 0); /* Reserved */
  1422. avio_wb16(pb, 1); /* Data-reference index */
  1423. avio_wb16(pb, 1); /* Hint track version */
  1424. avio_wb16(pb, 1); /* Highest compatible version */
  1425. avio_wb32(pb, track->max_packet_size); /* Max packet size */
  1426. avio_wb32(pb, 12); /* size */
  1427. ffio_wfourcc(pb, "tims");
  1428. avio_wb32(pb, track->timescale);
  1429. return update_size(pb, pos);
  1430. }
  1431. static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
  1432. {
  1433. uint64_t str_size =strlen(reel_name);
  1434. int64_t pos = avio_tell(pb);
  1435. if (str_size >= UINT16_MAX){
  1436. av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
  1437. avio_wb16(pb, 0);
  1438. return AVERROR(EINVAL);
  1439. }
  1440. avio_wb32(pb, 0); /* size */
  1441. ffio_wfourcc(pb, "name"); /* Data format */
  1442. avio_wb16(pb, str_size); /* string size */
  1443. avio_wb16(pb, track->language); /* langcode */
  1444. avio_write(pb, reel_name, str_size); /* reel name */
  1445. return update_size(pb,pos);
  1446. }
  1447. static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
  1448. {
  1449. int64_t pos = avio_tell(pb);
  1450. #if 1
  1451. int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);
  1452. int nb_frames = 1.0/av_q2d(track->enc->time_base) + 0.5;
  1453. AVDictionaryEntry *t = NULL;
  1454. if (nb_frames > 255) {
  1455. av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
  1456. return AVERROR(EINVAL);
  1457. }
  1458. avio_wb32(pb, 0); /* size */
  1459. ffio_wfourcc(pb, "tmcd"); /* Data format */
  1460. avio_wb32(pb, 0); /* Reserved */
  1461. avio_wb32(pb, 1); /* Data reference index */
  1462. avio_wb32(pb, 0); /* Flags */
  1463. avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
  1464. avio_wb32(pb, track->timescale); /* Timescale */
  1465. avio_wb32(pb, frame_duration); /* Frame duration */
  1466. avio_w8(pb, nb_frames); /* Number of frames */
  1467. avio_w8(pb, 0); /* Reserved */
  1468. if (track->st)
  1469. t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
  1470. if (t && utf8len(t->value))
  1471. mov_write_source_reference_tag(pb, track, t->value);
  1472. else
  1473. avio_wb16(pb, 0); /* zero size */
  1474. #else
  1475. avio_wb32(pb, 0); /* size */
  1476. ffio_wfourcc(pb, "tmcd"); /* Data format */
  1477. avio_wb32(pb, 0); /* Reserved */
  1478. avio_wb32(pb, 1); /* Data reference index */
  1479. if (track->enc->extradata_size)
  1480. avio_write(pb, track->enc->extradata, track->enc->extradata_size);
  1481. #endif
  1482. return update_size(pb, pos);
  1483. }
  1484. static int mov_write_stsd_tag(AVIOContext *pb, MOVTrack *track)
  1485. {
  1486. int64_t pos = avio_tell(pb);
  1487. avio_wb32(pb, 0); /* size */
  1488. ffio_wfourcc(pb, "stsd");
  1489. avio_wb32(pb, 0); /* version & flags */
  1490. avio_wb32(pb, 1); /* entry count */
  1491. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
  1492. mov_write_video_tag(pb, track);
  1493. else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
  1494. mov_write_audio_tag(pb, track);
  1495. else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
  1496. mov_write_subtitle_tag(pb, track);
  1497. else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
  1498. mov_write_rtp_tag(pb, track);
  1499. else if (track->enc->codec_tag == MKTAG('t','m','c','d'))
  1500. mov_write_tmcd_tag(pb, track);
  1501. return update_size(pb, pos);
  1502. }
  1503. static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
  1504. {
  1505. MOVStts *ctts_entries;
  1506. uint32_t entries = 0;
  1507. uint32_t atom_size;
  1508. int i;
  1509. ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
  1510. ctts_entries[0].count = 1;
  1511. ctts_entries[0].duration = track->cluster[0].cts;
  1512. for (i = 1; i < track->entry; i++) {
  1513. if (track->cluster[i].cts == ctts_entries[entries].duration) {
  1514. ctts_entries[entries].count++; /* compress */
  1515. } else {
  1516. entries++;
  1517. ctts_entries[entries].duration = track->cluster[i].cts;
  1518. ctts_entries[entries].count = 1;
  1519. }
  1520. }
  1521. entries++; /* last one */
  1522. atom_size = 16 + (entries * 8);
  1523. avio_wb32(pb, atom_size); /* size */
  1524. ffio_wfourcc(pb, "ctts");
  1525. avio_wb32(pb, 0); /* version & flags */
  1526. avio_wb32(pb, entries); /* entry count */
  1527. for (i = 0; i < entries; i++) {
  1528. avio_wb32(pb, ctts_entries[i].count);
  1529. avio_wb32(pb, ctts_entries[i].duration);
  1530. }
  1531. av_free(ctts_entries);
  1532. return atom_size;
  1533. }
  1534. /* Time to sample atom */
  1535. static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
  1536. {
  1537. MOVStts *stts_entries;
  1538. uint32_t entries = -1;
  1539. uint32_t atom_size;
  1540. int i;
  1541. if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
  1542. stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
  1543. stts_entries[0].count = track->sample_count;
  1544. stts_entries[0].duration = 1;
  1545. entries = 1;
  1546. } else {
  1547. stts_entries = track->entry ?
  1548. av_malloc_array(track->entry, sizeof(*stts_entries)) : /* worst case */
  1549. NULL;
  1550. for (i = 0; i < track->entry; i++) {
  1551. int duration = get_cluster_duration(track, i);
  1552. if (i && duration == stts_entries[entries].duration) {
  1553. stts_entries[entries].count++; /* compress */
  1554. } else {
  1555. entries++;
  1556. stts_entries[entries].duration = duration;
  1557. stts_entries[entries].count = 1;
  1558. }
  1559. }
  1560. entries++; /* last one */
  1561. }
  1562. atom_size = 16 + (entries * 8);
  1563. avio_wb32(pb, atom_size); /* size */
  1564. ffio_wfourcc(pb, "stts");
  1565. avio_wb32(pb, 0); /* version & flags */
  1566. avio_wb32(pb, entries); /* entry count */
  1567. for (i = 0; i < entries; i++) {
  1568. avio_wb32(pb, stts_entries[i].count);
  1569. avio_wb32(pb, stts_entries[i].duration);
  1570. }
  1571. av_free(stts_entries);
  1572. return atom_size;
  1573. }
  1574. static int mov_write_dref_tag(AVIOContext *pb)
  1575. {
  1576. avio_wb32(pb, 28); /* size */
  1577. ffio_wfourcc(pb, "dref");
  1578. avio_wb32(pb, 0); /* version & flags */
  1579. avio_wb32(pb, 1); /* entry count */
  1580. avio_wb32(pb, 0xc); /* size */
  1581. //FIXME add the alis and rsrc atom
  1582. ffio_wfourcc(pb, "url ");
  1583. avio_wb32(pb, 1); /* version & flags */
  1584. return 28;
  1585. }
  1586. static int mov_write_stbl_tag(AVIOContext *pb, MOVTrack *track)
  1587. {
  1588. int64_t pos = avio_tell(pb);
  1589. avio_wb32(pb, 0); /* size */
  1590. ffio_wfourcc(pb, "stbl");
  1591. mov_write_stsd_tag(pb, track);
  1592. mov_write_stts_tag(pb, track);
  1593. if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
  1594. track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
  1595. track->has_keyframes && track->has_keyframes < track->entry)
  1596. mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
  1597. if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
  1598. mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
  1599. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
  1600. track->flags & MOV_TRACK_CTTS)
  1601. mov_write_ctts_tag(pb, track);
  1602. mov_write_stsc_tag(pb, track);
  1603. mov_write_stsz_tag(pb, track);
  1604. mov_write_stco_tag(pb, track);
  1605. return update_size(pb, pos);
  1606. }
  1607. static int mov_write_dinf_tag(AVIOContext *pb)
  1608. {
  1609. int64_t pos = avio_tell(pb);
  1610. avio_wb32(pb, 0); /* size */
  1611. ffio_wfourcc(pb, "dinf");
  1612. mov_write_dref_tag(pb);
  1613. return update_size(pb, pos);
  1614. }
  1615. static int mov_write_nmhd_tag(AVIOContext *pb)
  1616. {
  1617. avio_wb32(pb, 12);
  1618. ffio_wfourcc(pb, "nmhd");
  1619. avio_wb32(pb, 0);
  1620. return 12;
  1621. }
  1622. static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
  1623. {
  1624. int64_t pos = avio_tell(pb);
  1625. const char *font = "Lucida Grande";
  1626. avio_wb32(pb, 0); /* size */
  1627. ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
  1628. avio_wb32(pb, 0); /* version & flags */
  1629. avio_wb16(pb, 0); /* text font */
  1630. avio_wb16(pb, 0); /* text face */
  1631. avio_wb16(pb, 12); /* text size */
  1632. avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
  1633. avio_wb16(pb, 0x0000); /* text color (red) */
  1634. avio_wb16(pb, 0x0000); /* text color (green) */
  1635. avio_wb16(pb, 0x0000); /* text color (blue) */
  1636. avio_wb16(pb, 0xffff); /* background color (red) */
  1637. avio_wb16(pb, 0xffff); /* background color (green) */
  1638. avio_wb16(pb, 0xffff); /* background color (blue) */
  1639. avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
  1640. avio_write(pb, font, strlen(font)); /* font name */
  1641. return update_size(pb, pos);
  1642. }
  1643. static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
  1644. {
  1645. int64_t pos = avio_tell(pb);
  1646. avio_wb32(pb, 0); /* size */
  1647. ffio_wfourcc(pb, "gmhd");
  1648. avio_wb32(pb, 0x18); /* gmin size */
  1649. ffio_wfourcc(pb, "gmin");/* generic media info */
  1650. avio_wb32(pb, 0); /* version & flags */
  1651. avio_wb16(pb, 0x40); /* graphics mode = */
  1652. avio_wb16(pb, 0x8000); /* opColor (r?) */
  1653. avio_wb16(pb, 0x8000); /* opColor (g?) */
  1654. avio_wb16(pb, 0x8000); /* opColor (b?) */
  1655. avio_wb16(pb, 0); /* balance */
  1656. avio_wb16(pb, 0); /* reserved */
  1657. /*
  1658. * This special text atom is required for
  1659. * Apple Quicktime chapters. The contents
  1660. * don't appear to be documented, so the
  1661. * bytes are copied verbatim.
  1662. */
  1663. if (track->tag != MKTAG('c','6','0','8')) {
  1664. avio_wb32(pb, 0x2C); /* size */
  1665. ffio_wfourcc(pb, "text");
  1666. avio_wb16(pb, 0x01);
  1667. avio_wb32(pb, 0x00);
  1668. avio_wb32(pb, 0x00);
  1669. avio_wb32(pb, 0x00);
  1670. avio_wb32(pb, 0x01);
  1671. avio_wb32(pb, 0x00);
  1672. avio_wb32(pb, 0x00);
  1673. avio_wb32(pb, 0x00);
  1674. avio_wb32(pb, 0x00004000);
  1675. avio_wb16(pb, 0x0000);
  1676. }
  1677. if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
  1678. int64_t tmcd_pos = avio_tell(pb);
  1679. avio_wb32(pb, 0); /* size */
  1680. ffio_wfourcc(pb, "tmcd");
  1681. mov_write_tcmi_tag(pb, track);
  1682. update_size(pb, tmcd_pos);
  1683. }
  1684. return update_size(pb, pos);
  1685. }
  1686. static int mov_write_smhd_tag(AVIOContext *pb)
  1687. {
  1688. avio_wb32(pb, 16); /* size */
  1689. ffio_wfourcc(pb, "smhd");
  1690. avio_wb32(pb, 0); /* version & flags */
  1691. avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
  1692. avio_wb16(pb, 0); /* reserved */
  1693. return 16;
  1694. }
  1695. static int mov_write_vmhd_tag(AVIOContext *pb)
  1696. {
  1697. avio_wb32(pb, 0x14); /* size (always 0x14) */
  1698. ffio_wfourcc(pb, "vmhd");
  1699. avio_wb32(pb, 0x01); /* version & flags */
  1700. avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
  1701. return 0x14;
  1702. }
  1703. static int is_clcp_track(MOVTrack *track)
  1704. {
  1705. return track->tag == MKTAG('c','7','0','8') ||
  1706. track->tag == MKTAG('c','6','0','8');
  1707. }
  1708. static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
  1709. {
  1710. const char *hdlr, *descr = NULL, *hdlr_type = NULL;
  1711. int64_t pos = avio_tell(pb);
  1712. hdlr = "dhlr";
  1713. hdlr_type = "url ";
  1714. descr = "DataHandler";
  1715. if (track) {
  1716. hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
  1717. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1718. hdlr_type = "vide";
  1719. descr = "VideoHandler";
  1720. } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
  1721. hdlr_type = "soun";
  1722. descr = "SoundHandler";
  1723. } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  1724. if (is_clcp_track(track)) {
  1725. hdlr_type = "clcp";
  1726. descr = "ClosedCaptionHandler";
  1727. } else {
  1728. if (track->tag == MKTAG('t','x','3','g')) {
  1729. hdlr_type = "sbtl";
  1730. } else if (track->tag == MKTAG('m','p','4','s')) {
  1731. hdlr_type = "subp";
  1732. } else {
  1733. hdlr_type = "text";
  1734. }
  1735. descr = "SubtitleHandler";
  1736. }
  1737. } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
  1738. hdlr_type = "hint";
  1739. descr = "HintHandler";
  1740. } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
  1741. hdlr_type = "tmcd";
  1742. descr = "TimeCodeHandler";
  1743. } else {
  1744. char tag_buf[32];
  1745. av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
  1746. track->enc->codec_tag);
  1747. av_log(track->enc, AV_LOG_WARNING,
  1748. "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
  1749. tag_buf, track->enc->codec_tag);
  1750. }
  1751. if (track->st) {
  1752. // hdlr.name is used by some players to identify the content title
  1753. // of the track. So if an alternate handler description is
  1754. // specified, use it.
  1755. AVDictionaryEntry *t;
  1756. t = av_dict_get(track->st->metadata, "handler", NULL, 0);
  1757. if (t && utf8len(t->value))
  1758. descr = t->value;
  1759. }
  1760. }
  1761. avio_wb32(pb, 0); /* size */
  1762. ffio_wfourcc(pb, "hdlr");
  1763. avio_wb32(pb, 0); /* Version & flags */
  1764. avio_write(pb, hdlr, 4); /* handler */
  1765. ffio_wfourcc(pb, hdlr_type); /* handler type */
  1766. avio_wb32(pb, 0); /* reserved */
  1767. avio_wb32(pb, 0); /* reserved */
  1768. avio_wb32(pb, 0); /* reserved */
  1769. if (!track || track->mode == MODE_MOV)
  1770. avio_w8(pb, strlen(descr)); /* pascal string */
  1771. avio_write(pb, descr, strlen(descr)); /* handler description */
  1772. if (track && track->mode != MODE_MOV)
  1773. avio_w8(pb, 0); /* c string */
  1774. return update_size(pb, pos);
  1775. }
  1776. static int mov_write_hmhd_tag(AVIOContext *pb)
  1777. {
  1778. /* This atom must be present, but leaving the values at zero
  1779. * seems harmless. */
  1780. avio_wb32(pb, 28); /* size */
  1781. ffio_wfourcc(pb, "hmhd");
  1782. avio_wb32(pb, 0); /* version, flags */
  1783. avio_wb16(pb, 0); /* maxPDUsize */
  1784. avio_wb16(pb, 0); /* avgPDUsize */
  1785. avio_wb32(pb, 0); /* maxbitrate */
  1786. avio_wb32(pb, 0); /* avgbitrate */
  1787. avio_wb32(pb, 0); /* reserved */
  1788. return 28;
  1789. }
  1790. static int mov_write_minf_tag(AVIOContext *pb, MOVTrack *track)
  1791. {
  1792. int64_t pos = avio_tell(pb);
  1793. avio_wb32(pb, 0); /* size */
  1794. ffio_wfourcc(pb, "minf");
  1795. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
  1796. mov_write_vmhd_tag(pb);
  1797. else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
  1798. mov_write_smhd_tag(pb);
  1799. else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  1800. if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
  1801. mov_write_gmhd_tag(pb, track);
  1802. } else {
  1803. mov_write_nmhd_tag(pb);
  1804. }
  1805. } else if (track->tag == MKTAG('r','t','p',' ')) {
  1806. mov_write_hmhd_tag(pb);
  1807. } else if (track->tag == MKTAG('t','m','c','d')) {
  1808. mov_write_gmhd_tag(pb, track);
  1809. }
  1810. if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
  1811. mov_write_hdlr_tag(pb, NULL);
  1812. mov_write_dinf_tag(pb);
  1813. mov_write_stbl_tag(pb, track);
  1814. return update_size(pb, pos);
  1815. }
  1816. static int mov_write_mdhd_tag(AVIOContext *pb, MOVTrack *track)
  1817. {
  1818. int version = track->track_duration < INT32_MAX ? 0 : 1;
  1819. if (track->mode == MODE_ISM)
  1820. version = 1;
  1821. (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
  1822. ffio_wfourcc(pb, "mdhd");
  1823. avio_w8(pb, version);
  1824. avio_wb24(pb, 0); /* flags */
  1825. if (version == 1) {
  1826. avio_wb64(pb, track->time);
  1827. avio_wb64(pb, track->time);
  1828. } else {
  1829. avio_wb32(pb, track->time); /* creation time */
  1830. avio_wb32(pb, track->time); /* modification time */
  1831. }
  1832. avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
  1833. if (!track->entry)
  1834. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  1835. else
  1836. (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
  1837. avio_wb16(pb, track->language); /* language */
  1838. avio_wb16(pb, 0); /* reserved (quality) */
  1839. if (version != 0 && track->mode == MODE_MOV) {
  1840. av_log(NULL, AV_LOG_ERROR,
  1841. "FATAL error, file duration too long for timebase, this file will not be\n"
  1842. "playable with quicktime. Choose a different timebase or a different\n"
  1843. "container format\n");
  1844. }
  1845. return 32;
  1846. }
  1847. static int mov_write_mdia_tag(AVIOContext *pb, MOVTrack *track)
  1848. {
  1849. int64_t pos = avio_tell(pb);
  1850. avio_wb32(pb, 0); /* size */
  1851. ffio_wfourcc(pb, "mdia");
  1852. mov_write_mdhd_tag(pb, track);
  1853. mov_write_hdlr_tag(pb, track);
  1854. mov_write_minf_tag(pb, track);
  1855. return update_size(pb, pos);
  1856. }
  1857. /* transformation matrix
  1858. |a b u|
  1859. |c d v|
  1860. |tx ty w| */
  1861. static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
  1862. int16_t d, int16_t tx, int16_t ty)
  1863. {
  1864. avio_wb32(pb, a << 16); /* 16.16 format */
  1865. avio_wb32(pb, b << 16); /* 16.16 format */
  1866. avio_wb32(pb, 0); /* u in 2.30 format */
  1867. avio_wb32(pb, c << 16); /* 16.16 format */
  1868. avio_wb32(pb, d << 16); /* 16.16 format */
  1869. avio_wb32(pb, 0); /* v in 2.30 format */
  1870. avio_wb32(pb, tx << 16); /* 16.16 format */
  1871. avio_wb32(pb, ty << 16); /* 16.16 format */
  1872. avio_wb32(pb, 1 << 30); /* w in 2.30 format */
  1873. }
  1874. static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  1875. MOVTrack *track, AVStream *st)
  1876. {
  1877. int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
  1878. track->timescale, AV_ROUND_UP);
  1879. int version = duration < INT32_MAX ? 0 : 1;
  1880. int flags = MOV_TKHD_FLAG_IN_MOVIE;
  1881. int rotation = 0;
  1882. int group = 0;
  1883. if (st) {
  1884. if (mov->per_stream_grouping)
  1885. group = st->index;
  1886. else
  1887. group = st->codec->codec_type;
  1888. }
  1889. if (track->flags & MOV_TRACK_ENABLED)
  1890. flags |= MOV_TKHD_FLAG_ENABLED;
  1891. if (track->mode == MODE_ISM)
  1892. version = 1;
  1893. (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
  1894. ffio_wfourcc(pb, "tkhd");
  1895. avio_w8(pb, version);
  1896. avio_wb24(pb, flags);
  1897. if (version == 1) {
  1898. avio_wb64(pb, track->time);
  1899. avio_wb64(pb, track->time);
  1900. } else {
  1901. avio_wb32(pb, track->time); /* creation time */
  1902. avio_wb32(pb, track->time); /* modification time */
  1903. }
  1904. avio_wb32(pb, track->track_id); /* track-id */
  1905. avio_wb32(pb, 0); /* reserved */
  1906. if (!track->entry)
  1907. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  1908. else
  1909. (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
  1910. avio_wb32(pb, 0); /* reserved */
  1911. avio_wb32(pb, 0); /* reserved */
  1912. avio_wb16(pb, 0); /* layer */
  1913. avio_wb16(pb, group); /* alternate group) */
  1914. /* Volume, only for audio */
  1915. if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
  1916. avio_wb16(pb, 0x0100);
  1917. else
  1918. avio_wb16(pb, 0);
  1919. avio_wb16(pb, 0); /* reserved */
  1920. /* Matrix structure */
  1921. if (st && st->metadata) {
  1922. AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
  1923. rotation = (rot && rot->value) ? atoi(rot->value) : 0;
  1924. }
  1925. if (rotation == 90) {
  1926. write_matrix(pb, 0, 1, -1, 0, track->enc->height, 0);
  1927. } else if (rotation == 180) {
  1928. write_matrix(pb, -1, 0, 0, -1, track->enc->width, track->enc->height);
  1929. } else if (rotation == 270) {
  1930. write_matrix(pb, 0, -1, 1, 0, 0, track->enc->width);
  1931. } else {
  1932. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  1933. }
  1934. /* Track width and height, for visual only */
  1935. if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
  1936. track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
  1937. if (track->mode == MODE_MOV) {
  1938. avio_wb32(pb, track->enc->width << 16);
  1939. avio_wb32(pb, track->height << 16);
  1940. } else {
  1941. double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
  1942. if (!sample_aspect_ratio || track->height != track->enc->height)
  1943. sample_aspect_ratio = 1;
  1944. avio_wb32(pb, sample_aspect_ratio * track->enc->width * 0x10000);
  1945. avio_wb32(pb, track->height * 0x10000);
  1946. }
  1947. } else {
  1948. avio_wb32(pb, 0);
  1949. avio_wb32(pb, 0);
  1950. }
  1951. return 0x5c;
  1952. }
  1953. static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
  1954. {
  1955. int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
  1956. track->enc->sample_aspect_ratio.den);
  1957. int64_t pos = avio_tell(pb);
  1958. avio_wb32(pb, 0); /* size */
  1959. ffio_wfourcc(pb, "tapt");
  1960. avio_wb32(pb, 20);
  1961. ffio_wfourcc(pb, "clef");
  1962. avio_wb32(pb, 0);
  1963. avio_wb32(pb, width << 16);
  1964. avio_wb32(pb, track->enc->height << 16);
  1965. avio_wb32(pb, 20);
  1966. ffio_wfourcc(pb, "prof");
  1967. avio_wb32(pb, 0);
  1968. avio_wb32(pb, width << 16);
  1969. avio_wb32(pb, track->enc->height << 16);
  1970. avio_wb32(pb, 20);
  1971. ffio_wfourcc(pb, "enof");
  1972. avio_wb32(pb, 0);
  1973. avio_wb32(pb, track->enc->width << 16);
  1974. avio_wb32(pb, track->enc->height << 16);
  1975. return update_size(pb, pos);
  1976. }
  1977. // This box seems important for the psp playback ... without it the movie seems to hang
  1978. static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
  1979. MOVTrack *track)
  1980. {
  1981. int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
  1982. track->timescale, AV_ROUND_UP);
  1983. int version = duration < INT32_MAX ? 0 : 1;
  1984. int entry_size, entry_count, size;
  1985. int64_t delay, start_ct = track->cluster[0].cts;
  1986. delay = av_rescale_rnd(track->cluster[0].dts + start_ct, MOV_TIMESCALE,
  1987. track->timescale, AV_ROUND_DOWN);
  1988. version |= delay < INT32_MAX ? 0 : 1;
  1989. entry_size = (version == 1) ? 20 : 12;
  1990. entry_count = 1 + (delay > 0);
  1991. size = 24 + entry_count * entry_size;
  1992. /* write the atom data */
  1993. avio_wb32(pb, size);
  1994. ffio_wfourcc(pb, "edts");
  1995. avio_wb32(pb, size - 8);
  1996. ffio_wfourcc(pb, "elst");
  1997. avio_w8(pb, version);
  1998. avio_wb24(pb, 0); /* flags */
  1999. avio_wb32(pb, entry_count);
  2000. if (delay > 0) { /* add an empty edit to delay presentation */
  2001. /* In the positive delay case, the delay includes the cts
  2002. * offset, and the second edit list entry below trims out
  2003. * the same amount from the actual content. This makes sure
  2004. * that the offsetted last sample is included in the edit
  2005. * list duration as well. */
  2006. if (version == 1) {
  2007. avio_wb64(pb, delay);
  2008. avio_wb64(pb, -1);
  2009. } else {
  2010. avio_wb32(pb, delay);
  2011. avio_wb32(pb, -1);
  2012. }
  2013. avio_wb32(pb, 0x00010000);
  2014. } else {
  2015. /* Avoid accidentally ending up with start_ct = -1 which has got a
  2016. * special meaning. Normally start_ct should end up positive or zero
  2017. * here, but use FFMIN in case dts is a a small positive integer
  2018. * rounded to 0 when represented in MOV_TIMESCALE units. */
  2019. av_assert0(av_rescale_rnd(track->cluster[0].dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
  2020. start_ct = -FFMIN(track->cluster[0].dts, 0);
  2021. /* Note, this delay is calculated from the pts of the first sample,
  2022. * ensuring that we don't reduce the duration for cases with
  2023. * dts<0 pts=0. */
  2024. duration += delay;
  2025. }
  2026. /* For fragmented files, we don't know the full length yet. Setting
  2027. * duration to 0 allows us to only specify the offset, including
  2028. * the rest of the content (from all future fragments) without specifying
  2029. * an explicit duration. */
  2030. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  2031. duration = 0;
  2032. /* duration */
  2033. if (version == 1) {
  2034. avio_wb64(pb, duration);
  2035. avio_wb64(pb, start_ct);
  2036. } else {
  2037. avio_wb32(pb, duration);
  2038. avio_wb32(pb, start_ct);
  2039. }
  2040. avio_wb32(pb, 0x00010000);
  2041. return size;
  2042. }
  2043. static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
  2044. {
  2045. avio_wb32(pb, 20); // size
  2046. ffio_wfourcc(pb, "tref");
  2047. avio_wb32(pb, 12); // size (subatom)
  2048. avio_wl32(pb, track->tref_tag);
  2049. avio_wb32(pb, track->tref_id);
  2050. return 20;
  2051. }
  2052. // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
  2053. static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
  2054. {
  2055. avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
  2056. ffio_wfourcc(pb, "uuid");
  2057. ffio_wfourcc(pb, "USMT");
  2058. avio_wb32(pb, 0x21d24fce);
  2059. avio_wb32(pb, 0xbb88695c);
  2060. avio_wb32(pb, 0xfac9c740);
  2061. avio_wb32(pb, 0x1c); // another size here!
  2062. ffio_wfourcc(pb, "MTDT");
  2063. avio_wb32(pb, 0x00010012);
  2064. avio_wb32(pb, 0x0a);
  2065. avio_wb32(pb, 0x55c40000);
  2066. avio_wb32(pb, 0x1);
  2067. avio_wb32(pb, 0x0);
  2068. return 0x34;
  2069. }
  2070. static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
  2071. {
  2072. AVFormatContext *ctx = track->rtp_ctx;
  2073. char buf[1000] = "";
  2074. int len;
  2075. ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
  2076. NULL, NULL, 0, 0, ctx);
  2077. av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
  2078. len = strlen(buf);
  2079. avio_wb32(pb, len + 24);
  2080. ffio_wfourcc(pb, "udta");
  2081. avio_wb32(pb, len + 16);
  2082. ffio_wfourcc(pb, "hnti");
  2083. avio_wb32(pb, len + 8);
  2084. ffio_wfourcc(pb, "sdp ");
  2085. avio_write(pb, buf, len);
  2086. return len + 24;
  2087. }
  2088. static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
  2089. const char *tag, const char *str)
  2090. {
  2091. int64_t pos = avio_tell(pb);
  2092. AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
  2093. if (!t || !utf8len(t->value))
  2094. return 0;
  2095. avio_wb32(pb, 0); /* size */
  2096. ffio_wfourcc(pb, tag); /* type */
  2097. avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
  2098. return update_size(pb, pos);
  2099. }
  2100. static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2101. AVStream *st)
  2102. {
  2103. AVIOContext *pb_buf;
  2104. int ret, size;
  2105. uint8_t *buf;
  2106. if (!st || mov->fc->flags & AVFMT_FLAG_BITEXACT)
  2107. return 0;
  2108. ret = avio_open_dyn_buf(&pb_buf);
  2109. if (ret < 0)
  2110. return ret;
  2111. if (mov->mode & MODE_MP4)
  2112. mov_write_track_metadata(pb_buf, st, "name", "title");
  2113. if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
  2114. avio_wb32(pb, size + 8);
  2115. ffio_wfourcc(pb, "udta");
  2116. avio_write(pb, buf, size);
  2117. }
  2118. av_free(buf);
  2119. return 0;
  2120. }
  2121. static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
  2122. MOVTrack *track, AVStream *st)
  2123. {
  2124. int64_t pos = avio_tell(pb);
  2125. avio_wb32(pb, 0); /* size */
  2126. ffio_wfourcc(pb, "trak");
  2127. mov_write_tkhd_tag(pb, mov, track, st);
  2128. if (supports_edts(mov))
  2129. mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
  2130. if (track->tref_tag)
  2131. mov_write_tref_tag(pb, track);
  2132. mov_write_mdia_tag(pb, track);
  2133. if (track->mode == MODE_PSP)
  2134. mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
  2135. if (track->tag == MKTAG('r','t','p',' '))
  2136. mov_write_udta_sdp(pb, track);
  2137. if (track->mode == MODE_MOV) {
  2138. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  2139. double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
  2140. if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
  2141. mov_write_tapt_tag(pb, track);
  2142. }
  2143. }
  2144. if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
  2145. mov_write_tapt_tag(pb, track);
  2146. }
  2147. }
  2148. mov_write_track_udta_tag(pb, mov, st);
  2149. return update_size(pb, pos);
  2150. }
  2151. static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
  2152. {
  2153. int i, has_audio = 0, has_video = 0;
  2154. int64_t pos = avio_tell(pb);
  2155. int audio_profile = mov->iods_audio_profile;
  2156. int video_profile = mov->iods_video_profile;
  2157. for (i = 0; i < mov->nb_streams; i++) {
  2158. if (mov->tracks[i].entry > 0) {
  2159. has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
  2160. has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
  2161. }
  2162. }
  2163. if (audio_profile < 0)
  2164. audio_profile = 0xFF - has_audio;
  2165. if (video_profile < 0)
  2166. video_profile = 0xFF - has_video;
  2167. avio_wb32(pb, 0x0); /* size */
  2168. ffio_wfourcc(pb, "iods");
  2169. avio_wb32(pb, 0); /* version & flags */
  2170. put_descr(pb, 0x10, 7);
  2171. avio_wb16(pb, 0x004f);
  2172. avio_w8(pb, 0xff);
  2173. avio_w8(pb, 0xff);
  2174. avio_w8(pb, audio_profile);
  2175. avio_w8(pb, video_profile);
  2176. avio_w8(pb, 0xff);
  2177. return update_size(pb, pos);
  2178. }
  2179. static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
  2180. {
  2181. avio_wb32(pb, 0x20); /* size */
  2182. ffio_wfourcc(pb, "trex");
  2183. avio_wb32(pb, 0); /* version & flags */
  2184. avio_wb32(pb, track->track_id); /* track ID */
  2185. avio_wb32(pb, 1); /* default sample description index */
  2186. avio_wb32(pb, 0); /* default sample duration */
  2187. avio_wb32(pb, 0); /* default sample size */
  2188. avio_wb32(pb, 0); /* default sample flags */
  2189. return 0;
  2190. }
  2191. static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
  2192. {
  2193. int64_t pos = avio_tell(pb);
  2194. int i;
  2195. avio_wb32(pb, 0x0); /* size */
  2196. ffio_wfourcc(pb, "mvex");
  2197. for (i = 0; i < mov->nb_streams; i++)
  2198. mov_write_trex_tag(pb, &mov->tracks[i]);
  2199. return update_size(pb, pos);
  2200. }
  2201. static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  2202. {
  2203. int max_track_id = 1, i;
  2204. int64_t max_track_len_temp, max_track_len = 0;
  2205. int version;
  2206. for (i = 0; i < mov->nb_streams; i++) {
  2207. if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
  2208. max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
  2209. MOV_TIMESCALE,
  2210. mov->tracks[i].timescale,
  2211. AV_ROUND_UP);
  2212. if (max_track_len < max_track_len_temp)
  2213. max_track_len = max_track_len_temp;
  2214. if (max_track_id < mov->tracks[i].track_id)
  2215. max_track_id = mov->tracks[i].track_id;
  2216. }
  2217. }
  2218. version = max_track_len < UINT32_MAX ? 0 : 1;
  2219. (version == 1) ? avio_wb32(pb, 120) : avio_wb32(pb, 108); /* size */
  2220. ffio_wfourcc(pb, "mvhd");
  2221. avio_w8(pb, version);
  2222. avio_wb24(pb, 0); /* flags */
  2223. if (version == 1) {
  2224. avio_wb64(pb, mov->time);
  2225. avio_wb64(pb, mov->time);
  2226. } else {
  2227. avio_wb32(pb, mov->time); /* creation time */
  2228. avio_wb32(pb, mov->time); /* modification time */
  2229. }
  2230. avio_wb32(pb, MOV_TIMESCALE);
  2231. (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
  2232. avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
  2233. avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
  2234. avio_wb16(pb, 0); /* reserved */
  2235. avio_wb32(pb, 0); /* reserved */
  2236. avio_wb32(pb, 0); /* reserved */
  2237. /* Matrix structure */
  2238. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  2239. avio_wb32(pb, 0); /* reserved (preview time) */
  2240. avio_wb32(pb, 0); /* reserved (preview duration) */
  2241. avio_wb32(pb, 0); /* reserved (poster time) */
  2242. avio_wb32(pb, 0); /* reserved (selection time) */
  2243. avio_wb32(pb, 0); /* reserved (selection duration) */
  2244. avio_wb32(pb, 0); /* reserved (current time) */
  2245. avio_wb32(pb, max_track_id + 1); /* Next track id */
  2246. return 0x6c;
  2247. }
  2248. static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
  2249. AVFormatContext *s)
  2250. {
  2251. avio_wb32(pb, 33); /* size */
  2252. ffio_wfourcc(pb, "hdlr");
  2253. avio_wb32(pb, 0);
  2254. avio_wb32(pb, 0);
  2255. ffio_wfourcc(pb, "mdir");
  2256. ffio_wfourcc(pb, "appl");
  2257. avio_wb32(pb, 0);
  2258. avio_wb32(pb, 0);
  2259. avio_w8(pb, 0);
  2260. return 33;
  2261. }
  2262. /* helper function to write a data tag with the specified string as data */
  2263. static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
  2264. {
  2265. if (long_style) {
  2266. int size = 16 + strlen(data);
  2267. avio_wb32(pb, size); /* size */
  2268. ffio_wfourcc(pb, "data");
  2269. avio_wb32(pb, 1);
  2270. avio_wb32(pb, 0);
  2271. avio_write(pb, data, strlen(data));
  2272. return size;
  2273. } else {
  2274. if (!lang)
  2275. lang = ff_mov_iso639_to_lang("und", 1);
  2276. avio_wb16(pb, strlen(data)); /* string length */
  2277. avio_wb16(pb, lang);
  2278. avio_write(pb, data, strlen(data));
  2279. return strlen(data) + 4;
  2280. }
  2281. }
  2282. static int mov_write_string_tag(AVIOContext *pb, const char *name,
  2283. const char *value, int lang, int long_style)
  2284. {
  2285. int size = 0;
  2286. if (value && value[0]) {
  2287. int64_t pos = avio_tell(pb);
  2288. avio_wb32(pb, 0); /* size */
  2289. ffio_wfourcc(pb, name);
  2290. mov_write_string_data_tag(pb, value, lang, long_style);
  2291. size = update_size(pb, pos);
  2292. }
  2293. return size;
  2294. }
  2295. static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
  2296. const char *name, const char *tag,
  2297. int long_style)
  2298. {
  2299. int l, lang = 0, len, len2;
  2300. AVDictionaryEntry *t, *t2 = NULL;
  2301. char tag2[16];
  2302. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  2303. return 0;
  2304. len = strlen(t->key);
  2305. snprintf(tag2, sizeof(tag2), "%s-", tag);
  2306. while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
  2307. len2 = strlen(t2->key);
  2308. if (len2 == len + 4 && !strcmp(t->value, t2->value)
  2309. && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
  2310. lang = l;
  2311. break;
  2312. }
  2313. }
  2314. return mov_write_string_tag(pb, name, t->value, lang, long_style);
  2315. }
  2316. /* iTunes bpm number */
  2317. static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
  2318. {
  2319. AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
  2320. int size = 0, tmpo = t ? atoi(t->value) : 0;
  2321. if (tmpo) {
  2322. size = 26;
  2323. avio_wb32(pb, size);
  2324. ffio_wfourcc(pb, "tmpo");
  2325. avio_wb32(pb, size-8); /* size */
  2326. ffio_wfourcc(pb, "data");
  2327. avio_wb32(pb, 0x15); //type specifier
  2328. avio_wb32(pb, 0);
  2329. avio_wb16(pb, tmpo); // data
  2330. }
  2331. return size;
  2332. }
  2333. /* iTunes track or disc number */
  2334. static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
  2335. AVFormatContext *s, int disc)
  2336. {
  2337. AVDictionaryEntry *t = av_dict_get(s->metadata,
  2338. disc ? "disc" : "track",
  2339. NULL, 0);
  2340. int size = 0, track = t ? atoi(t->value) : 0;
  2341. if (track) {
  2342. int tracks = 0;
  2343. char *slash = strchr(t->value, '/');
  2344. if (slash)
  2345. tracks = atoi(slash + 1);
  2346. avio_wb32(pb, 32); /* size */
  2347. ffio_wfourcc(pb, disc ? "disk" : "trkn");
  2348. avio_wb32(pb, 24); /* size */
  2349. ffio_wfourcc(pb, "data");
  2350. avio_wb32(pb, 0); // 8 bytes empty
  2351. avio_wb32(pb, 0);
  2352. avio_wb16(pb, 0); // empty
  2353. avio_wb16(pb, track); // track / disc number
  2354. avio_wb16(pb, tracks); // total track / disc number
  2355. avio_wb16(pb, 0); // empty
  2356. size = 32;
  2357. }
  2358. return size;
  2359. }
  2360. static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
  2361. const char *name, const char *tag,
  2362. int len)
  2363. {
  2364. AVDictionaryEntry *t = NULL;
  2365. uint8_t num;
  2366. int size = 24 + len;
  2367. if (len != 1 && len != 4)
  2368. return -1;
  2369. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  2370. return 0;
  2371. num = atoi(t->value);
  2372. avio_wb32(pb, size);
  2373. ffio_wfourcc(pb, name);
  2374. avio_wb32(pb, size - 8);
  2375. ffio_wfourcc(pb, "data");
  2376. avio_wb32(pb, 0x15);
  2377. avio_wb32(pb, 0);
  2378. if (len==4) avio_wb32(pb, num);
  2379. else avio_w8 (pb, num);
  2380. return size;
  2381. }
  2382. /* iTunes meta data list */
  2383. static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
  2384. AVFormatContext *s)
  2385. {
  2386. int64_t pos = avio_tell(pb);
  2387. avio_wb32(pb, 0); /* size */
  2388. ffio_wfourcc(pb, "ilst");
  2389. mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
  2390. mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
  2391. mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
  2392. mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
  2393. mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
  2394. mov_write_string_metadata(s, pb, "\251day", "date" , 1);
  2395. if (!mov->exact &&
  2396. !mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1))
  2397. mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
  2398. mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
  2399. mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
  2400. mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
  2401. mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
  2402. mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
  2403. mov_write_string_metadata(s, pb, "desc", "description",1);
  2404. mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
  2405. mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
  2406. mov_write_string_metadata(s, pb, "tven", "episode_id",1);
  2407. mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
  2408. mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
  2409. mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
  2410. mov_write_int8_metadata (s, pb, "stik", "media_type",1);
  2411. mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
  2412. mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
  2413. mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
  2414. mov_write_trkn_tag(pb, mov, s, 0); // track number
  2415. mov_write_trkn_tag(pb, mov, s, 1); // disc number
  2416. mov_write_tmpo_tag(pb, s);
  2417. return update_size(pb, pos);
  2418. }
  2419. /* iTunes meta data tag */
  2420. static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2421. AVFormatContext *s)
  2422. {
  2423. int size = 0;
  2424. int64_t pos = avio_tell(pb);
  2425. avio_wb32(pb, 0); /* size */
  2426. ffio_wfourcc(pb, "meta");
  2427. avio_wb32(pb, 0);
  2428. mov_write_itunes_hdlr_tag(pb, mov, s);
  2429. mov_write_ilst_tag(pb, mov, s);
  2430. size = update_size(pb, pos);
  2431. return size;
  2432. }
  2433. static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
  2434. const char *name, const char *key)
  2435. {
  2436. int len;
  2437. AVDictionaryEntry *t;
  2438. if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
  2439. return 0;
  2440. len = strlen(t->value);
  2441. if (len > 0) {
  2442. int size = len + 8;
  2443. avio_wb32(pb, size);
  2444. ffio_wfourcc(pb, name);
  2445. avio_write(pb, t->value, len);
  2446. return size;
  2447. }
  2448. return 0;
  2449. }
  2450. static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
  2451. {
  2452. int val;
  2453. while (*b) {
  2454. GET_UTF8(val, *b++, return -1;)
  2455. avio_wb16(pb, val);
  2456. }
  2457. avio_wb16(pb, 0x00);
  2458. return 0;
  2459. }
  2460. static uint16_t language_code(const char *str)
  2461. {
  2462. return (((str[0] - 0x60) & 0x1F) << 10) +
  2463. (((str[1] - 0x60) & 0x1F) << 5) +
  2464. (( str[2] - 0x60) & 0x1F);
  2465. }
  2466. static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
  2467. const char *tag, const char *str)
  2468. {
  2469. int64_t pos = avio_tell(pb);
  2470. AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
  2471. if (!t || !utf8len(t->value))
  2472. return 0;
  2473. avio_wb32(pb, 0); /* size */
  2474. ffio_wfourcc(pb, tag); /* type */
  2475. avio_wb32(pb, 0); /* version + flags */
  2476. if (!strcmp(tag, "yrrc"))
  2477. avio_wb16(pb, atoi(t->value));
  2478. else {
  2479. avio_wb16(pb, language_code("eng")); /* language */
  2480. avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
  2481. if (!strcmp(tag, "albm") &&
  2482. (t = av_dict_get(s->metadata, "track", NULL, 0)))
  2483. avio_w8(pb, atoi(t->value));
  2484. }
  2485. return update_size(pb, pos);
  2486. }
  2487. static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
  2488. {
  2489. int64_t pos = avio_tell(pb);
  2490. int i, nb_chapters = FFMIN(s->nb_chapters, 255);
  2491. avio_wb32(pb, 0); // size
  2492. ffio_wfourcc(pb, "chpl");
  2493. avio_wb32(pb, 0x01000000); // version + flags
  2494. avio_wb32(pb, 0); // unknown
  2495. avio_w8(pb, nb_chapters);
  2496. for (i = 0; i < nb_chapters; i++) {
  2497. AVChapter *c = s->chapters[i];
  2498. AVDictionaryEntry *t;
  2499. avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
  2500. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  2501. int len = FFMIN(strlen(t->value), 255);
  2502. avio_w8(pb, len);
  2503. avio_write(pb, t->value, len);
  2504. } else
  2505. avio_w8(pb, 0);
  2506. }
  2507. return update_size(pb, pos);
  2508. }
  2509. static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2510. AVFormatContext *s)
  2511. {
  2512. AVIOContext *pb_buf;
  2513. int ret, size;
  2514. uint8_t *buf;
  2515. ret = avio_open_dyn_buf(&pb_buf);
  2516. if (ret < 0)
  2517. return ret;
  2518. if (mov->mode & MODE_3GP) {
  2519. mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
  2520. mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
  2521. mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
  2522. mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
  2523. mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
  2524. mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
  2525. mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
  2526. mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
  2527. } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
  2528. mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
  2529. mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
  2530. mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
  2531. mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
  2532. mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
  2533. mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
  2534. // currently ignored by mov.c
  2535. mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
  2536. // add support for libquicktime, this atom is also actually read by mov.c
  2537. mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
  2538. mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
  2539. mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
  2540. mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
  2541. } else {
  2542. /* iTunes meta data */
  2543. mov_write_meta_tag(pb_buf, mov, s);
  2544. }
  2545. if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
  2546. mov_write_chpl_tag(pb_buf, s);
  2547. if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
  2548. avio_wb32(pb, size + 8);
  2549. ffio_wfourcc(pb, "udta");
  2550. avio_write(pb, buf, size);
  2551. }
  2552. av_free(buf);
  2553. return 0;
  2554. }
  2555. static void mov_write_psp_udta_tag(AVIOContext *pb,
  2556. const char *str, const char *lang, int type)
  2557. {
  2558. int len = utf8len(str) + 1;
  2559. if (len <= 0)
  2560. return;
  2561. avio_wb16(pb, len * 2 + 10); /* size */
  2562. avio_wb32(pb, type); /* type */
  2563. avio_wb16(pb, language_code(lang)); /* language */
  2564. avio_wb16(pb, 0x01); /* ? */
  2565. ascii_to_wc(pb, str);
  2566. }
  2567. static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
  2568. {
  2569. MOVMuxContext *mov = s->priv_data;
  2570. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  2571. int64_t pos, pos2;
  2572. if (title) {
  2573. pos = avio_tell(pb);
  2574. avio_wb32(pb, 0); /* size placeholder*/
  2575. ffio_wfourcc(pb, "uuid");
  2576. ffio_wfourcc(pb, "USMT");
  2577. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  2578. avio_wb32(pb, 0xbb88695c);
  2579. avio_wb32(pb, 0xfac9c740);
  2580. pos2 = avio_tell(pb);
  2581. avio_wb32(pb, 0); /* size placeholder*/
  2582. ffio_wfourcc(pb, "MTDT");
  2583. avio_wb16(pb, 4);
  2584. // ?
  2585. avio_wb16(pb, 0x0C); /* size */
  2586. avio_wb32(pb, 0x0B); /* type */
  2587. avio_wb16(pb, language_code("und")); /* language */
  2588. avio_wb16(pb, 0x0); /* ? */
  2589. avio_wb16(pb, 0x021C); /* data */
  2590. if (!mov->exact)
  2591. mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
  2592. mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
  2593. mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
  2594. update_size(pb, pos2);
  2595. return update_size(pb, pos);
  2596. }
  2597. return 0;
  2598. }
  2599. static void build_chunks(MOVTrack *trk)
  2600. {
  2601. int i;
  2602. MOVIentry *chunk = &trk->cluster[0];
  2603. uint64_t chunkSize = chunk->size;
  2604. chunk->chunkNum = 1;
  2605. if (trk->chunkCount)
  2606. return;
  2607. trk->chunkCount = 1;
  2608. for (i = 1; i<trk->entry; i++){
  2609. if (chunk->pos + chunkSize == trk->cluster[i].pos &&
  2610. chunkSize + trk->cluster[i].size < (1<<20)){
  2611. chunkSize += trk->cluster[i].size;
  2612. chunk->samples_in_chunk += trk->cluster[i].entries;
  2613. } else {
  2614. trk->cluster[i].chunkNum = chunk->chunkNum+1;
  2615. chunk=&trk->cluster[i];
  2616. chunkSize = chunk->size;
  2617. trk->chunkCount++;
  2618. }
  2619. }
  2620. }
  2621. static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
  2622. AVFormatContext *s)
  2623. {
  2624. int i;
  2625. int64_t pos = avio_tell(pb);
  2626. avio_wb32(pb, 0); /* size placeholder*/
  2627. ffio_wfourcc(pb, "moov");
  2628. for (i = 0; i < mov->nb_streams; i++) {
  2629. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  2630. continue;
  2631. mov->tracks[i].time = mov->time;
  2632. mov->tracks[i].track_id = i + 1;
  2633. if (mov->tracks[i].entry)
  2634. build_chunks(&mov->tracks[i]);
  2635. }
  2636. if (mov->chapter_track)
  2637. for (i = 0; i < s->nb_streams; i++) {
  2638. mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
  2639. mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
  2640. }
  2641. for (i = 0; i < mov->nb_streams; i++) {
  2642. if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) {
  2643. mov->tracks[i].tref_tag = MKTAG('h','i','n','t');
  2644. mov->tracks[i].tref_id =
  2645. mov->tracks[mov->tracks[i].src_track].track_id;
  2646. }
  2647. }
  2648. for (i = 0; i < mov->nb_streams; i++) {
  2649. if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
  2650. int src_trk = mov->tracks[i].src_track;
  2651. mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
  2652. mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
  2653. //src_trk may have a different timescale than the tmcd track
  2654. mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
  2655. mov->tracks[i].timescale,
  2656. mov->tracks[src_trk].timescale);
  2657. }
  2658. }
  2659. mov_write_mvhd_tag(pb, mov);
  2660. if (mov->mode != MODE_MOV && !mov->iods_skip)
  2661. mov_write_iods_tag(pb, mov);
  2662. for (i = 0; i < mov->nb_streams; i++) {
  2663. if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
  2664. mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
  2665. }
  2666. }
  2667. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  2668. mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
  2669. if (mov->mode == MODE_PSP)
  2670. mov_write_uuidusmt_tag(pb, s);
  2671. else
  2672. mov_write_udta_tag(pb, mov, s);
  2673. return update_size(pb, pos);
  2674. }
  2675. static void param_write_int(AVIOContext *pb, const char *name, int value)
  2676. {
  2677. avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
  2678. }
  2679. static void param_write_string(AVIOContext *pb, const char *name, const char *value)
  2680. {
  2681. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
  2682. }
  2683. static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
  2684. {
  2685. char buf[150];
  2686. len = FFMIN(sizeof(buf) / 2 - 1, len);
  2687. ff_data_to_hex(buf, value, len, 0);
  2688. buf[2 * len] = '\0';
  2689. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
  2690. }
  2691. static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
  2692. {
  2693. int64_t pos = avio_tell(pb);
  2694. int i;
  2695. static const uint8_t uuid[] = {
  2696. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  2697. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  2698. };
  2699. avio_wb32(pb, 0);
  2700. ffio_wfourcc(pb, "uuid");
  2701. avio_write(pb, uuid, sizeof(uuid));
  2702. avio_wb32(pb, 0);
  2703. avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  2704. avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
  2705. avio_printf(pb, "<head>\n");
  2706. if (!mov->exact)
  2707. avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
  2708. LIBAVFORMAT_IDENT);
  2709. avio_printf(pb, "</head>\n");
  2710. avio_printf(pb, "<body>\n");
  2711. avio_printf(pb, "<switch>\n");
  2712. for (i = 0; i < mov->nb_streams; i++) {
  2713. MOVTrack *track = &mov->tracks[i];
  2714. const char *type;
  2715. /* track->track_id is initialized in write_moov, and thus isn't known
  2716. * here yet */
  2717. int track_id = i + 1;
  2718. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  2719. type = "video";
  2720. } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
  2721. type = "audio";
  2722. } else {
  2723. continue;
  2724. }
  2725. avio_printf(pb, "<%s systemBitrate=\"%d\">\n", type,
  2726. track->enc->bit_rate);
  2727. param_write_int(pb, "systemBitrate", track->enc->bit_rate);
  2728. param_write_int(pb, "trackID", track_id);
  2729. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  2730. if (track->enc->codec_id == AV_CODEC_ID_H264) {
  2731. uint8_t *ptr;
  2732. int size = track->enc->extradata_size;
  2733. if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
  2734. &size)) {
  2735. param_write_hex(pb, "CodecPrivateData",
  2736. ptr ? ptr : track->enc->extradata,
  2737. size);
  2738. av_free(ptr);
  2739. }
  2740. param_write_string(pb, "FourCC", "H264");
  2741. } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
  2742. param_write_string(pb, "FourCC", "WVC1");
  2743. param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
  2744. track->enc->extradata_size);
  2745. }
  2746. param_write_int(pb, "MaxWidth", track->enc->width);
  2747. param_write_int(pb, "MaxHeight", track->enc->height);
  2748. param_write_int(pb, "DisplayWidth", track->enc->width);
  2749. param_write_int(pb, "DisplayHeight", track->enc->height);
  2750. } else {
  2751. if (track->enc->codec_id == AV_CODEC_ID_AAC) {
  2752. param_write_string(pb, "FourCC", "AACL");
  2753. } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
  2754. param_write_string(pb, "FourCC", "WMAP");
  2755. }
  2756. param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
  2757. track->enc->extradata_size);
  2758. param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
  2759. track->enc->codec_id));
  2760. param_write_int(pb, "Channels", track->enc->channels);
  2761. param_write_int(pb, "SamplingRate", track->enc->sample_rate);
  2762. param_write_int(pb, "BitsPerSample", 16);
  2763. param_write_int(pb, "PacketSize", track->enc->block_align ?
  2764. track->enc->block_align : 4);
  2765. }
  2766. avio_printf(pb, "</%s>\n", type);
  2767. }
  2768. avio_printf(pb, "</switch>\n");
  2769. avio_printf(pb, "</body>\n");
  2770. avio_printf(pb, "</smil>\n");
  2771. return update_size(pb, pos);
  2772. }
  2773. static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  2774. {
  2775. avio_wb32(pb, 16);
  2776. ffio_wfourcc(pb, "mfhd");
  2777. avio_wb32(pb, 0);
  2778. avio_wb32(pb, mov->fragments);
  2779. return 0;
  2780. }
  2781. static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  2782. MOVTrack *track, int64_t moof_offset)
  2783. {
  2784. int64_t pos = avio_tell(pb);
  2785. uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  2786. MOV_TFHD_BASE_DATA_OFFSET;
  2787. if (!track->entry) {
  2788. flags |= MOV_TFHD_DURATION_IS_EMPTY;
  2789. } else {
  2790. flags |= MOV_TFHD_DEFAULT_FLAGS;
  2791. }
  2792. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
  2793. flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
  2794. /* Don't set a default sample size, the silverlight player refuses
  2795. * to play files with that set. Don't set a default sample duration,
  2796. * WMP freaks out if it is set. Don't set a base data offset, PIFF
  2797. * file format says it MUST NOT be set. */
  2798. if (track->mode == MODE_ISM)
  2799. flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  2800. MOV_TFHD_BASE_DATA_OFFSET);
  2801. avio_wb32(pb, 0); /* size placeholder */
  2802. ffio_wfourcc(pb, "tfhd");
  2803. avio_w8(pb, 0); /* version */
  2804. avio_wb24(pb, flags);
  2805. avio_wb32(pb, track->track_id); /* track-id */
  2806. if (flags & MOV_TFHD_BASE_DATA_OFFSET)
  2807. avio_wb64(pb, moof_offset);
  2808. if (flags & MOV_TFHD_DEFAULT_DURATION) {
  2809. track->default_duration = get_cluster_duration(track, 0);
  2810. avio_wb32(pb, track->default_duration);
  2811. }
  2812. if (flags & MOV_TFHD_DEFAULT_SIZE) {
  2813. track->default_size = track->entry ? track->cluster[0].size : 1;
  2814. avio_wb32(pb, track->default_size);
  2815. } else
  2816. track->default_size = -1;
  2817. if (flags & MOV_TFHD_DEFAULT_FLAGS) {
  2818. track->default_sample_flags =
  2819. track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
  2820. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
  2821. MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
  2822. avio_wb32(pb, track->default_sample_flags);
  2823. }
  2824. return update_size(pb, pos);
  2825. }
  2826. static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
  2827. {
  2828. return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
  2829. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
  2830. }
  2831. static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
  2832. MOVTrack *track, int moof_size)
  2833. {
  2834. int64_t pos = avio_tell(pb);
  2835. uint32_t flags = MOV_TRUN_DATA_OFFSET;
  2836. int i;
  2837. for (i = 0; i < track->entry; i++) {
  2838. if (get_cluster_duration(track, i) != track->default_duration)
  2839. flags |= MOV_TRUN_SAMPLE_DURATION;
  2840. if (track->cluster[i].size != track->default_size)
  2841. flags |= MOV_TRUN_SAMPLE_SIZE;
  2842. if (i > 0 && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
  2843. flags |= MOV_TRUN_SAMPLE_FLAGS;
  2844. }
  2845. if (!(flags & MOV_TRUN_SAMPLE_FLAGS))
  2846. flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
  2847. if (track->flags & MOV_TRACK_CTTS)
  2848. flags |= MOV_TRUN_SAMPLE_CTS;
  2849. avio_wb32(pb, 0); /* size placeholder */
  2850. ffio_wfourcc(pb, "trun");
  2851. avio_w8(pb, 0); /* version */
  2852. avio_wb24(pb, flags);
  2853. avio_wb32(pb, track->entry); /* sample count */
  2854. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
  2855. !(mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) &&
  2856. track->track_id != 1)
  2857. avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
  2858. else
  2859. avio_wb32(pb, moof_size + 8 + track->data_offset +
  2860. track->cluster[0].pos); /* data offset */
  2861. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
  2862. avio_wb32(pb, get_sample_flags(track, &track->cluster[0]));
  2863. for (i = 0; i < track->entry; i++) {
  2864. if (flags & MOV_TRUN_SAMPLE_DURATION)
  2865. avio_wb32(pb, get_cluster_duration(track, i));
  2866. if (flags & MOV_TRUN_SAMPLE_SIZE)
  2867. avio_wb32(pb, track->cluster[i].size);
  2868. if (flags & MOV_TRUN_SAMPLE_FLAGS)
  2869. avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
  2870. if (flags & MOV_TRUN_SAMPLE_CTS)
  2871. avio_wb32(pb, track->cluster[i].cts);
  2872. }
  2873. return update_size(pb, pos);
  2874. }
  2875. static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
  2876. {
  2877. int64_t pos = avio_tell(pb);
  2878. static const uint8_t uuid[] = {
  2879. 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
  2880. 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
  2881. };
  2882. avio_wb32(pb, 0); /* size placeholder */
  2883. ffio_wfourcc(pb, "uuid");
  2884. avio_write(pb, uuid, sizeof(uuid));
  2885. avio_w8(pb, 1);
  2886. avio_wb24(pb, 0);
  2887. avio_wb64(pb, track->frag_start);
  2888. avio_wb64(pb, track->start_dts + track->track_duration -
  2889. track->cluster[0].dts);
  2890. return update_size(pb, pos);
  2891. }
  2892. static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
  2893. MOVTrack *track, int entry)
  2894. {
  2895. int n = track->nb_frag_info - 1 - entry, i;
  2896. int size = 8 + 16 + 4 + 1 + 16*n;
  2897. static const uint8_t uuid[] = {
  2898. 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
  2899. 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
  2900. };
  2901. if (entry < 0)
  2902. return 0;
  2903. avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
  2904. avio_wb32(pb, size);
  2905. ffio_wfourcc(pb, "uuid");
  2906. avio_write(pb, uuid, sizeof(uuid));
  2907. avio_w8(pb, 1);
  2908. avio_wb24(pb, 0);
  2909. avio_w8(pb, n);
  2910. for (i = 0; i < n; i++) {
  2911. int index = entry + 1 + i;
  2912. avio_wb64(pb, track->frag_info[index].time);
  2913. avio_wb64(pb, track->frag_info[index].duration);
  2914. }
  2915. if (n < mov->ism_lookahead) {
  2916. int free_size = 16 * (mov->ism_lookahead - n);
  2917. avio_wb32(pb, free_size);
  2918. ffio_wfourcc(pb, "free");
  2919. ffio_fill(pb, 0, free_size - 8);
  2920. }
  2921. return 0;
  2922. }
  2923. static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
  2924. MOVTrack *track)
  2925. {
  2926. int64_t pos = avio_tell(pb);
  2927. int i;
  2928. for (i = 0; i < mov->ism_lookahead; i++) {
  2929. /* Update the tfrf tag for the last ism_lookahead fragments,
  2930. * nb_frag_info - 1 is the next fragment to be written. */
  2931. mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
  2932. }
  2933. avio_seek(pb, pos, SEEK_SET);
  2934. return 0;
  2935. }
  2936. static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
  2937. {
  2938. int64_t pos = avio_tell(pb);
  2939. avio_wb32(pb, 0); /* size */
  2940. ffio_wfourcc(pb, "tfdt");
  2941. avio_w8(pb, 1); /* version */
  2942. avio_wb24(pb, 0);
  2943. avio_wb64(pb, track->frag_start);
  2944. return update_size(pb, pos);
  2945. }
  2946. static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
  2947. MOVTrack *track, int64_t moof_offset,
  2948. int moof_size)
  2949. {
  2950. int64_t pos = avio_tell(pb);
  2951. avio_wb32(pb, 0); /* size placeholder */
  2952. ffio_wfourcc(pb, "traf");
  2953. mov_write_tfhd_tag(pb, mov, track, moof_offset);
  2954. mov_write_tfdt_tag(pb, track);
  2955. mov_write_trun_tag(pb, mov, track, moof_size);
  2956. if (mov->mode == MODE_ISM) {
  2957. mov_write_tfxd_tag(pb, track);
  2958. if (mov->ism_lookahead) {
  2959. int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
  2960. track->tfrf_offset = avio_tell(pb);
  2961. avio_wb32(pb, 8 + size);
  2962. ffio_wfourcc(pb, "free");
  2963. for (i = 0; i < size; i++)
  2964. avio_w8(pb, 0);
  2965. }
  2966. }
  2967. return update_size(pb, pos);
  2968. }
  2969. static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
  2970. int tracks, int moof_size)
  2971. {
  2972. int64_t pos = avio_tell(pb);
  2973. int i;
  2974. avio_wb32(pb, 0); /* size placeholder */
  2975. ffio_wfourcc(pb, "moof");
  2976. mov_write_mfhd_tag(pb, mov);
  2977. for (i = 0; i < mov->nb_streams; i++) {
  2978. MOVTrack *track = &mov->tracks[i];
  2979. if (tracks >= 0 && i != tracks)
  2980. continue;
  2981. if (!track->entry)
  2982. continue;
  2983. mov_write_traf_tag(pb, mov, track, pos, moof_size);
  2984. }
  2985. return update_size(pb, pos);
  2986. }
  2987. static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
  2988. {
  2989. AVIOContext *avio_buf;
  2990. int ret, moof_size;
  2991. if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
  2992. return ret;
  2993. mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
  2994. moof_size = ffio_close_null_buf(avio_buf);
  2995. return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
  2996. }
  2997. static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
  2998. {
  2999. int64_t pos = avio_tell(pb);
  3000. int i;
  3001. avio_wb32(pb, 0); /* size placeholder */
  3002. ffio_wfourcc(pb, "tfra");
  3003. avio_w8(pb, 1); /* version */
  3004. avio_wb24(pb, 0);
  3005. avio_wb32(pb, track->track_id);
  3006. avio_wb32(pb, 0); /* length of traf/trun/sample num */
  3007. avio_wb32(pb, track->nb_frag_info);
  3008. for (i = 0; i < track->nb_frag_info; i++) {
  3009. avio_wb64(pb, track->frag_info[i].time);
  3010. avio_wb64(pb, track->frag_info[i].offset);
  3011. avio_w8(pb, 1); /* traf number */
  3012. avio_w8(pb, 1); /* trun number */
  3013. avio_w8(pb, 1); /* sample number */
  3014. }
  3015. return update_size(pb, pos);
  3016. }
  3017. static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
  3018. {
  3019. int64_t pos = avio_tell(pb);
  3020. int i;
  3021. avio_wb32(pb, 0); /* size placeholder */
  3022. ffio_wfourcc(pb, "mfra");
  3023. /* An empty mfra atom is enough to indicate to the publishing point that
  3024. * the stream has ended. */
  3025. if (mov->flags & FF_MOV_FLAG_ISML)
  3026. return update_size(pb, pos);
  3027. for (i = 0; i < mov->nb_streams; i++) {
  3028. MOVTrack *track = &mov->tracks[i];
  3029. if (track->nb_frag_info)
  3030. mov_write_tfra_tag(pb, track);
  3031. }
  3032. avio_wb32(pb, 16);
  3033. ffio_wfourcc(pb, "mfro");
  3034. avio_wb32(pb, 0); /* version + flags */
  3035. avio_wb32(pb, avio_tell(pb) + 4 - pos);
  3036. return update_size(pb, pos);
  3037. }
  3038. static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
  3039. {
  3040. avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
  3041. ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
  3042. mov->mdat_pos = avio_tell(pb);
  3043. avio_wb32(pb, 0); /* size placeholder*/
  3044. ffio_wfourcc(pb, "mdat");
  3045. return 0;
  3046. }
  3047. /* TODO: This needs to be more general */
  3048. static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
  3049. {
  3050. MOVMuxContext *mov = s->priv_data;
  3051. int64_t pos = avio_tell(pb);
  3052. int has_h264 = 0, has_video = 0;
  3053. int minor = 0x200;
  3054. int i;
  3055. for (i = 0; i < s->nb_streams; i++) {
  3056. AVStream *st = s->streams[i];
  3057. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  3058. has_video = 1;
  3059. if (st->codec->codec_id == AV_CODEC_ID_H264)
  3060. has_h264 = 1;
  3061. }
  3062. avio_wb32(pb, 0); /* size */
  3063. ffio_wfourcc(pb, "ftyp");
  3064. if (mov->major_brand && strlen(mov->major_brand) >= 4)
  3065. ffio_wfourcc(pb, mov->major_brand);
  3066. else if (mov->mode == MODE_3GP) {
  3067. ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
  3068. minor = has_h264 ? 0x100 : 0x200;
  3069. } else if (mov->mode & MODE_3G2) {
  3070. ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
  3071. minor = has_h264 ? 0x20000 : 0x10000;
  3072. } else if (mov->mode == MODE_PSP)
  3073. ffio_wfourcc(pb, "MSNV");
  3074. else if (mov->mode == MODE_MP4)
  3075. ffio_wfourcc(pb, "isom");
  3076. else if (mov->mode == MODE_IPOD)
  3077. ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
  3078. else if (mov->mode == MODE_ISM)
  3079. ffio_wfourcc(pb, "isml");
  3080. else if (mov->mode == MODE_F4V)
  3081. ffio_wfourcc(pb, "f4v ");
  3082. else
  3083. ffio_wfourcc(pb, "qt ");
  3084. avio_wb32(pb, minor);
  3085. if (mov->mode == MODE_MOV)
  3086. ffio_wfourcc(pb, "qt ");
  3087. else if (mov->mode == MODE_ISM) {
  3088. ffio_wfourcc(pb, "piff");
  3089. ffio_wfourcc(pb, "iso2");
  3090. } else {
  3091. ffio_wfourcc(pb, "isom");
  3092. ffio_wfourcc(pb, "iso2");
  3093. if (has_h264)
  3094. ffio_wfourcc(pb, "avc1");
  3095. }
  3096. if (mov->mode == MODE_3GP)
  3097. ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
  3098. else if (mov->mode & MODE_3G2)
  3099. ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
  3100. else if (mov->mode == MODE_PSP)
  3101. ffio_wfourcc(pb, "MSNV");
  3102. else if (mov->mode == MODE_MP4)
  3103. ffio_wfourcc(pb, "mp41");
  3104. return update_size(pb, pos);
  3105. }
  3106. static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
  3107. {
  3108. AVStream *video_st = s->streams[0];
  3109. AVCodecContext *video_codec = s->streams[0]->codec;
  3110. AVCodecContext *audio_codec = s->streams[1]->codec;
  3111. int audio_rate = audio_codec->sample_rate;
  3112. // TODO: should be avg_frame_rate
  3113. int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);
  3114. int audio_kbitrate = audio_codec->bit_rate / 1000;
  3115. int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
  3116. avio_wb32(pb, 0x94); /* size */
  3117. ffio_wfourcc(pb, "uuid");
  3118. ffio_wfourcc(pb, "PROF");
  3119. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  3120. avio_wb32(pb, 0xbb88695c);
  3121. avio_wb32(pb, 0xfac9c740);
  3122. avio_wb32(pb, 0x0); /* ? */
  3123. avio_wb32(pb, 0x3); /* 3 sections ? */
  3124. avio_wb32(pb, 0x14); /* size */
  3125. ffio_wfourcc(pb, "FPRF");
  3126. avio_wb32(pb, 0x0); /* ? */
  3127. avio_wb32(pb, 0x0); /* ? */
  3128. avio_wb32(pb, 0x0); /* ? */
  3129. avio_wb32(pb, 0x2c); /* size */
  3130. ffio_wfourcc(pb, "APRF"); /* audio */
  3131. avio_wb32(pb, 0x0);
  3132. avio_wb32(pb, 0x2); /* TrackID */
  3133. ffio_wfourcc(pb, "mp4a");
  3134. avio_wb32(pb, 0x20f);
  3135. avio_wb32(pb, 0x0);
  3136. avio_wb32(pb, audio_kbitrate);
  3137. avio_wb32(pb, audio_kbitrate);
  3138. avio_wb32(pb, audio_rate);
  3139. avio_wb32(pb, audio_codec->channels);
  3140. avio_wb32(pb, 0x34); /* size */
  3141. ffio_wfourcc(pb, "VPRF"); /* video */
  3142. avio_wb32(pb, 0x0);
  3143. avio_wb32(pb, 0x1); /* TrackID */
  3144. if (video_codec->codec_id == AV_CODEC_ID_H264) {
  3145. ffio_wfourcc(pb, "avc1");
  3146. avio_wb16(pb, 0x014D);
  3147. avio_wb16(pb, 0x0015);
  3148. } else {
  3149. ffio_wfourcc(pb, "mp4v");
  3150. avio_wb16(pb, 0x0000);
  3151. avio_wb16(pb, 0x0103);
  3152. }
  3153. avio_wb32(pb, 0x0);
  3154. avio_wb32(pb, video_kbitrate);
  3155. avio_wb32(pb, video_kbitrate);
  3156. avio_wb32(pb, frame_rate);
  3157. avio_wb32(pb, frame_rate);
  3158. avio_wb16(pb, video_codec->width);
  3159. avio_wb16(pb, video_codec->height);
  3160. avio_wb32(pb, 0x010001); /* ? */
  3161. }
  3162. static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
  3163. {
  3164. uint32_t c = -1;
  3165. int i, closed_gop = 0;
  3166. for (i = 0; i < pkt->size - 4; i++) {
  3167. c = (c << 8) + pkt->data[i];
  3168. if (c == 0x1b8) { // gop
  3169. closed_gop = pkt->data[i + 4] >> 6 & 0x01;
  3170. } else if (c == 0x100) { // pic
  3171. int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
  3172. if (!temp_ref || closed_gop) // I picture is not reordered
  3173. *flags = MOV_SYNC_SAMPLE;
  3174. else
  3175. *flags = MOV_PARTIAL_SYNC_SAMPLE;
  3176. break;
  3177. }
  3178. }
  3179. return 0;
  3180. }
  3181. static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk, int fragment)
  3182. {
  3183. const uint8_t *start, *next, *end = pkt->data + pkt->size;
  3184. int seq = 0, entry = 0;
  3185. int key = pkt->flags & AV_PKT_FLAG_KEY;
  3186. start = find_next_marker(pkt->data, end);
  3187. for (next = start; next < end; start = next) {
  3188. next = find_next_marker(start + 4, end);
  3189. switch (AV_RB32(start)) {
  3190. case VC1_CODE_SEQHDR:
  3191. seq = 1;
  3192. break;
  3193. case VC1_CODE_ENTRYPOINT:
  3194. entry = 1;
  3195. break;
  3196. case VC1_CODE_SLICE:
  3197. trk->vc1_info.slices = 1;
  3198. break;
  3199. }
  3200. }
  3201. if (!trk->entry && !fragment) {
  3202. /* First packet in first fragment */
  3203. trk->vc1_info.first_packet_seq = seq;
  3204. trk->vc1_info.first_packet_entry = entry;
  3205. } else if ((seq && !trk->vc1_info.packet_seq) ||
  3206. (entry && !trk->vc1_info.packet_entry)) {
  3207. int i;
  3208. for (i = 0; i < trk->entry; i++)
  3209. trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
  3210. trk->has_keyframes = 0;
  3211. if (seq)
  3212. trk->vc1_info.packet_seq = 1;
  3213. if (entry)
  3214. trk->vc1_info.packet_entry = 1;
  3215. if (!fragment) {
  3216. /* First fragment */
  3217. if ((!seq || trk->vc1_info.first_packet_seq) &&
  3218. (!entry || trk->vc1_info.first_packet_entry)) {
  3219. /* First packet had the same headers as this one, readd the
  3220. * sync sample flag. */
  3221. trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
  3222. trk->has_keyframes = 1;
  3223. }
  3224. }
  3225. }
  3226. if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
  3227. key = seq && entry;
  3228. else if (trk->vc1_info.packet_seq)
  3229. key = seq;
  3230. else if (trk->vc1_info.packet_entry)
  3231. key = entry;
  3232. if (key) {
  3233. trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
  3234. trk->has_keyframes++;
  3235. }
  3236. }
  3237. static int mov_flush_fragment(AVFormatContext *s)
  3238. {
  3239. MOVMuxContext *mov = s->priv_data;
  3240. int i, first_track = -1;
  3241. int64_t mdat_size = 0;
  3242. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3243. return 0;
  3244. if (!(mov->flags & FF_MOV_FLAG_EMPTY_MOOV) && mov->fragments == 0) {
  3245. int64_t pos = avio_tell(s->pb);
  3246. uint8_t *buf;
  3247. int buf_size, moov_size;
  3248. for (i = 0; i < mov->nb_streams; i++)
  3249. if (!mov->tracks[i].entry)
  3250. break;
  3251. /* Don't write the initial moov unless all tracks have data */
  3252. if (i < mov->nb_streams)
  3253. return 0;
  3254. moov_size = get_moov_size(s);
  3255. for (i = 0; i < mov->nb_streams; i++)
  3256. mov->tracks[i].data_offset = pos + moov_size + 8;
  3257. mov_write_moov_tag(s->pb, mov, s);
  3258. buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
  3259. mov->mdat_buf = NULL;
  3260. avio_wb32(s->pb, buf_size + 8);
  3261. ffio_wfourcc(s->pb, "mdat");
  3262. avio_write(s->pb, buf, buf_size);
  3263. av_free(buf);
  3264. mov->fragments++;
  3265. mov->mdat_size = 0;
  3266. for (i = 0; i < mov->nb_streams; i++) {
  3267. if (mov->tracks[i].entry)
  3268. mov->tracks[i].frag_start += mov->tracks[i].start_dts +
  3269. mov->tracks[i].track_duration -
  3270. mov->tracks[i].cluster[0].dts;
  3271. mov->tracks[i].entry = 0;
  3272. }
  3273. avio_flush(s->pb);
  3274. return 0;
  3275. }
  3276. for (i = 0; i < mov->nb_streams; i++) {
  3277. MOVTrack *track = &mov->tracks[i];
  3278. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF)
  3279. track->data_offset = 0;
  3280. else
  3281. track->data_offset = mdat_size;
  3282. if (!track->mdat_buf)
  3283. continue;
  3284. mdat_size += avio_tell(track->mdat_buf);
  3285. if (first_track < 0)
  3286. first_track = i;
  3287. }
  3288. if (!mdat_size)
  3289. return 0;
  3290. for (i = 0; i < mov->nb_streams; i++) {
  3291. MOVTrack *track = &mov->tracks[i];
  3292. int buf_size, write_moof = 1, moof_tracks = -1;
  3293. uint8_t *buf;
  3294. int64_t duration = 0;
  3295. if (track->entry)
  3296. duration = track->start_dts + track->track_duration -
  3297. track->cluster[0].dts;
  3298. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
  3299. if (!track->mdat_buf)
  3300. continue;
  3301. mdat_size = avio_tell(track->mdat_buf);
  3302. moof_tracks = i;
  3303. } else {
  3304. write_moof = i == first_track;
  3305. }
  3306. if (write_moof) {
  3307. MOVFragmentInfo *info;
  3308. avio_flush(s->pb);
  3309. track->nb_frag_info++;
  3310. if (track->nb_frag_info >= track->frag_info_capacity) {
  3311. unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
  3312. if (av_reallocp_array(&track->frag_info,
  3313. new_capacity,
  3314. sizeof(*track->frag_info)))
  3315. return AVERROR(ENOMEM);
  3316. track->frag_info_capacity = new_capacity;
  3317. }
  3318. info = &track->frag_info[track->nb_frag_info - 1];
  3319. info->offset = avio_tell(s->pb);
  3320. info->time = track->frag_start;
  3321. info->duration = duration;
  3322. mov_write_tfrf_tags(s->pb, mov, track);
  3323. mov_write_moof_tag(s->pb, mov, moof_tracks);
  3324. info->tfrf_offset = track->tfrf_offset;
  3325. mov->fragments++;
  3326. avio_wb32(s->pb, mdat_size + 8);
  3327. ffio_wfourcc(s->pb, "mdat");
  3328. }
  3329. if (track->entry)
  3330. track->frag_start += duration;
  3331. track->entry = 0;
  3332. if (!track->mdat_buf)
  3333. continue;
  3334. buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
  3335. track->mdat_buf = NULL;
  3336. avio_write(s->pb, buf, buf_size);
  3337. av_free(buf);
  3338. }
  3339. mov->mdat_size = 0;
  3340. avio_flush(s->pb);
  3341. return 0;
  3342. }
  3343. int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  3344. {
  3345. MOVMuxContext *mov = s->priv_data;
  3346. AVIOContext *pb = s->pb;
  3347. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  3348. AVCodecContext *enc = trk->enc;
  3349. unsigned int samples_in_chunk = 0;
  3350. int size = pkt->size;
  3351. uint8_t *reformatted_data = NULL;
  3352. if (trk->entry) {
  3353. int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
  3354. if (duration < 0 || duration > INT_MAX) {
  3355. av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
  3356. duration, pkt->dts
  3357. );
  3358. pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
  3359. pkt->pts = AV_NOPTS_VALUE;
  3360. }
  3361. if (pkt->duration < 0) {
  3362. av_log(s, AV_LOG_ERROR, "Application provided duration: %d is invalid\n", pkt->duration);
  3363. return AVERROR(EINVAL);
  3364. }
  3365. }
  3366. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  3367. int ret;
  3368. if (mov->fragments > 0) {
  3369. if (!trk->mdat_buf) {
  3370. if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
  3371. return ret;
  3372. }
  3373. pb = trk->mdat_buf;
  3374. } else {
  3375. if (!mov->mdat_buf) {
  3376. if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
  3377. return ret;
  3378. }
  3379. pb = mov->mdat_buf;
  3380. }
  3381. }
  3382. if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
  3383. /* We must find out how many AMR blocks there are in one packet */
  3384. static uint16_t packed_size[16] =
  3385. {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
  3386. int len = 0;
  3387. while (len < size && samples_in_chunk < 100) {
  3388. len += packed_size[(pkt->data[len] >> 3) & 0x0F];
  3389. samples_in_chunk++;
  3390. }
  3391. if (samples_in_chunk > 1) {
  3392. av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
  3393. return -1;
  3394. }
  3395. } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
  3396. enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
  3397. samples_in_chunk = enc->frame_size;
  3398. } else if (trk->sample_size)
  3399. samples_in_chunk = size / trk->sample_size;
  3400. else
  3401. samples_in_chunk = 1;
  3402. /* copy extradata if it exists */
  3403. if (trk->vos_len == 0 && enc->extradata_size > 0 && !TAG_IS_AVCI(trk->tag)) {
  3404. trk->vos_len = enc->extradata_size;
  3405. trk->vos_data = av_malloc(trk->vos_len);
  3406. memcpy(trk->vos_data, enc->extradata, trk->vos_len);
  3407. }
  3408. if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
  3409. (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
  3410. if (!s->streams[pkt->stream_index]->nb_frames) {
  3411. av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
  3412. "use the audio bitstream filter 'aac_adtstoasc' to fix it "
  3413. "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
  3414. return -1;
  3415. }
  3416. av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
  3417. }
  3418. if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
  3419. /* from x264 or from bytestream h264 */
  3420. /* nal reformating needed */
  3421. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  3422. ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
  3423. &size);
  3424. avio_write(pb, reformatted_data, size);
  3425. } else {
  3426. size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
  3427. }
  3428. } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
  3429. (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
  3430. /* extradata is Annex B, assume the bitstream is too and convert it */
  3431. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  3432. ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
  3433. avio_write(pb, reformatted_data, size);
  3434. } else {
  3435. size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
  3436. }
  3437. } else if (enc->codec_id == AV_CODEC_ID_EAC3) {
  3438. size = handle_eac3(mov, pkt, trk);
  3439. if (size < 0)
  3440. return size;
  3441. else if (!size)
  3442. goto end;
  3443. avio_write(pb, pkt->data, size);
  3444. } else {
  3445. avio_write(pb, pkt->data, size);
  3446. }
  3447. if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
  3448. enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
  3449. /* copy frame to create needed atoms */
  3450. trk->vos_len = size;
  3451. trk->vos_data = av_malloc(size);
  3452. if (!trk->vos_data)
  3453. return AVERROR(ENOMEM);
  3454. memcpy(trk->vos_data, pkt->data, size);
  3455. }
  3456. if (trk->entry >= trk->cluster_capacity) {
  3457. unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
  3458. if (av_reallocp_array(&trk->cluster, new_capacity,
  3459. sizeof(*trk->cluster)))
  3460. return AVERROR(ENOMEM);
  3461. trk->cluster_capacity = new_capacity;
  3462. }
  3463. trk->cluster[trk->entry].pos = avio_tell(pb) - size;
  3464. trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
  3465. trk->cluster[trk->entry].chunkNum = 0;
  3466. trk->cluster[trk->entry].size = size;
  3467. trk->cluster[trk->entry].entries = samples_in_chunk;
  3468. trk->cluster[trk->entry].dts = pkt->dts;
  3469. if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
  3470. /* First packet of a new fragment. We already wrote the duration
  3471. * of the last packet of the previous fragment based on track_duration,
  3472. * which might not exactly match our dts. Therefore adjust the dts
  3473. * of this packet to be what the previous packets duration implies. */
  3474. trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
  3475. }
  3476. if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !supports_edts(mov)) {
  3477. trk->cluster[trk->entry].dts = trk->start_dts = 0;
  3478. }
  3479. if (trk->start_dts == AV_NOPTS_VALUE) {
  3480. trk->start_dts = pkt->dts;
  3481. if (pkt->dts && mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
  3482. av_log(s, AV_LOG_WARNING,
  3483. "Track %d starts with a nonzero dts %"PRId64". This "
  3484. "currently isn't handled correctly in combination with "
  3485. "empty_moov.\n", pkt->stream_index, pkt->dts);
  3486. }
  3487. trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
  3488. trk->last_sample_is_subtitle_end = 0;
  3489. if (pkt->pts == AV_NOPTS_VALUE) {
  3490. av_log(s, AV_LOG_WARNING, "pts has no value\n");
  3491. pkt->pts = pkt->dts;
  3492. }
  3493. if (pkt->dts != pkt->pts)
  3494. trk->flags |= MOV_TRACK_CTTS;
  3495. trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
  3496. trk->cluster[trk->entry].flags = 0;
  3497. if (enc->codec_id == AV_CODEC_ID_VC1) {
  3498. mov_parse_vc1_frame(pkt, trk, mov->fragments);
  3499. } else if (pkt->flags & AV_PKT_FLAG_KEY) {
  3500. if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
  3501. trk->entry > 0) { // force sync sample for the first key frame
  3502. mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
  3503. if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
  3504. trk->flags |= MOV_TRACK_STPS;
  3505. } else {
  3506. trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
  3507. }
  3508. if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
  3509. trk->has_keyframes++;
  3510. }
  3511. trk->entry++;
  3512. trk->sample_count += samples_in_chunk;
  3513. mov->mdat_size += size;
  3514. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
  3515. ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
  3516. reformatted_data, size);
  3517. end:
  3518. av_free(reformatted_data);
  3519. return 0;
  3520. }
  3521. static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
  3522. {
  3523. MOVMuxContext *mov = s->priv_data;
  3524. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  3525. AVCodecContext *enc = trk->enc;
  3526. int64_t frag_duration = 0;
  3527. int size = pkt->size;
  3528. if (!pkt->size)
  3529. return 0; /* Discard 0 sized packets */
  3530. if (trk->entry && pkt->stream_index < s->nb_streams)
  3531. frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
  3532. s->streams[pkt->stream_index]->time_base,
  3533. AV_TIME_BASE_Q);
  3534. if ((mov->max_fragment_duration &&
  3535. frag_duration >= mov->max_fragment_duration) ||
  3536. (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
  3537. (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
  3538. enc->codec_type == AVMEDIA_TYPE_VIDEO &&
  3539. trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
  3540. if (frag_duration >= mov->min_fragment_duration)
  3541. mov_flush_fragment(s);
  3542. }
  3543. return ff_mov_write_packet(s, pkt);
  3544. }
  3545. static int mov_write_subtitle_end_packet(AVFormatContext *s,
  3546. int stream_index,
  3547. int64_t dts) {
  3548. AVPacket end;
  3549. uint8_t data[2] = {0};
  3550. int ret;
  3551. av_init_packet(&end);
  3552. end.size = sizeof(data);
  3553. end.data = data;
  3554. end.pts = dts;
  3555. end.dts = dts;
  3556. end.duration = 0;
  3557. end.stream_index = stream_index;
  3558. ret = mov_write_single_packet(s, &end);
  3559. av_free_packet(&end);
  3560. return ret;
  3561. }
  3562. static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  3563. {
  3564. if (!pkt) {
  3565. mov_flush_fragment(s);
  3566. return 1;
  3567. } else {
  3568. int i;
  3569. MOVMuxContext *mov = s->priv_data;
  3570. if (!pkt->size) return 0; /* Discard 0 sized packets */
  3571. /*
  3572. * Subtitles require special handling.
  3573. *
  3574. * 1) For full complaince, every track must have a sample at
  3575. * dts == 0, which is rarely true for subtitles. So, as soon
  3576. * as we see any packet with dts > 0, write an empty subtitle
  3577. * at dts == 0 for any subtitle track with no samples in it.
  3578. *
  3579. * 2) For each subtitle track, check if the current packet's
  3580. * dts is past the duration of the last subtitle sample. If
  3581. * so, we now need to write an end sample for that subtitle.
  3582. *
  3583. * This must be done conditionally to allow for subtitles that
  3584. * immediately replace each other, in which case an end sample
  3585. * is not needed, and is, in fact, actively harmful.
  3586. *
  3587. * 3) See mov_write_trailer for how the final end sample is
  3588. * handled.
  3589. */
  3590. for (i = 0; i < mov->nb_streams; i++) {
  3591. MOVTrack *trk = &mov->tracks[i];
  3592. int ret;
  3593. if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
  3594. trk->track_duration < pkt->dts &&
  3595. (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
  3596. ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
  3597. if (ret < 0) return ret;
  3598. trk->last_sample_is_subtitle_end = 1;
  3599. }
  3600. }
  3601. return mov_write_single_packet(s, pkt);
  3602. }
  3603. }
  3604. // QuickTime chapters involve an additional text track with the chapter names
  3605. // as samples, and a tref pointing from the other tracks to the chapter one.
  3606. static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
  3607. {
  3608. AVIOContext *pb;
  3609. MOVMuxContext *mov = s->priv_data;
  3610. MOVTrack *track = &mov->tracks[tracknum];
  3611. AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
  3612. int i, len;
  3613. track->mode = mov->mode;
  3614. track->tag = MKTAG('t','e','x','t');
  3615. track->timescale = MOV_TIMESCALE;
  3616. track->enc = avcodec_alloc_context3(NULL);
  3617. if (!track->enc)
  3618. return AVERROR(ENOMEM);
  3619. track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
  3620. #if 0
  3621. // These properties are required to make QT recognize the chapter track
  3622. uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
  3623. if (ff_alloc_extradata(track->enc, sizeof(chapter_properties)))
  3624. return AVERROR(ENOMEM);
  3625. memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));
  3626. #else
  3627. if (avio_open_dyn_buf(&pb) >= 0) {
  3628. int size;
  3629. uint8_t *buf;
  3630. /* Stub header (usually for Quicktime chapter track) */
  3631. // TextSampleEntry
  3632. avio_wb32(pb, 0x01); // displayFlags
  3633. avio_w8(pb, 0x00); // horizontal justification
  3634. avio_w8(pb, 0x00); // vertical justification
  3635. avio_w8(pb, 0x00); // bgColourRed
  3636. avio_w8(pb, 0x00); // bgColourGreen
  3637. avio_w8(pb, 0x00); // bgColourBlue
  3638. avio_w8(pb, 0x00); // bgColourAlpha
  3639. // BoxRecord
  3640. avio_wb16(pb, 0x00); // defTextBoxTop
  3641. avio_wb16(pb, 0x00); // defTextBoxLeft
  3642. avio_wb16(pb, 0x00); // defTextBoxBottom
  3643. avio_wb16(pb, 0x00); // defTextBoxRight
  3644. // StyleRecord
  3645. avio_wb16(pb, 0x00); // startChar
  3646. avio_wb16(pb, 0x00); // endChar
  3647. avio_wb16(pb, 0x01); // fontID
  3648. avio_w8(pb, 0x00); // fontStyleFlags
  3649. avio_w8(pb, 0x00); // fontSize
  3650. avio_w8(pb, 0x00); // fgColourRed
  3651. avio_w8(pb, 0x00); // fgColourGreen
  3652. avio_w8(pb, 0x00); // fgColourBlue
  3653. avio_w8(pb, 0x00); // fgColourAlpha
  3654. // FontTableBox
  3655. avio_wb32(pb, 0x0D); // box size
  3656. ffio_wfourcc(pb, "ftab"); // box atom name
  3657. avio_wb16(pb, 0x01); // entry count
  3658. // FontRecord
  3659. avio_wb16(pb, 0x01); // font ID
  3660. avio_w8(pb, 0x00); // font name length
  3661. if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
  3662. track->enc->extradata = buf;
  3663. track->enc->extradata_size = size;
  3664. } else {
  3665. av_freep(&buf);
  3666. }
  3667. }
  3668. #endif
  3669. for (i = 0; i < s->nb_chapters; i++) {
  3670. AVChapter *c = s->chapters[i];
  3671. AVDictionaryEntry *t;
  3672. int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
  3673. pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
  3674. pkt.duration = end - pkt.dts;
  3675. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  3676. const char encd[12] = {
  3677. 0x00, 0x00, 0x00, 0x0C,
  3678. 'e', 'n', 'c', 'd',
  3679. 0x00, 0x00, 0x01, 0x00 };
  3680. len = strlen(t->value);
  3681. pkt.size = len + 2 + 12;
  3682. pkt.data = av_malloc(pkt.size);
  3683. if (!pkt.data)
  3684. return AVERROR(ENOMEM);
  3685. AV_WB16(pkt.data, len);
  3686. memcpy(pkt.data + 2, t->value, len);
  3687. memcpy(pkt.data + len + 2, encd, sizeof(encd));
  3688. ff_mov_write_packet(s, &pkt);
  3689. av_freep(&pkt.data);
  3690. }
  3691. }
  3692. return 0;
  3693. }
  3694. static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
  3695. {
  3696. int ret;
  3697. MOVMuxContext *mov = s->priv_data;
  3698. MOVTrack *track = &mov->tracks[index];
  3699. AVStream *src_st = s->streams[src_index];
  3700. AVTimecode tc;
  3701. AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
  3702. AVRational rate = find_fps(s, src_st);
  3703. /* compute the frame number */
  3704. ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
  3705. if (ret < 0)
  3706. return ret;
  3707. /* tmcd track based on video stream */
  3708. track->mode = mov->mode;
  3709. track->tag = MKTAG('t','m','c','d');
  3710. track->src_track = src_index;
  3711. track->timescale = mov->tracks[src_index].timescale;
  3712. if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
  3713. track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
  3714. /* set st to src_st for metadata access*/
  3715. track->st = src_st;
  3716. /* encode context: tmcd data stream */
  3717. track->enc = avcodec_alloc_context3(NULL);
  3718. track->enc->codec_type = AVMEDIA_TYPE_DATA;
  3719. track->enc->codec_tag = track->tag;
  3720. track->enc->time_base = av_inv_q(rate);
  3721. /* the tmcd track just contains one packet with the frame number */
  3722. pkt.data = av_malloc(pkt.size);
  3723. AV_WB32(pkt.data, tc.start);
  3724. ret = ff_mov_write_packet(s, &pkt);
  3725. av_free(pkt.data);
  3726. return ret;
  3727. }
  3728. /*
  3729. * st->disposition controls the "enabled" flag in the tkhd tag.
  3730. * QuickTime will not play a track if it is not enabled. So make sure
  3731. * that one track of each type (audio, video, subtitle) is enabled.
  3732. *
  3733. * Subtitles are special. For audio and video, setting "enabled" also
  3734. * makes the track "default" (i.e. it is rendered when played). For
  3735. * subtitles, an "enabled" subtitle is not rendered by default, but
  3736. * if no subtitle is enabled, the subtitle menu in QuickTime will be
  3737. * empty!
  3738. */
  3739. static void enable_tracks(AVFormatContext *s)
  3740. {
  3741. MOVMuxContext *mov = s->priv_data;
  3742. int i;
  3743. int enabled[AVMEDIA_TYPE_NB];
  3744. int first[AVMEDIA_TYPE_NB];
  3745. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  3746. enabled[i] = 0;
  3747. first[i] = -1;
  3748. }
  3749. for (i = 0; i < s->nb_streams; i++) {
  3750. AVStream *st = s->streams[i];
  3751. if (st->codec->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
  3752. st->codec->codec_type >= AVMEDIA_TYPE_NB)
  3753. continue;
  3754. if (first[st->codec->codec_type] < 0)
  3755. first[st->codec->codec_type] = i;
  3756. if (st->disposition & AV_DISPOSITION_DEFAULT) {
  3757. mov->tracks[i].flags |= MOV_TRACK_ENABLED;
  3758. enabled[st->codec->codec_type]++;
  3759. }
  3760. }
  3761. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  3762. switch (i) {
  3763. case AVMEDIA_TYPE_VIDEO:
  3764. case AVMEDIA_TYPE_AUDIO:
  3765. case AVMEDIA_TYPE_SUBTITLE:
  3766. if (enabled[i] > 1)
  3767. mov->per_stream_grouping = 1;
  3768. if (!enabled[i] && first[i] >= 0)
  3769. mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
  3770. break;
  3771. }
  3772. }
  3773. }
  3774. static void mov_free(AVFormatContext *s)
  3775. {
  3776. MOVMuxContext *mov = s->priv_data;
  3777. int i;
  3778. if (mov->chapter_track) {
  3779. if (mov->tracks[mov->chapter_track].enc)
  3780. av_freep(&mov->tracks[mov->chapter_track].enc->extradata);
  3781. av_freep(&mov->tracks[mov->chapter_track].enc);
  3782. }
  3783. for (i = 0; i < mov->nb_streams; i++) {
  3784. if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
  3785. ff_mov_close_hinting(&mov->tracks[i]);
  3786. else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
  3787. av_freep(&mov->tracks[i].enc);
  3788. av_freep(&mov->tracks[i].cluster);
  3789. av_freep(&mov->tracks[i].frag_info);
  3790. if (mov->tracks[i].vos_len)
  3791. av_freep(&mov->tracks[i].vos_data);
  3792. }
  3793. av_freep(&mov->tracks);
  3794. }
  3795. static uint32_t rgb_to_yuv(uint32_t rgb)
  3796. {
  3797. uint8_t r, g, b;
  3798. int y, cb, cr;
  3799. r = (rgb >> 16) & 0xFF;
  3800. g = (rgb >> 8) & 0xFF;
  3801. b = (rgb ) & 0xFF;
  3802. y = av_clip_uint8( 16. + 0.257 * r + 0.504 * g + 0.098 * b);
  3803. cb = av_clip_uint8(128. - 0.148 * r - 0.291 * g + 0.439 * b);
  3804. cr = av_clip_uint8(128. + 0.439 * r - 0.368 * g - 0.071 * b);
  3805. return (y << 16) | (cr << 8) | cb;
  3806. }
  3807. static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
  3808. AVStream *st)
  3809. {
  3810. int i, width = 720, height = 480;
  3811. int have_palette = 0, have_size = 0;
  3812. uint32_t palette[16];
  3813. char *cur = st->codec->extradata;
  3814. while (cur && *cur) {
  3815. if (strncmp("palette:", cur, 8) == 0) {
  3816. int i, count;
  3817. count = sscanf(cur + 8,
  3818. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  3819. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  3820. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  3821. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
  3822. &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
  3823. &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
  3824. &palette[ 8], &palette[ 9], &palette[10], &palette[11],
  3825. &palette[12], &palette[13], &palette[14], &palette[15]);
  3826. for (i = 0; i < count; i++) {
  3827. palette[i] = rgb_to_yuv(palette[i]);
  3828. }
  3829. have_palette = 1;
  3830. } else if (!strncmp("size:", cur, 5)) {
  3831. sscanf(cur + 5, "%dx%d", &width, &height);
  3832. have_size = 1;
  3833. }
  3834. if (have_palette && have_size)
  3835. break;
  3836. cur += strcspn(cur, "\n\r");
  3837. cur += strspn(cur, "\n\r");
  3838. }
  3839. if (have_palette) {
  3840. track->vos_data = av_malloc(16*4);
  3841. if (!track->vos_data)
  3842. return AVERROR(ENOMEM);
  3843. for (i = 0; i < 16; i++) {
  3844. AV_WB32(track->vos_data + i * 4, palette[i]);
  3845. }
  3846. track->vos_len = 16 * 4;
  3847. }
  3848. st->codec->width = width;
  3849. st->codec->height = track->height = height;
  3850. return 0;
  3851. }
  3852. static int mov_write_header(AVFormatContext *s)
  3853. {
  3854. AVIOContext *pb = s->pb;
  3855. MOVMuxContext *mov = s->priv_data;
  3856. AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  3857. int i, ret, hint_track = 0, tmcd_track = 0;
  3858. mov->fc = s;
  3859. /* Default mode == MP4 */
  3860. mov->mode = MODE_MP4;
  3861. if (s->oformat) {
  3862. if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
  3863. else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
  3864. else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
  3865. else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
  3866. else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
  3867. else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
  3868. else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
  3869. }
  3870. if (s->flags & AVFMT_FLAG_BITEXACT)
  3871. mov->exact = 1;
  3872. /* Set the FRAGMENT flag if any of the fragmentation methods are
  3873. * enabled. */
  3874. if (mov->max_fragment_duration || mov->max_fragment_size ||
  3875. mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
  3876. FF_MOV_FLAG_FRAG_KEYFRAME |
  3877. FF_MOV_FLAG_FRAG_CUSTOM))
  3878. mov->flags |= FF_MOV_FLAG_FRAGMENT;
  3879. /* Set other implicit flags immediately */
  3880. if (mov->mode == MODE_ISM)
  3881. mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
  3882. FF_MOV_FLAG_FRAGMENT;
  3883. /* faststart: moov at the beginning of the file, if supported */
  3884. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  3885. if ((mov->flags & FF_MOV_FLAG_FRAGMENT) ||
  3886. (s->flags & AVFMT_FLAG_CUSTOM_IO)) {
  3887. av_log(s, AV_LOG_WARNING, "The faststart flag is incompatible "
  3888. "with fragmentation and custom IO, disabling faststart\n");
  3889. mov->flags &= ~FF_MOV_FLAG_FASTSTART;
  3890. } else
  3891. mov->reserved_moov_size = -1;
  3892. }
  3893. if (!supports_edts(mov) && s->avoid_negative_ts < 0) {
  3894. s->avoid_negative_ts = 2;
  3895. }
  3896. /* Non-seekable output is ok if using fragmentation. If ism_lookahead
  3897. * is enabled, we don't support non-seekable output at all. */
  3898. if (!s->pb->seekable &&
  3899. (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
  3900. av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
  3901. return AVERROR(EINVAL);
  3902. }
  3903. mov_write_ftyp_tag(pb,s);
  3904. if (mov->mode == MODE_PSP) {
  3905. int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
  3906. for (i = 0; i < s->nb_streams; i++) {
  3907. AVStream *st = s->streams[i];
  3908. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  3909. video_streams_nb++;
  3910. else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  3911. audio_streams_nb++;
  3912. else
  3913. other_streams_nb++;
  3914. }
  3915. if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
  3916. av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
  3917. return AVERROR(EINVAL);
  3918. }
  3919. mov_write_uuidprof_tag(pb, s);
  3920. }
  3921. mov->nb_streams = s->nb_streams;
  3922. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
  3923. mov->chapter_track = mov->nb_streams++;
  3924. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  3925. /* Add hint tracks for each audio and video stream */
  3926. hint_track = mov->nb_streams;
  3927. for (i = 0; i < s->nb_streams; i++) {
  3928. AVStream *st = s->streams[i];
  3929. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  3930. st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  3931. mov->nb_streams++;
  3932. }
  3933. }
  3934. }
  3935. if (mov->mode == MODE_MOV) {
  3936. tmcd_track = mov->nb_streams;
  3937. /* +1 tmcd track for each video stream with a timecode */
  3938. for (i = 0; i < s->nb_streams; i++) {
  3939. AVStream *st = s->streams[i];
  3940. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  3941. (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
  3942. mov->nb_meta_tmcd++;
  3943. }
  3944. /* check if there is already a tmcd track to remux */
  3945. if (mov->nb_meta_tmcd) {
  3946. for (i = 0; i < s->nb_streams; i++) {
  3947. AVStream *st = s->streams[i];
  3948. if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
  3949. av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
  3950. "so timecode metadata are now ignored\n");
  3951. mov->nb_meta_tmcd = 0;
  3952. }
  3953. }
  3954. }
  3955. mov->nb_streams += mov->nb_meta_tmcd;
  3956. }
  3957. // Reserve an extra stream for chapters for the case where chapters
  3958. // are written in the trailer
  3959. mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
  3960. if (!mov->tracks)
  3961. return AVERROR(ENOMEM);
  3962. for (i = 0; i < s->nb_streams; i++) {
  3963. AVStream *st= s->streams[i];
  3964. MOVTrack *track= &mov->tracks[i];
  3965. AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
  3966. track->st = st;
  3967. track->enc = st->codec;
  3968. track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
  3969. if (track->language < 0)
  3970. track->language = 0;
  3971. track->mode = mov->mode;
  3972. track->tag = mov_find_codec_tag(s, track);
  3973. if (!track->tag) {
  3974. av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
  3975. "codec not currently supported in container\n",
  3976. avcodec_get_name(st->codec->codec_id), i);
  3977. ret = AVERROR(EINVAL);
  3978. goto error;
  3979. }
  3980. /* If hinting of this track is enabled by a later hint track,
  3981. * this is updated. */
  3982. track->hint_track = -1;
  3983. track->start_dts = AV_NOPTS_VALUE;
  3984. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  3985. if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
  3986. track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
  3987. track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
  3988. if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
  3989. av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
  3990. ret = AVERROR(EINVAL);
  3991. goto error;
  3992. }
  3993. track->height = track->tag >> 24 == 'n' ? 486 : 576;
  3994. }
  3995. if (mov->video_track_timescale) {
  3996. track->timescale = mov->video_track_timescale;
  3997. } else {
  3998. track->timescale = st->time_base.den;
  3999. while(track->timescale < 10000)
  4000. track->timescale *= 2;
  4001. }
  4002. if (st->codec->width > 65535 || st->codec->height > 65535) {
  4003. av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codec->width, st->codec->height);
  4004. ret = AVERROR(EINVAL);
  4005. goto error;
  4006. }
  4007. if (track->mode == MODE_MOV && track->timescale > 100000)
  4008. av_log(s, AV_LOG_WARNING,
  4009. "WARNING codec timebase is very high. If duration is too long,\n"
  4010. "file may not be playable by quicktime. Specify a shorter timebase\n"
  4011. "or choose different container.\n");
  4012. } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  4013. track->timescale = st->codec->sample_rate;
  4014. if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
  4015. av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
  4016. track->audio_vbr = 1;
  4017. }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
  4018. st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  4019. st->codec->codec_id == AV_CODEC_ID_ILBC){
  4020. if (!st->codec->block_align) {
  4021. av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
  4022. ret = AVERROR(EINVAL);
  4023. goto error;
  4024. }
  4025. track->sample_size = st->codec->block_align;
  4026. }else if (st->codec->frame_size > 1){ /* assume compressed audio */
  4027. track->audio_vbr = 1;
  4028. }else{
  4029. track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
  4030. }
  4031. if (st->codec->codec_id == AV_CODEC_ID_ILBC ||
  4032. st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
  4033. track->audio_vbr = 1;
  4034. }
  4035. if (track->mode != MODE_MOV &&
  4036. track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
  4037. av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",
  4038. i, track->enc->sample_rate);
  4039. ret = AVERROR(EINVAL);
  4040. goto error;
  4041. }
  4042. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  4043. track->timescale = st->time_base.den;
  4044. } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
  4045. track->timescale = st->time_base.den;
  4046. } else {
  4047. track->timescale = MOV_TIMESCALE;
  4048. }
  4049. if (!track->height)
  4050. track->height = st->codec->height;
  4051. /* The ism specific timescale isn't mandatory, but is assumed by
  4052. * some tools, such as mp4split. */
  4053. if (mov->mode == MODE_ISM)
  4054. track->timescale = 10000000;
  4055. avpriv_set_pts_info(st, 64, 1, track->timescale);
  4056. /* copy extradata if it exists */
  4057. if (st->codec->extradata_size) {
  4058. if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  4059. mov_create_dvd_sub_decoder_specific_info(track, st);
  4060. else if (!TAG_IS_AVCI(track->tag)){
  4061. track->vos_len = st->codec->extradata_size;
  4062. track->vos_data = av_malloc(track->vos_len);
  4063. memcpy(track->vos_data, st->codec->extradata, track->vos_len);
  4064. }
  4065. }
  4066. }
  4067. for (i = 0; i < s->nb_streams; i++) {
  4068. int j;
  4069. AVStream *st= s->streams[i];
  4070. MOVTrack *track= &mov->tracks[i];
  4071. if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
  4072. track->enc->channel_layout != AV_CH_LAYOUT_MONO)
  4073. continue;
  4074. for (j = 0; j < s->nb_streams; j++) {
  4075. AVStream *stj= s->streams[j];
  4076. MOVTrack *trackj= &mov->tracks[j];
  4077. if (j == i)
  4078. continue;
  4079. if (stj->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
  4080. trackj->enc->channel_layout != AV_CH_LAYOUT_MONO ||
  4081. trackj->language != track->language ||
  4082. trackj->tag != track->tag
  4083. )
  4084. continue;
  4085. track->multichannel_as_mono++;
  4086. }
  4087. }
  4088. enable_tracks(s);
  4089. if (mov->reserved_moov_size){
  4090. mov->reserved_moov_pos= avio_tell(pb);
  4091. if (mov->reserved_moov_size > 0)
  4092. avio_skip(pb, mov->reserved_moov_size);
  4093. }
  4094. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  4095. /* If no fragmentation options have been set, set a default. */
  4096. if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
  4097. FF_MOV_FLAG_FRAG_CUSTOM)) &&
  4098. !mov->max_fragment_duration && !mov->max_fragment_size)
  4099. mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
  4100. } else {
  4101. if (mov->flags & FF_MOV_FLAG_FASTSTART)
  4102. mov->reserved_moov_pos = avio_tell(pb);
  4103. mov_write_mdat_tag(pb, mov);
  4104. }
  4105. if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
  4106. mov->time = ff_iso8601_to_unix_time(t->value);
  4107. if (mov->time)
  4108. mov->time += 0x7C25B080; // 1970 based -> 1904 based
  4109. if (mov->chapter_track)
  4110. if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  4111. goto error;
  4112. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  4113. /* Initialize the hint tracks for each audio and video stream */
  4114. for (i = 0; i < s->nb_streams; i++) {
  4115. AVStream *st = s->streams[i];
  4116. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  4117. st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  4118. if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
  4119. goto error;
  4120. hint_track++;
  4121. }
  4122. }
  4123. }
  4124. if (mov->nb_meta_tmcd) {
  4125. /* Initialize the tmcd tracks */
  4126. for (i = 0; i < s->nb_streams; i++) {
  4127. AVStream *st = s->streams[i];
  4128. t = global_tcr;
  4129. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  4130. if (!t)
  4131. t = av_dict_get(st->metadata, "timecode", NULL, 0);
  4132. if (!t)
  4133. continue;
  4134. if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
  4135. goto error;
  4136. tmcd_track++;
  4137. }
  4138. }
  4139. }
  4140. avio_flush(pb);
  4141. if (mov->flags & FF_MOV_FLAG_ISML)
  4142. mov_write_isml_manifest(pb, mov);
  4143. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  4144. mov_write_moov_tag(pb, mov, s);
  4145. mov->fragments++;
  4146. }
  4147. return 0;
  4148. error:
  4149. mov_free(s);
  4150. return ret;
  4151. }
  4152. static int get_moov_size(AVFormatContext *s)
  4153. {
  4154. int ret;
  4155. AVIOContext *moov_buf;
  4156. MOVMuxContext *mov = s->priv_data;
  4157. if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
  4158. return ret;
  4159. mov_write_moov_tag(moov_buf, mov, s);
  4160. return ffio_close_null_buf(moov_buf);
  4161. }
  4162. /*
  4163. * This function gets the moov size if moved to the top of the file: the chunk
  4164. * offset table can switch between stco (32-bit entries) to co64 (64-bit
  4165. * entries) when the moov is moved to the beginning, so the size of the moov
  4166. * would change. It also updates the chunk offset tables.
  4167. */
  4168. static int compute_moov_size(AVFormatContext *s)
  4169. {
  4170. int i, moov_size, moov_size2;
  4171. MOVMuxContext *mov = s->priv_data;
  4172. moov_size = get_moov_size(s);
  4173. if (moov_size < 0)
  4174. return moov_size;
  4175. for (i = 0; i < mov->nb_streams; i++)
  4176. mov->tracks[i].data_offset += moov_size;
  4177. moov_size2 = get_moov_size(s);
  4178. if (moov_size2 < 0)
  4179. return moov_size2;
  4180. /* if the size changed, we just switched from stco to co64 and need to
  4181. * update the offsets */
  4182. if (moov_size2 != moov_size)
  4183. for (i = 0; i < mov->nb_streams; i++)
  4184. mov->tracks[i].data_offset += moov_size2 - moov_size;
  4185. return moov_size2;
  4186. }
  4187. static int shift_data(AVFormatContext *s)
  4188. {
  4189. int ret = 0, moov_size;
  4190. MOVMuxContext *mov = s->priv_data;
  4191. int64_t pos, pos_end = avio_tell(s->pb);
  4192. uint8_t *buf, *read_buf[2];
  4193. int read_buf_id = 0;
  4194. int read_size[2];
  4195. AVIOContext *read_pb;
  4196. moov_size = compute_moov_size(s);
  4197. if (moov_size < 0)
  4198. return moov_size;
  4199. buf = av_malloc(moov_size * 2);
  4200. if (!buf)
  4201. return AVERROR(ENOMEM);
  4202. read_buf[0] = buf;
  4203. read_buf[1] = buf + moov_size;
  4204. /* Shift the data: the AVIO context of the output can only be used for
  4205. * writing, so we re-open the same output, but for reading. It also avoids
  4206. * a read/seek/write/seek back and forth. */
  4207. avio_flush(s->pb);
  4208. ret = avio_open(&read_pb, s->filename, AVIO_FLAG_READ);
  4209. if (ret < 0) {
  4210. av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
  4211. "the second pass (faststart)\n", s->filename);
  4212. goto end;
  4213. }
  4214. /* mark the end of the shift to up to the last data we wrote, and get ready
  4215. * for writing */
  4216. pos_end = avio_tell(s->pb);
  4217. avio_seek(s->pb, mov->reserved_moov_pos + moov_size, SEEK_SET);
  4218. /* start reading at where the new moov will be placed */
  4219. avio_seek(read_pb, mov->reserved_moov_pos, SEEK_SET);
  4220. pos = avio_tell(read_pb);
  4221. #define READ_BLOCK do { \
  4222. read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
  4223. read_buf_id ^= 1; \
  4224. } while (0)
  4225. /* shift data by chunk of at most moov_size */
  4226. READ_BLOCK;
  4227. do {
  4228. int n;
  4229. READ_BLOCK;
  4230. n = read_size[read_buf_id];
  4231. if (n <= 0)
  4232. break;
  4233. avio_write(s->pb, read_buf[read_buf_id], n);
  4234. pos += n;
  4235. } while (pos < pos_end);
  4236. avio_close(read_pb);
  4237. end:
  4238. av_free(buf);
  4239. return ret;
  4240. }
  4241. static int mov_write_trailer(AVFormatContext *s)
  4242. {
  4243. MOVMuxContext *mov = s->priv_data;
  4244. AVIOContext *pb = s->pb;
  4245. int res = 0;
  4246. int i;
  4247. int64_t moov_pos;
  4248. /*
  4249. * Before actually writing the trailer, make sure that there are no
  4250. * dangling subtitles, that need a terminating sample.
  4251. */
  4252. for (i = 0; i < mov->nb_streams; i++) {
  4253. MOVTrack *trk = &mov->tracks[i];
  4254. if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
  4255. !trk->last_sample_is_subtitle_end) {
  4256. mov_write_subtitle_end_packet(s, i, trk->track_duration);
  4257. trk->last_sample_is_subtitle_end = 1;
  4258. }
  4259. }
  4260. // If there were no chapters when the header was written, but there
  4261. // are chapters now, write them in the trailer. This only works
  4262. // when we are not doing fragments.
  4263. if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  4264. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
  4265. mov->chapter_track = mov->nb_streams++;
  4266. if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  4267. goto error;
  4268. }
  4269. }
  4270. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  4271. moov_pos = avio_tell(pb);
  4272. /* Write size of mdat tag */
  4273. if (mov->mdat_size + 8 <= UINT32_MAX) {
  4274. avio_seek(pb, mov->mdat_pos, SEEK_SET);
  4275. avio_wb32(pb, mov->mdat_size + 8);
  4276. } else {
  4277. /* overwrite 'wide' placeholder atom */
  4278. avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
  4279. /* special value: real atom size will be 64 bit value after
  4280. * tag field */
  4281. avio_wb32(pb, 1);
  4282. ffio_wfourcc(pb, "mdat");
  4283. avio_wb64(pb, mov->mdat_size + 16);
  4284. }
  4285. avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);
  4286. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  4287. av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
  4288. res = shift_data(s);
  4289. if (res == 0) {
  4290. avio_seek(s->pb, mov->reserved_moov_pos, SEEK_SET);
  4291. mov_write_moov_tag(pb, mov, s);
  4292. }
  4293. } else if (mov->reserved_moov_size > 0) {
  4294. int64_t size;
  4295. mov_write_moov_tag(pb, mov, s);
  4296. size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);
  4297. if (size < 8){
  4298. av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
  4299. return -1;
  4300. }
  4301. avio_wb32(pb, size);
  4302. ffio_wfourcc(pb, "free");
  4303. ffio_fill(pb, 0, size - 8);
  4304. avio_seek(pb, moov_pos, SEEK_SET);
  4305. } else {
  4306. mov_write_moov_tag(pb, mov, s);
  4307. }
  4308. } else {
  4309. mov_flush_fragment(s);
  4310. mov_write_mfra_tag(pb, mov);
  4311. }
  4312. for (i = 0; i < mov->nb_streams; i++) {
  4313. if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
  4314. mov->tracks[i].vc1_info.struct_offset && s->pb->seekable) {
  4315. int64_t off = avio_tell(pb);
  4316. uint8_t buf[7];
  4317. if (mov_write_dvc1_structs(&mov->tracks[i], buf) >= 0) {
  4318. avio_seek(pb, mov->tracks[i].vc1_info.struct_offset, SEEK_SET);
  4319. avio_write(pb, buf, 7);
  4320. avio_seek(pb, off, SEEK_SET);
  4321. }
  4322. }
  4323. }
  4324. error:
  4325. mov_free(s);
  4326. return res;
  4327. }
  4328. #if CONFIG_MOV_MUXER
  4329. MOV_CLASS(mov)
  4330. AVOutputFormat ff_mov_muxer = {
  4331. .name = "mov",
  4332. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  4333. .extensions = "mov",
  4334. .priv_data_size = sizeof(MOVMuxContext),
  4335. .audio_codec = AV_CODEC_ID_AAC,
  4336. .video_codec = CONFIG_LIBX264_ENCODER ?
  4337. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  4338. .write_header = mov_write_header,
  4339. .write_packet = mov_write_packet,
  4340. .write_trailer = mov_write_trailer,
  4341. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  4342. .codec_tag = (const AVCodecTag* const []){
  4343. ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
  4344. },
  4345. .priv_class = &mov_muxer_class,
  4346. };
  4347. #endif
  4348. #if CONFIG_TGP_MUXER
  4349. MOV_CLASS(tgp)
  4350. AVOutputFormat ff_tgp_muxer = {
  4351. .name = "3gp",
  4352. .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
  4353. .extensions = "3gp",
  4354. .priv_data_size = sizeof(MOVMuxContext),
  4355. .audio_codec = AV_CODEC_ID_AMR_NB,
  4356. .video_codec = AV_CODEC_ID_H263,
  4357. .write_header = mov_write_header,
  4358. .write_packet = mov_write_packet,
  4359. .write_trailer = mov_write_trailer,
  4360. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  4361. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  4362. .priv_class = &tgp_muxer_class,
  4363. };
  4364. #endif
  4365. #if CONFIG_MP4_MUXER
  4366. MOV_CLASS(mp4)
  4367. AVOutputFormat ff_mp4_muxer = {
  4368. .name = "mp4",
  4369. .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
  4370. .mime_type = "application/mp4",
  4371. .extensions = "mp4",
  4372. .priv_data_size = sizeof(MOVMuxContext),
  4373. .audio_codec = AV_CODEC_ID_AAC,
  4374. .video_codec = CONFIG_LIBX264_ENCODER ?
  4375. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  4376. .write_header = mov_write_header,
  4377. .write_packet = mov_write_packet,
  4378. .write_trailer = mov_write_trailer,
  4379. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  4380. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  4381. .priv_class = &mp4_muxer_class,
  4382. };
  4383. #endif
  4384. #if CONFIG_PSP_MUXER
  4385. MOV_CLASS(psp)
  4386. AVOutputFormat ff_psp_muxer = {
  4387. .name = "psp",
  4388. .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
  4389. .extensions = "mp4,psp",
  4390. .priv_data_size = sizeof(MOVMuxContext),
  4391. .audio_codec = AV_CODEC_ID_AAC,
  4392. .video_codec = CONFIG_LIBX264_ENCODER ?
  4393. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  4394. .write_header = mov_write_header,
  4395. .write_packet = mov_write_packet,
  4396. .write_trailer = mov_write_trailer,
  4397. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  4398. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  4399. .priv_class = &psp_muxer_class,
  4400. };
  4401. #endif
  4402. #if CONFIG_TG2_MUXER
  4403. MOV_CLASS(tg2)
  4404. AVOutputFormat ff_tg2_muxer = {
  4405. .name = "3g2",
  4406. .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
  4407. .extensions = "3g2",
  4408. .priv_data_size = sizeof(MOVMuxContext),
  4409. .audio_codec = AV_CODEC_ID_AMR_NB,
  4410. .video_codec = AV_CODEC_ID_H263,
  4411. .write_header = mov_write_header,
  4412. .write_packet = mov_write_packet,
  4413. .write_trailer = mov_write_trailer,
  4414. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  4415. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  4416. .priv_class = &tg2_muxer_class,
  4417. };
  4418. #endif
  4419. #if CONFIG_IPOD_MUXER
  4420. MOV_CLASS(ipod)
  4421. AVOutputFormat ff_ipod_muxer = {
  4422. .name = "ipod",
  4423. .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
  4424. .mime_type = "application/mp4",
  4425. .extensions = "m4v,m4a",
  4426. .priv_data_size = sizeof(MOVMuxContext),
  4427. .audio_codec = AV_CODEC_ID_AAC,
  4428. .video_codec = AV_CODEC_ID_H264,
  4429. .write_header = mov_write_header,
  4430. .write_packet = mov_write_packet,
  4431. .write_trailer = mov_write_trailer,
  4432. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  4433. .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
  4434. .priv_class = &ipod_muxer_class,
  4435. };
  4436. #endif
  4437. #if CONFIG_ISMV_MUXER
  4438. MOV_CLASS(ismv)
  4439. AVOutputFormat ff_ismv_muxer = {
  4440. .name = "ismv",
  4441. .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
  4442. .mime_type = "application/mp4",
  4443. .extensions = "ismv,isma",
  4444. .priv_data_size = sizeof(MOVMuxContext),
  4445. .audio_codec = AV_CODEC_ID_AAC,
  4446. .video_codec = AV_CODEC_ID_H264,
  4447. .write_header = mov_write_header,
  4448. .write_packet = mov_write_packet,
  4449. .write_trailer = mov_write_trailer,
  4450. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  4451. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  4452. .priv_class = &ismv_muxer_class,
  4453. };
  4454. #endif
  4455. #if CONFIG_F4V_MUXER
  4456. MOV_CLASS(f4v)
  4457. AVOutputFormat ff_f4v_muxer = {
  4458. .name = "f4v",
  4459. .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
  4460. .mime_type = "application/f4v",
  4461. .extensions = "f4v",
  4462. .priv_data_size = sizeof(MOVMuxContext),
  4463. .audio_codec = AV_CODEC_ID_AAC,
  4464. .video_codec = AV_CODEC_ID_H264,
  4465. .write_header = mov_write_header,
  4466. .write_packet = mov_write_packet,
  4467. .write_trailer = mov_write_trailer,
  4468. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
  4469. .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
  4470. .priv_class = &f4v_muxer_class,
  4471. };
  4472. #endif