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.

5886 lines
213KB

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