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.

5877 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, .unit = "movflags" },
  84. { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM, .unit = "movflags" },
  85. { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM, .unit = "movflags" },
  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->is_unaligned_qt_rgb && track->enc->pix_fmt == AV_PIX_FMT_PAL8) {
  1532. int i;
  1533. avio_wb16(pb, 0); /* Color table ID */
  1534. avio_wb32(pb, 0); /* Color table seed */
  1535. avio_wb16(pb, 0x8000); /* Color table flags */
  1536. avio_wb16(pb, 255); /* Color table size (zero-relative) */
  1537. for (i = 0; i < 256; i++) {
  1538. uint32_t rgb = AV_RL32(&track->palette[i]);
  1539. uint16_t r = (rgb >> 16) & 0xff;
  1540. uint16_t g = (rgb >> 8) & 0xff;
  1541. uint16_t b = rgb & 0xff;
  1542. avio_wb16(pb, 0);
  1543. avio_wb16(pb, (r << 8) | r);
  1544. avio_wb16(pb, (g << 8) | g);
  1545. avio_wb16(pb, (b << 8) | b);
  1546. }
  1547. } else
  1548. avio_wb16(pb, 0xffff); /* Reserved */
  1549. if (track->tag == MKTAG('m','p','4','v'))
  1550. mov_write_esds_tag(pb, track);
  1551. else if (track->enc->codec_id == AV_CODEC_ID_H263)
  1552. mov_write_d263_tag(pb);
  1553. else if (track->enc->codec_id == AV_CODEC_ID_AVUI ||
  1554. track->enc->codec_id == AV_CODEC_ID_SVQ3) {
  1555. mov_write_extradata_tag(pb, track);
  1556. avio_wb32(pb, 0);
  1557. } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD) {
  1558. mov_write_avid_tag(pb, track);
  1559. avid = 1;
  1560. } else if (track->enc->codec_id == AV_CODEC_ID_HEVC)
  1561. mov_write_hvcc_tag(pb, track);
  1562. else if (track->enc->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
  1563. mov_write_avcc_tag(pb, track);
  1564. if (track->mode == MODE_IPOD)
  1565. mov_write_uuid_tag_ipod(pb);
  1566. } else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
  1567. mov_write_dvc1_tag(pb, track);
  1568. else if (track->enc->codec_id == AV_CODEC_ID_VP6F ||
  1569. track->enc->codec_id == AV_CODEC_ID_VP6A) {
  1570. /* Don't write any potential extradata here - the cropping
  1571. * is signalled via the normal width/height fields. */
  1572. } else if (track->enc->codec_id == AV_CODEC_ID_R10K) {
  1573. if (track->enc->codec_tag == MKTAG('R','1','0','k'))
  1574. mov_write_dpxe_tag(pb, track);
  1575. } else if (track->vos_len > 0)
  1576. mov_write_glbl_tag(pb, track);
  1577. if (track->enc->codec_id != AV_CODEC_ID_H264 &&
  1578. track->enc->codec_id != AV_CODEC_ID_MPEG4 &&
  1579. track->enc->codec_id != AV_CODEC_ID_DNXHD)
  1580. if (track->enc->field_order != AV_FIELD_UNKNOWN)
  1581. mov_write_fiel_tag(pb, track);
  1582. if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
  1583. if (track->mode == MODE_MOV)
  1584. mov_write_gama_tag(pb, track, mov->gamma);
  1585. else
  1586. av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
  1587. }
  1588. if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
  1589. if (track->mode == MODE_MOV || track->mode == MODE_MP4)
  1590. mov_write_colr_tag(pb, track);
  1591. else
  1592. av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
  1593. }
  1594. if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&
  1595. track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {
  1596. mov_write_pasp_tag(pb, track);
  1597. }
  1598. if (mov->encryption_scheme != MOV_ENC_NONE) {
  1599. ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
  1600. }
  1601. /* extra padding for avid stsd */
  1602. /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
  1603. if (avid)
  1604. avio_wb32(pb, 0);
  1605. return update_size(pb, pos);
  1606. }
  1607. static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
  1608. {
  1609. int64_t pos = avio_tell(pb);
  1610. avio_wb32(pb, 0); /* size */
  1611. ffio_wfourcc(pb, "rtp ");
  1612. avio_wb32(pb, 0); /* Reserved */
  1613. avio_wb16(pb, 0); /* Reserved */
  1614. avio_wb16(pb, 1); /* Data-reference index */
  1615. avio_wb16(pb, 1); /* Hint track version */
  1616. avio_wb16(pb, 1); /* Highest compatible version */
  1617. avio_wb32(pb, track->max_packet_size); /* Max packet size */
  1618. avio_wb32(pb, 12); /* size */
  1619. ffio_wfourcc(pb, "tims");
  1620. avio_wb32(pb, track->timescale);
  1621. return update_size(pb, pos);
  1622. }
  1623. static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
  1624. {
  1625. uint64_t str_size =strlen(reel_name);
  1626. int64_t pos = avio_tell(pb);
  1627. if (str_size >= UINT16_MAX){
  1628. av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
  1629. avio_wb16(pb, 0);
  1630. return AVERROR(EINVAL);
  1631. }
  1632. avio_wb32(pb, 0); /* size */
  1633. ffio_wfourcc(pb, "name"); /* Data format */
  1634. avio_wb16(pb, str_size); /* string size */
  1635. avio_wb16(pb, track->language); /* langcode */
  1636. avio_write(pb, reel_name, str_size); /* reel name */
  1637. return update_size(pb,pos);
  1638. }
  1639. static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
  1640. {
  1641. int64_t pos = avio_tell(pb);
  1642. #if 1
  1643. int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);
  1644. int nb_frames = ROUNDED_DIV(track->enc->time_base.den, track->enc->time_base.num);
  1645. AVDictionaryEntry *t = NULL;
  1646. if (nb_frames > 255) {
  1647. av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
  1648. return AVERROR(EINVAL);
  1649. }
  1650. avio_wb32(pb, 0); /* size */
  1651. ffio_wfourcc(pb, "tmcd"); /* Data format */
  1652. avio_wb32(pb, 0); /* Reserved */
  1653. avio_wb32(pb, 1); /* Data reference index */
  1654. avio_wb32(pb, 0); /* Flags */
  1655. avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
  1656. avio_wb32(pb, track->timescale); /* Timescale */
  1657. avio_wb32(pb, frame_duration); /* Frame duration */
  1658. avio_w8(pb, nb_frames); /* Number of frames */
  1659. avio_w8(pb, 0); /* Reserved */
  1660. if (track->st)
  1661. t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
  1662. if (t && utf8len(t->value))
  1663. mov_write_source_reference_tag(pb, track, t->value);
  1664. else
  1665. avio_wb16(pb, 0); /* zero size */
  1666. #else
  1667. avio_wb32(pb, 0); /* size */
  1668. ffio_wfourcc(pb, "tmcd"); /* Data format */
  1669. avio_wb32(pb, 0); /* Reserved */
  1670. avio_wb32(pb, 1); /* Data reference index */
  1671. if (track->enc->extradata_size)
  1672. avio_write(pb, track->enc->extradata, track->enc->extradata_size);
  1673. #endif
  1674. return update_size(pb, pos);
  1675. }
  1676. static int mov_write_stsd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  1677. {
  1678. int64_t pos = avio_tell(pb);
  1679. avio_wb32(pb, 0); /* size */
  1680. ffio_wfourcc(pb, "stsd");
  1681. avio_wb32(pb, 0); /* version & flags */
  1682. avio_wb32(pb, 1); /* entry count */
  1683. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
  1684. mov_write_video_tag(pb, mov, track);
  1685. else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
  1686. mov_write_audio_tag(pb, mov, track);
  1687. else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
  1688. mov_write_subtitle_tag(pb, track);
  1689. else if (track->enc->codec_tag == MKTAG('r','t','p',' '))
  1690. mov_write_rtp_tag(pb, track);
  1691. else if (track->enc->codec_tag == MKTAG('t','m','c','d'))
  1692. mov_write_tmcd_tag(pb, track);
  1693. return update_size(pb, pos);
  1694. }
  1695. static int mov_write_ctts_tag(AVIOContext *pb, MOVTrack *track)
  1696. {
  1697. MOVStts *ctts_entries;
  1698. uint32_t entries = 0;
  1699. uint32_t atom_size;
  1700. int i;
  1701. ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
  1702. if (!ctts_entries)
  1703. return AVERROR(ENOMEM);
  1704. ctts_entries[0].count = 1;
  1705. ctts_entries[0].duration = track->cluster[0].cts;
  1706. for (i = 1; i < track->entry; i++) {
  1707. if (track->cluster[i].cts == ctts_entries[entries].duration) {
  1708. ctts_entries[entries].count++; /* compress */
  1709. } else {
  1710. entries++;
  1711. ctts_entries[entries].duration = track->cluster[i].cts;
  1712. ctts_entries[entries].count = 1;
  1713. }
  1714. }
  1715. entries++; /* last one */
  1716. atom_size = 16 + (entries * 8);
  1717. avio_wb32(pb, atom_size); /* size */
  1718. ffio_wfourcc(pb, "ctts");
  1719. avio_wb32(pb, 0); /* version & flags */
  1720. avio_wb32(pb, entries); /* entry count */
  1721. for (i = 0; i < entries; i++) {
  1722. avio_wb32(pb, ctts_entries[i].count);
  1723. avio_wb32(pb, ctts_entries[i].duration);
  1724. }
  1725. av_free(ctts_entries);
  1726. return atom_size;
  1727. }
  1728. /* Time to sample atom */
  1729. static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
  1730. {
  1731. MOVStts *stts_entries = NULL;
  1732. uint32_t entries = -1;
  1733. uint32_t atom_size;
  1734. int i;
  1735. if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
  1736. stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
  1737. if (!stts_entries)
  1738. return AVERROR(ENOMEM);
  1739. stts_entries[0].count = track->sample_count;
  1740. stts_entries[0].duration = 1;
  1741. entries = 1;
  1742. } else {
  1743. if (track->entry) {
  1744. stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
  1745. if (!stts_entries)
  1746. return AVERROR(ENOMEM);
  1747. }
  1748. for (i = 0; i < track->entry; i++) {
  1749. int duration = get_cluster_duration(track, i);
  1750. if (i && duration == stts_entries[entries].duration) {
  1751. stts_entries[entries].count++; /* compress */
  1752. } else {
  1753. entries++;
  1754. stts_entries[entries].duration = duration;
  1755. stts_entries[entries].count = 1;
  1756. }
  1757. }
  1758. entries++; /* last one */
  1759. }
  1760. atom_size = 16 + (entries * 8);
  1761. avio_wb32(pb, atom_size); /* size */
  1762. ffio_wfourcc(pb, "stts");
  1763. avio_wb32(pb, 0); /* version & flags */
  1764. avio_wb32(pb, entries); /* entry count */
  1765. for (i = 0; i < entries; i++) {
  1766. avio_wb32(pb, stts_entries[i].count);
  1767. avio_wb32(pb, stts_entries[i].duration);
  1768. }
  1769. av_free(stts_entries);
  1770. return atom_size;
  1771. }
  1772. static int mov_write_dref_tag(AVIOContext *pb)
  1773. {
  1774. avio_wb32(pb, 28); /* size */
  1775. ffio_wfourcc(pb, "dref");
  1776. avio_wb32(pb, 0); /* version & flags */
  1777. avio_wb32(pb, 1); /* entry count */
  1778. avio_wb32(pb, 0xc); /* size */
  1779. //FIXME add the alis and rsrc atom
  1780. ffio_wfourcc(pb, "url ");
  1781. avio_wb32(pb, 1); /* version & flags */
  1782. return 28;
  1783. }
  1784. static int mov_write_stbl_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  1785. {
  1786. int64_t pos = avio_tell(pb);
  1787. int ret;
  1788. avio_wb32(pb, 0); /* size */
  1789. ffio_wfourcc(pb, "stbl");
  1790. mov_write_stsd_tag(pb, mov, track);
  1791. mov_write_stts_tag(pb, track);
  1792. if ((track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
  1793. track->enc->codec_tag == MKTAG('r','t','p',' ')) &&
  1794. track->has_keyframes && track->has_keyframes < track->entry)
  1795. mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
  1796. if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
  1797. mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
  1798. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO &&
  1799. track->flags & MOV_TRACK_CTTS && track->entry) {
  1800. if ((ret = mov_write_ctts_tag(pb, track)) < 0)
  1801. return ret;
  1802. }
  1803. mov_write_stsc_tag(pb, track);
  1804. mov_write_stsz_tag(pb, track);
  1805. mov_write_stco_tag(pb, track);
  1806. if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
  1807. ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
  1808. }
  1809. return update_size(pb, pos);
  1810. }
  1811. static int mov_write_dinf_tag(AVIOContext *pb)
  1812. {
  1813. int64_t pos = avio_tell(pb);
  1814. avio_wb32(pb, 0); /* size */
  1815. ffio_wfourcc(pb, "dinf");
  1816. mov_write_dref_tag(pb);
  1817. return update_size(pb, pos);
  1818. }
  1819. static int mov_write_nmhd_tag(AVIOContext *pb)
  1820. {
  1821. avio_wb32(pb, 12);
  1822. ffio_wfourcc(pb, "nmhd");
  1823. avio_wb32(pb, 0);
  1824. return 12;
  1825. }
  1826. static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
  1827. {
  1828. int64_t pos = avio_tell(pb);
  1829. const char *font = "Lucida Grande";
  1830. avio_wb32(pb, 0); /* size */
  1831. ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
  1832. avio_wb32(pb, 0); /* version & flags */
  1833. avio_wb16(pb, 0); /* text font */
  1834. avio_wb16(pb, 0); /* text face */
  1835. avio_wb16(pb, 12); /* text size */
  1836. avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
  1837. avio_wb16(pb, 0x0000); /* text color (red) */
  1838. avio_wb16(pb, 0x0000); /* text color (green) */
  1839. avio_wb16(pb, 0x0000); /* text color (blue) */
  1840. avio_wb16(pb, 0xffff); /* background color (red) */
  1841. avio_wb16(pb, 0xffff); /* background color (green) */
  1842. avio_wb16(pb, 0xffff); /* background color (blue) */
  1843. avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
  1844. avio_write(pb, font, strlen(font)); /* font name */
  1845. return update_size(pb, pos);
  1846. }
  1847. static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
  1848. {
  1849. int64_t pos = avio_tell(pb);
  1850. avio_wb32(pb, 0); /* size */
  1851. ffio_wfourcc(pb, "gmhd");
  1852. avio_wb32(pb, 0x18); /* gmin size */
  1853. ffio_wfourcc(pb, "gmin");/* generic media info */
  1854. avio_wb32(pb, 0); /* version & flags */
  1855. avio_wb16(pb, 0x40); /* graphics mode = */
  1856. avio_wb16(pb, 0x8000); /* opColor (r?) */
  1857. avio_wb16(pb, 0x8000); /* opColor (g?) */
  1858. avio_wb16(pb, 0x8000); /* opColor (b?) */
  1859. avio_wb16(pb, 0); /* balance */
  1860. avio_wb16(pb, 0); /* reserved */
  1861. /*
  1862. * This special text atom is required for
  1863. * Apple Quicktime chapters. The contents
  1864. * don't appear to be documented, so the
  1865. * bytes are copied verbatim.
  1866. */
  1867. if (track->tag != MKTAG('c','6','0','8')) {
  1868. avio_wb32(pb, 0x2C); /* size */
  1869. ffio_wfourcc(pb, "text");
  1870. avio_wb16(pb, 0x01);
  1871. avio_wb32(pb, 0x00);
  1872. avio_wb32(pb, 0x00);
  1873. avio_wb32(pb, 0x00);
  1874. avio_wb32(pb, 0x01);
  1875. avio_wb32(pb, 0x00);
  1876. avio_wb32(pb, 0x00);
  1877. avio_wb32(pb, 0x00);
  1878. avio_wb32(pb, 0x00004000);
  1879. avio_wb16(pb, 0x0000);
  1880. }
  1881. if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
  1882. int64_t tmcd_pos = avio_tell(pb);
  1883. avio_wb32(pb, 0); /* size */
  1884. ffio_wfourcc(pb, "tmcd");
  1885. mov_write_tcmi_tag(pb, track);
  1886. update_size(pb, tmcd_pos);
  1887. }
  1888. return update_size(pb, pos);
  1889. }
  1890. static int mov_write_smhd_tag(AVIOContext *pb)
  1891. {
  1892. avio_wb32(pb, 16); /* size */
  1893. ffio_wfourcc(pb, "smhd");
  1894. avio_wb32(pb, 0); /* version & flags */
  1895. avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
  1896. avio_wb16(pb, 0); /* reserved */
  1897. return 16;
  1898. }
  1899. static int mov_write_vmhd_tag(AVIOContext *pb)
  1900. {
  1901. avio_wb32(pb, 0x14); /* size (always 0x14) */
  1902. ffio_wfourcc(pb, "vmhd");
  1903. avio_wb32(pb, 0x01); /* version & flags */
  1904. avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
  1905. return 0x14;
  1906. }
  1907. static int is_clcp_track(MOVTrack *track)
  1908. {
  1909. return track->tag == MKTAG('c','7','0','8') ||
  1910. track->tag == MKTAG('c','6','0','8');
  1911. }
  1912. static int mov_write_hdlr_tag(AVIOContext *pb, MOVTrack *track)
  1913. {
  1914. const char *hdlr, *descr = NULL, *hdlr_type = NULL;
  1915. int64_t pos = avio_tell(pb);
  1916. hdlr = "dhlr";
  1917. hdlr_type = "url ";
  1918. descr = "DataHandler";
  1919. if (track) {
  1920. hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
  1921. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1922. hdlr_type = "vide";
  1923. descr = "VideoHandler";
  1924. } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
  1925. hdlr_type = "soun";
  1926. descr = "SoundHandler";
  1927. } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  1928. if (is_clcp_track(track)) {
  1929. hdlr_type = "clcp";
  1930. descr = "ClosedCaptionHandler";
  1931. } else {
  1932. if (track->tag == MKTAG('t','x','3','g')) {
  1933. hdlr_type = "sbtl";
  1934. } else if (track->tag == MKTAG('m','p','4','s')) {
  1935. hdlr_type = "subp";
  1936. } else {
  1937. hdlr_type = "text";
  1938. }
  1939. descr = "SubtitleHandler";
  1940. }
  1941. } else if (track->enc->codec_tag == MKTAG('r','t','p',' ')) {
  1942. hdlr_type = "hint";
  1943. descr = "HintHandler";
  1944. } else if (track->enc->codec_tag == MKTAG('t','m','c','d')) {
  1945. hdlr_type = "tmcd";
  1946. descr = "TimeCodeHandler";
  1947. } else {
  1948. char tag_buf[32];
  1949. av_get_codec_tag_string(tag_buf, sizeof(tag_buf),
  1950. track->enc->codec_tag);
  1951. av_log(track->enc, AV_LOG_WARNING,
  1952. "Unknown hldr_type for %s / 0x%04X, writing dummy values\n",
  1953. tag_buf, track->enc->codec_tag);
  1954. }
  1955. if (track->st) {
  1956. // hdlr.name is used by some players to identify the content title
  1957. // of the track. So if an alternate handler description is
  1958. // specified, use it.
  1959. AVDictionaryEntry *t;
  1960. t = av_dict_get(track->st->metadata, "handler", NULL, 0);
  1961. if (t && utf8len(t->value))
  1962. descr = t->value;
  1963. }
  1964. }
  1965. avio_wb32(pb, 0); /* size */
  1966. ffio_wfourcc(pb, "hdlr");
  1967. avio_wb32(pb, 0); /* Version & flags */
  1968. avio_write(pb, hdlr, 4); /* handler */
  1969. ffio_wfourcc(pb, hdlr_type); /* handler type */
  1970. avio_wb32(pb, 0); /* reserved */
  1971. avio_wb32(pb, 0); /* reserved */
  1972. avio_wb32(pb, 0); /* reserved */
  1973. if (!track || track->mode == MODE_MOV)
  1974. avio_w8(pb, strlen(descr)); /* pascal string */
  1975. avio_write(pb, descr, strlen(descr)); /* handler description */
  1976. if (track && track->mode != MODE_MOV)
  1977. avio_w8(pb, 0); /* c string */
  1978. return update_size(pb, pos);
  1979. }
  1980. static int mov_write_hmhd_tag(AVIOContext *pb)
  1981. {
  1982. /* This atom must be present, but leaving the values at zero
  1983. * seems harmless. */
  1984. avio_wb32(pb, 28); /* size */
  1985. ffio_wfourcc(pb, "hmhd");
  1986. avio_wb32(pb, 0); /* version, flags */
  1987. avio_wb16(pb, 0); /* maxPDUsize */
  1988. avio_wb16(pb, 0); /* avgPDUsize */
  1989. avio_wb32(pb, 0); /* maxbitrate */
  1990. avio_wb32(pb, 0); /* avgbitrate */
  1991. avio_wb32(pb, 0); /* reserved */
  1992. return 28;
  1993. }
  1994. static int mov_write_minf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  1995. {
  1996. int64_t pos = avio_tell(pb);
  1997. int ret;
  1998. avio_wb32(pb, 0); /* size */
  1999. ffio_wfourcc(pb, "minf");
  2000. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO)
  2001. mov_write_vmhd_tag(pb);
  2002. else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
  2003. mov_write_smhd_tag(pb);
  2004. else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  2005. if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
  2006. mov_write_gmhd_tag(pb, track);
  2007. } else {
  2008. mov_write_nmhd_tag(pb);
  2009. }
  2010. } else if (track->tag == MKTAG('r','t','p',' ')) {
  2011. mov_write_hmhd_tag(pb);
  2012. } else if (track->tag == MKTAG('t','m','c','d')) {
  2013. mov_write_gmhd_tag(pb, track);
  2014. }
  2015. if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
  2016. mov_write_hdlr_tag(pb, NULL);
  2017. mov_write_dinf_tag(pb);
  2018. if ((ret = mov_write_stbl_tag(pb, mov, track)) < 0)
  2019. return ret;
  2020. return update_size(pb, pos);
  2021. }
  2022. static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  2023. MOVTrack *track)
  2024. {
  2025. int version = track->track_duration < INT32_MAX ? 0 : 1;
  2026. if (track->mode == MODE_ISM)
  2027. version = 1;
  2028. (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
  2029. ffio_wfourcc(pb, "mdhd");
  2030. avio_w8(pb, version);
  2031. avio_wb24(pb, 0); /* flags */
  2032. if (version == 1) {
  2033. avio_wb64(pb, track->time);
  2034. avio_wb64(pb, track->time);
  2035. } else {
  2036. avio_wb32(pb, track->time); /* creation time */
  2037. avio_wb32(pb, track->time); /* modification time */
  2038. }
  2039. avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
  2040. if (!track->entry && mov->mode == MODE_ISM)
  2041. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  2042. else if (!track->entry)
  2043. (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
  2044. else
  2045. (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
  2046. avio_wb16(pb, track->language); /* language */
  2047. avio_wb16(pb, 0); /* reserved (quality) */
  2048. if (version != 0 && track->mode == MODE_MOV) {
  2049. av_log(NULL, AV_LOG_ERROR,
  2050. "FATAL error, file duration too long for timebase, this file will not be\n"
  2051. "playable with quicktime. Choose a different timebase or a different\n"
  2052. "container format\n");
  2053. }
  2054. return 32;
  2055. }
  2056. static int mov_write_mdia_tag(AVIOContext *pb, MOVMuxContext *mov,
  2057. MOVTrack *track)
  2058. {
  2059. int64_t pos = avio_tell(pb);
  2060. int ret;
  2061. avio_wb32(pb, 0); /* size */
  2062. ffio_wfourcc(pb, "mdia");
  2063. mov_write_mdhd_tag(pb, mov, track);
  2064. mov_write_hdlr_tag(pb, track);
  2065. if ((ret = mov_write_minf_tag(pb, mov, track)) < 0)
  2066. return ret;
  2067. return update_size(pb, pos);
  2068. }
  2069. /* transformation matrix
  2070. |a b u|
  2071. |c d v|
  2072. |tx ty w| */
  2073. static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
  2074. int16_t d, int16_t tx, int16_t ty)
  2075. {
  2076. avio_wb32(pb, a << 16); /* 16.16 format */
  2077. avio_wb32(pb, b << 16); /* 16.16 format */
  2078. avio_wb32(pb, 0); /* u in 2.30 format */
  2079. avio_wb32(pb, c << 16); /* 16.16 format */
  2080. avio_wb32(pb, d << 16); /* 16.16 format */
  2081. avio_wb32(pb, 0); /* v in 2.30 format */
  2082. avio_wb32(pb, tx << 16); /* 16.16 format */
  2083. avio_wb32(pb, ty << 16); /* 16.16 format */
  2084. avio_wb32(pb, 1 << 30); /* w in 2.30 format */
  2085. }
  2086. static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  2087. MOVTrack *track, AVStream *st)
  2088. {
  2089. int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
  2090. track->timescale, AV_ROUND_UP);
  2091. int version = duration < INT32_MAX ? 0 : 1;
  2092. int flags = MOV_TKHD_FLAG_IN_MOVIE;
  2093. int rotation = 0;
  2094. int group = 0;
  2095. uint32_t *display_matrix = NULL;
  2096. int display_matrix_size, i;
  2097. if (st) {
  2098. if (mov->per_stream_grouping)
  2099. group = st->index;
  2100. else
  2101. group = st->codec->codec_type;
  2102. display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
  2103. &display_matrix_size);
  2104. if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
  2105. display_matrix = NULL;
  2106. }
  2107. if (track->flags & MOV_TRACK_ENABLED)
  2108. flags |= MOV_TKHD_FLAG_ENABLED;
  2109. if (track->mode == MODE_ISM)
  2110. version = 1;
  2111. (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
  2112. ffio_wfourcc(pb, "tkhd");
  2113. avio_w8(pb, version);
  2114. avio_wb24(pb, flags);
  2115. if (version == 1) {
  2116. avio_wb64(pb, track->time);
  2117. avio_wb64(pb, track->time);
  2118. } else {
  2119. avio_wb32(pb, track->time); /* creation time */
  2120. avio_wb32(pb, track->time); /* modification time */
  2121. }
  2122. avio_wb32(pb, track->track_id); /* track-id */
  2123. avio_wb32(pb, 0); /* reserved */
  2124. if (!track->entry && mov->mode == MODE_ISM)
  2125. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  2126. else if (!track->entry)
  2127. (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
  2128. else
  2129. (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
  2130. avio_wb32(pb, 0); /* reserved */
  2131. avio_wb32(pb, 0); /* reserved */
  2132. avio_wb16(pb, 0); /* layer */
  2133. avio_wb16(pb, group); /* alternate group) */
  2134. /* Volume, only for audio */
  2135. if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO)
  2136. avio_wb16(pb, 0x0100);
  2137. else
  2138. avio_wb16(pb, 0);
  2139. avio_wb16(pb, 0); /* reserved */
  2140. /* Matrix structure */
  2141. if (st && st->metadata) {
  2142. AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
  2143. rotation = (rot && rot->value) ? atoi(rot->value) : 0;
  2144. }
  2145. if (display_matrix) {
  2146. for (i = 0; i < 9; i++)
  2147. avio_wb32(pb, display_matrix[i]);
  2148. } else if (rotation == 90) {
  2149. write_matrix(pb, 0, 1, -1, 0, track->enc->height, 0);
  2150. } else if (rotation == 180) {
  2151. write_matrix(pb, -1, 0, 0, -1, track->enc->width, track->enc->height);
  2152. } else if (rotation == 270) {
  2153. write_matrix(pb, 0, -1, 1, 0, 0, track->enc->width);
  2154. } else {
  2155. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  2156. }
  2157. /* Track width and height, for visual only */
  2158. if (st && (track->enc->codec_type == AVMEDIA_TYPE_VIDEO ||
  2159. track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
  2160. if (track->mode == MODE_MOV) {
  2161. avio_wb32(pb, track->enc->width << 16);
  2162. avio_wb32(pb, track->height << 16);
  2163. } else {
  2164. int64_t track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
  2165. track->enc->width * 0x10000LL,
  2166. st->sample_aspect_ratio.den);
  2167. if (!track_width_1616 ||
  2168. track->height != track->enc->height ||
  2169. track_width_1616 > UINT32_MAX)
  2170. track_width_1616 = track->enc->width * 0x10000U;
  2171. avio_wb32(pb, track_width_1616);
  2172. avio_wb32(pb, track->height * 0x10000U);
  2173. }
  2174. } else {
  2175. avio_wb32(pb, 0);
  2176. avio_wb32(pb, 0);
  2177. }
  2178. return 0x5c;
  2179. }
  2180. static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
  2181. {
  2182. int32_t width = av_rescale(track->enc->sample_aspect_ratio.num, track->enc->width,
  2183. track->enc->sample_aspect_ratio.den);
  2184. int64_t pos = avio_tell(pb);
  2185. avio_wb32(pb, 0); /* size */
  2186. ffio_wfourcc(pb, "tapt");
  2187. avio_wb32(pb, 20);
  2188. ffio_wfourcc(pb, "clef");
  2189. avio_wb32(pb, 0);
  2190. avio_wb32(pb, width << 16);
  2191. avio_wb32(pb, track->enc->height << 16);
  2192. avio_wb32(pb, 20);
  2193. ffio_wfourcc(pb, "prof");
  2194. avio_wb32(pb, 0);
  2195. avio_wb32(pb, width << 16);
  2196. avio_wb32(pb, track->enc->height << 16);
  2197. avio_wb32(pb, 20);
  2198. ffio_wfourcc(pb, "enof");
  2199. avio_wb32(pb, 0);
  2200. avio_wb32(pb, track->enc->width << 16);
  2201. avio_wb32(pb, track->enc->height << 16);
  2202. return update_size(pb, pos);
  2203. }
  2204. // This box seems important for the psp playback ... without it the movie seems to hang
  2205. static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
  2206. MOVTrack *track)
  2207. {
  2208. int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
  2209. track->timescale, AV_ROUND_UP);
  2210. int version = duration < INT32_MAX ? 0 : 1;
  2211. int entry_size, entry_count, size;
  2212. int64_t delay, start_ct = track->start_cts;
  2213. int64_t start_dts = track->start_dts;
  2214. if (track->entry) {
  2215. if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
  2216. av_log(mov->fc, AV_LOG_DEBUG,
  2217. "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
  2218. track->cluster[0].dts, track->cluster[0].cts,
  2219. start_dts, start_ct, track->track_id);
  2220. start_dts = track->cluster[0].dts;
  2221. start_ct = track->cluster[0].cts;
  2222. }
  2223. }
  2224. delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
  2225. track->timescale, AV_ROUND_DOWN);
  2226. version |= delay < INT32_MAX ? 0 : 1;
  2227. entry_size = (version == 1) ? 20 : 12;
  2228. entry_count = 1 + (delay > 0);
  2229. size = 24 + entry_count * entry_size;
  2230. /* write the atom data */
  2231. avio_wb32(pb, size);
  2232. ffio_wfourcc(pb, "edts");
  2233. avio_wb32(pb, size - 8);
  2234. ffio_wfourcc(pb, "elst");
  2235. avio_w8(pb, version);
  2236. avio_wb24(pb, 0); /* flags */
  2237. avio_wb32(pb, entry_count);
  2238. if (delay > 0) { /* add an empty edit to delay presentation */
  2239. /* In the positive delay case, the delay includes the cts
  2240. * offset, and the second edit list entry below trims out
  2241. * the same amount from the actual content. This makes sure
  2242. * that the offsetted last sample is included in the edit
  2243. * list duration as well. */
  2244. if (version == 1) {
  2245. avio_wb64(pb, delay);
  2246. avio_wb64(pb, -1);
  2247. } else {
  2248. avio_wb32(pb, delay);
  2249. avio_wb32(pb, -1);
  2250. }
  2251. avio_wb32(pb, 0x00010000);
  2252. } else {
  2253. /* Avoid accidentally ending up with start_ct = -1 which has got a
  2254. * special meaning. Normally start_ct should end up positive or zero
  2255. * here, but use FFMIN in case dts is a a small positive integer
  2256. * rounded to 0 when represented in MOV_TIMESCALE units. */
  2257. av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
  2258. start_ct = -FFMIN(start_dts, 0);
  2259. /* Note, this delay is calculated from the pts of the first sample,
  2260. * ensuring that we don't reduce the duration for cases with
  2261. * dts<0 pts=0. */
  2262. duration += delay;
  2263. }
  2264. /* For fragmented files, we don't know the full length yet. Setting
  2265. * duration to 0 allows us to only specify the offset, including
  2266. * the rest of the content (from all future fragments) without specifying
  2267. * an explicit duration. */
  2268. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  2269. duration = 0;
  2270. /* duration */
  2271. if (version == 1) {
  2272. avio_wb64(pb, duration);
  2273. avio_wb64(pb, start_ct);
  2274. } else {
  2275. avio_wb32(pb, duration);
  2276. avio_wb32(pb, start_ct);
  2277. }
  2278. avio_wb32(pb, 0x00010000);
  2279. return size;
  2280. }
  2281. static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
  2282. {
  2283. avio_wb32(pb, 20); // size
  2284. ffio_wfourcc(pb, "tref");
  2285. avio_wb32(pb, 12); // size (subatom)
  2286. avio_wl32(pb, track->tref_tag);
  2287. avio_wb32(pb, track->tref_id);
  2288. return 20;
  2289. }
  2290. // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
  2291. static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
  2292. {
  2293. avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
  2294. ffio_wfourcc(pb, "uuid");
  2295. ffio_wfourcc(pb, "USMT");
  2296. avio_wb32(pb, 0x21d24fce);
  2297. avio_wb32(pb, 0xbb88695c);
  2298. avio_wb32(pb, 0xfac9c740);
  2299. avio_wb32(pb, 0x1c); // another size here!
  2300. ffio_wfourcc(pb, "MTDT");
  2301. avio_wb32(pb, 0x00010012);
  2302. avio_wb32(pb, 0x0a);
  2303. avio_wb32(pb, 0x55c40000);
  2304. avio_wb32(pb, 0x1);
  2305. avio_wb32(pb, 0x0);
  2306. return 0x34;
  2307. }
  2308. static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
  2309. {
  2310. AVFormatContext *ctx = track->rtp_ctx;
  2311. char buf[1000] = "";
  2312. int len;
  2313. ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
  2314. NULL, NULL, 0, 0, ctx);
  2315. av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
  2316. len = strlen(buf);
  2317. avio_wb32(pb, len + 24);
  2318. ffio_wfourcc(pb, "udta");
  2319. avio_wb32(pb, len + 16);
  2320. ffio_wfourcc(pb, "hnti");
  2321. avio_wb32(pb, len + 8);
  2322. ffio_wfourcc(pb, "sdp ");
  2323. avio_write(pb, buf, len);
  2324. return len + 24;
  2325. }
  2326. static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
  2327. const char *tag, const char *str)
  2328. {
  2329. int64_t pos = avio_tell(pb);
  2330. AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
  2331. if (!t || !utf8len(t->value))
  2332. return 0;
  2333. avio_wb32(pb, 0); /* size */
  2334. ffio_wfourcc(pb, tag); /* type */
  2335. avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
  2336. return update_size(pb, pos);
  2337. }
  2338. static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2339. AVStream *st)
  2340. {
  2341. AVIOContext *pb_buf;
  2342. int ret, size;
  2343. uint8_t *buf;
  2344. if (!st)
  2345. return 0;
  2346. ret = avio_open_dyn_buf(&pb_buf);
  2347. if (ret < 0)
  2348. return ret;
  2349. if (mov->mode & MODE_MP4)
  2350. mov_write_track_metadata(pb_buf, st, "name", "title");
  2351. if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
  2352. avio_wb32(pb, size + 8);
  2353. ffio_wfourcc(pb, "udta");
  2354. avio_write(pb, buf, size);
  2355. }
  2356. av_free(buf);
  2357. return 0;
  2358. }
  2359. static int mov_write_trak_tag(AVIOContext *pb, MOVMuxContext *mov,
  2360. MOVTrack *track, AVStream *st)
  2361. {
  2362. int64_t pos = avio_tell(pb);
  2363. int entry_backup = track->entry;
  2364. int chunk_backup = track->chunkCount;
  2365. int ret;
  2366. /* If we want to have an empty moov, but some samples already have been
  2367. * buffered (delay_moov), pretend that no samples have been written yet. */
  2368. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
  2369. track->chunkCount = track->entry = 0;
  2370. avio_wb32(pb, 0); /* size */
  2371. ffio_wfourcc(pb, "trak");
  2372. mov_write_tkhd_tag(pb, mov, track, st);
  2373. av_assert2(mov->use_editlist >= 0);
  2374. if (track->start_dts != AV_NOPTS_VALUE) {
  2375. if (mov->use_editlist)
  2376. mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
  2377. else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
  2378. av_log(mov->fc, AV_LOG_WARNING,
  2379. "Not writing any edit list even though one would have been required\n");
  2380. }
  2381. if (track->tref_tag)
  2382. mov_write_tref_tag(pb, track);
  2383. if ((ret = mov_write_mdia_tag(pb, mov, track)) < 0)
  2384. return ret;
  2385. if (track->mode == MODE_PSP)
  2386. mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
  2387. if (track->tag == MKTAG('r','t','p',' '))
  2388. mov_write_udta_sdp(pb, track);
  2389. if (track->mode == MODE_MOV) {
  2390. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  2391. double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
  2392. if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
  2393. mov_write_tapt_tag(pb, track);
  2394. }
  2395. }
  2396. if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
  2397. mov_write_tapt_tag(pb, track);
  2398. }
  2399. }
  2400. mov_write_track_udta_tag(pb, mov, st);
  2401. track->entry = entry_backup;
  2402. track->chunkCount = chunk_backup;
  2403. return update_size(pb, pos);
  2404. }
  2405. static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
  2406. {
  2407. int i, has_audio = 0, has_video = 0;
  2408. int64_t pos = avio_tell(pb);
  2409. int audio_profile = mov->iods_audio_profile;
  2410. int video_profile = mov->iods_video_profile;
  2411. for (i = 0; i < mov->nb_streams; i++) {
  2412. if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  2413. has_audio |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_AUDIO;
  2414. has_video |= mov->tracks[i].enc->codec_type == AVMEDIA_TYPE_VIDEO;
  2415. }
  2416. }
  2417. if (audio_profile < 0)
  2418. audio_profile = 0xFF - has_audio;
  2419. if (video_profile < 0)
  2420. video_profile = 0xFF - has_video;
  2421. avio_wb32(pb, 0x0); /* size */
  2422. ffio_wfourcc(pb, "iods");
  2423. avio_wb32(pb, 0); /* version & flags */
  2424. put_descr(pb, 0x10, 7);
  2425. avio_wb16(pb, 0x004f);
  2426. avio_w8(pb, 0xff);
  2427. avio_w8(pb, 0xff);
  2428. avio_w8(pb, audio_profile);
  2429. avio_w8(pb, video_profile);
  2430. avio_w8(pb, 0xff);
  2431. return update_size(pb, pos);
  2432. }
  2433. static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
  2434. {
  2435. avio_wb32(pb, 0x20); /* size */
  2436. ffio_wfourcc(pb, "trex");
  2437. avio_wb32(pb, 0); /* version & flags */
  2438. avio_wb32(pb, track->track_id); /* track ID */
  2439. avio_wb32(pb, 1); /* default sample description index */
  2440. avio_wb32(pb, 0); /* default sample duration */
  2441. avio_wb32(pb, 0); /* default sample size */
  2442. avio_wb32(pb, 0); /* default sample flags */
  2443. return 0;
  2444. }
  2445. static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
  2446. {
  2447. int64_t pos = avio_tell(pb);
  2448. int i;
  2449. avio_wb32(pb, 0x0); /* size */
  2450. ffio_wfourcc(pb, "mvex");
  2451. for (i = 0; i < mov->nb_streams; i++)
  2452. mov_write_trex_tag(pb, &mov->tracks[i]);
  2453. return update_size(pb, pos);
  2454. }
  2455. static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  2456. {
  2457. int max_track_id = 1, i;
  2458. int64_t max_track_len = 0;
  2459. int version;
  2460. for (i = 0; i < mov->nb_streams; i++) {
  2461. if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
  2462. int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
  2463. MOV_TIMESCALE,
  2464. mov->tracks[i].timescale,
  2465. AV_ROUND_UP);
  2466. if (max_track_len < max_track_len_temp)
  2467. max_track_len = max_track_len_temp;
  2468. if (max_track_id < mov->tracks[i].track_id)
  2469. max_track_id = mov->tracks[i].track_id;
  2470. }
  2471. }
  2472. /* If using delay_moov, make sure the output is the same as if no
  2473. * samples had been written yet. */
  2474. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  2475. max_track_len = 0;
  2476. max_track_id = 1;
  2477. }
  2478. version = max_track_len < UINT32_MAX ? 0 : 1;
  2479. avio_wb32(pb, version == 1 ? 120 : 108); /* size */
  2480. ffio_wfourcc(pb, "mvhd");
  2481. avio_w8(pb, version);
  2482. avio_wb24(pb, 0); /* flags */
  2483. if (version == 1) {
  2484. avio_wb64(pb, mov->time);
  2485. avio_wb64(pb, mov->time);
  2486. } else {
  2487. avio_wb32(pb, mov->time); /* creation time */
  2488. avio_wb32(pb, mov->time); /* modification time */
  2489. }
  2490. avio_wb32(pb, MOV_TIMESCALE);
  2491. (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
  2492. avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
  2493. avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
  2494. avio_wb16(pb, 0); /* reserved */
  2495. avio_wb32(pb, 0); /* reserved */
  2496. avio_wb32(pb, 0); /* reserved */
  2497. /* Matrix structure */
  2498. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  2499. avio_wb32(pb, 0); /* reserved (preview time) */
  2500. avio_wb32(pb, 0); /* reserved (preview duration) */
  2501. avio_wb32(pb, 0); /* reserved (poster time) */
  2502. avio_wb32(pb, 0); /* reserved (selection time) */
  2503. avio_wb32(pb, 0); /* reserved (selection duration) */
  2504. avio_wb32(pb, 0); /* reserved (current time) */
  2505. avio_wb32(pb, max_track_id + 1); /* Next track id */
  2506. return 0x6c;
  2507. }
  2508. static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
  2509. AVFormatContext *s)
  2510. {
  2511. avio_wb32(pb, 33); /* size */
  2512. ffio_wfourcc(pb, "hdlr");
  2513. avio_wb32(pb, 0);
  2514. avio_wb32(pb, 0);
  2515. ffio_wfourcc(pb, "mdir");
  2516. ffio_wfourcc(pb, "appl");
  2517. avio_wb32(pb, 0);
  2518. avio_wb32(pb, 0);
  2519. avio_w8(pb, 0);
  2520. return 33;
  2521. }
  2522. /* helper function to write a data tag with the specified string as data */
  2523. static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
  2524. {
  2525. if (long_style) {
  2526. int size = 16 + strlen(data);
  2527. avio_wb32(pb, size); /* size */
  2528. ffio_wfourcc(pb, "data");
  2529. avio_wb32(pb, 1);
  2530. avio_wb32(pb, 0);
  2531. avio_write(pb, data, strlen(data));
  2532. return size;
  2533. } else {
  2534. if (!lang)
  2535. lang = ff_mov_iso639_to_lang("und", 1);
  2536. avio_wb16(pb, strlen(data)); /* string length */
  2537. avio_wb16(pb, lang);
  2538. avio_write(pb, data, strlen(data));
  2539. return strlen(data) + 4;
  2540. }
  2541. }
  2542. static int mov_write_string_tag(AVIOContext *pb, const char *name,
  2543. const char *value, int lang, int long_style)
  2544. {
  2545. int size = 0;
  2546. if (value && value[0]) {
  2547. int64_t pos = avio_tell(pb);
  2548. avio_wb32(pb, 0); /* size */
  2549. ffio_wfourcc(pb, name);
  2550. mov_write_string_data_tag(pb, value, lang, long_style);
  2551. size = update_size(pb, pos);
  2552. }
  2553. return size;
  2554. }
  2555. static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
  2556. const char *name, const char *tag,
  2557. int long_style)
  2558. {
  2559. int l, lang = 0, len, len2;
  2560. AVDictionaryEntry *t, *t2 = NULL;
  2561. char tag2[16];
  2562. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  2563. return 0;
  2564. len = strlen(t->key);
  2565. snprintf(tag2, sizeof(tag2), "%s-", tag);
  2566. while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
  2567. len2 = strlen(t2->key);
  2568. if (len2 == len + 4 && !strcmp(t->value, t2->value)
  2569. && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
  2570. lang = l;
  2571. break;
  2572. }
  2573. }
  2574. return mov_write_string_tag(pb, name, t->value, lang, long_style);
  2575. }
  2576. /* iTunes bpm number */
  2577. static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
  2578. {
  2579. AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
  2580. int size = 0, tmpo = t ? atoi(t->value) : 0;
  2581. if (tmpo) {
  2582. size = 26;
  2583. avio_wb32(pb, size);
  2584. ffio_wfourcc(pb, "tmpo");
  2585. avio_wb32(pb, size-8); /* size */
  2586. ffio_wfourcc(pb, "data");
  2587. avio_wb32(pb, 0x15); //type specifier
  2588. avio_wb32(pb, 0);
  2589. avio_wb16(pb, tmpo); // data
  2590. }
  2591. return size;
  2592. }
  2593. /* iTunes track or disc number */
  2594. static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
  2595. AVFormatContext *s, int disc)
  2596. {
  2597. AVDictionaryEntry *t = av_dict_get(s->metadata,
  2598. disc ? "disc" : "track",
  2599. NULL, 0);
  2600. int size = 0, track = t ? atoi(t->value) : 0;
  2601. if (track) {
  2602. int tracks = 0;
  2603. char *slash = strchr(t->value, '/');
  2604. if (slash)
  2605. tracks = atoi(slash + 1);
  2606. avio_wb32(pb, 32); /* size */
  2607. ffio_wfourcc(pb, disc ? "disk" : "trkn");
  2608. avio_wb32(pb, 24); /* size */
  2609. ffio_wfourcc(pb, "data");
  2610. avio_wb32(pb, 0); // 8 bytes empty
  2611. avio_wb32(pb, 0);
  2612. avio_wb16(pb, 0); // empty
  2613. avio_wb16(pb, track); // track / disc number
  2614. avio_wb16(pb, tracks); // total track / disc number
  2615. avio_wb16(pb, 0); // empty
  2616. size = 32;
  2617. }
  2618. return size;
  2619. }
  2620. static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
  2621. const char *name, const char *tag,
  2622. int len)
  2623. {
  2624. AVDictionaryEntry *t = NULL;
  2625. uint8_t num;
  2626. int size = 24 + len;
  2627. if (len != 1 && len != 4)
  2628. return -1;
  2629. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  2630. return 0;
  2631. num = atoi(t->value);
  2632. avio_wb32(pb, size);
  2633. ffio_wfourcc(pb, name);
  2634. avio_wb32(pb, size - 8);
  2635. ffio_wfourcc(pb, "data");
  2636. avio_wb32(pb, 0x15);
  2637. avio_wb32(pb, 0);
  2638. if (len==4) avio_wb32(pb, num);
  2639. else avio_w8 (pb, num);
  2640. return size;
  2641. }
  2642. /* iTunes meta data list */
  2643. static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
  2644. AVFormatContext *s)
  2645. {
  2646. int64_t pos = avio_tell(pb);
  2647. avio_wb32(pb, 0); /* size */
  2648. ffio_wfourcc(pb, "ilst");
  2649. mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
  2650. mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
  2651. mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
  2652. mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
  2653. mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
  2654. mov_write_string_metadata(s, pb, "\251day", "date" , 1);
  2655. if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
  2656. if (!(s->flags & AVFMT_FLAG_BITEXACT))
  2657. mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
  2658. }
  2659. mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
  2660. mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
  2661. mov_write_string_metadata(s, pb, "\251cpy", "copyright", 1);
  2662. mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
  2663. mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
  2664. mov_write_string_metadata(s, pb, "desc", "description",1);
  2665. mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
  2666. mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
  2667. mov_write_string_metadata(s, pb, "tven", "episode_id",1);
  2668. mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
  2669. mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
  2670. mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
  2671. mov_write_int8_metadata (s, pb, "stik", "media_type",1);
  2672. mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
  2673. mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
  2674. mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
  2675. mov_write_trkn_tag(pb, mov, s, 0); // track number
  2676. mov_write_trkn_tag(pb, mov, s, 1); // disc number
  2677. mov_write_tmpo_tag(pb, s);
  2678. return update_size(pb, pos);
  2679. }
  2680. /* iTunes meta data tag */
  2681. static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2682. AVFormatContext *s)
  2683. {
  2684. int size = 0;
  2685. int64_t pos = avio_tell(pb);
  2686. avio_wb32(pb, 0); /* size */
  2687. ffio_wfourcc(pb, "meta");
  2688. avio_wb32(pb, 0);
  2689. mov_write_itunes_hdlr_tag(pb, mov, s);
  2690. mov_write_ilst_tag(pb, mov, s);
  2691. size = update_size(pb, pos);
  2692. return size;
  2693. }
  2694. static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
  2695. const char *name, const char *key)
  2696. {
  2697. int len;
  2698. AVDictionaryEntry *t;
  2699. if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
  2700. return 0;
  2701. len = strlen(t->value);
  2702. if (len > 0) {
  2703. int size = len + 8;
  2704. avio_wb32(pb, size);
  2705. ffio_wfourcc(pb, name);
  2706. avio_write(pb, t->value, len);
  2707. return size;
  2708. }
  2709. return 0;
  2710. }
  2711. static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
  2712. {
  2713. int val;
  2714. while (*b) {
  2715. GET_UTF8(val, *b++, return -1;)
  2716. avio_wb16(pb, val);
  2717. }
  2718. avio_wb16(pb, 0x00);
  2719. return 0;
  2720. }
  2721. static uint16_t language_code(const char *str)
  2722. {
  2723. return (((str[0] - 0x60) & 0x1F) << 10) +
  2724. (((str[1] - 0x60) & 0x1F) << 5) +
  2725. (( str[2] - 0x60) & 0x1F);
  2726. }
  2727. static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
  2728. const char *tag, const char *str)
  2729. {
  2730. int64_t pos = avio_tell(pb);
  2731. AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
  2732. if (!t || !utf8len(t->value))
  2733. return 0;
  2734. avio_wb32(pb, 0); /* size */
  2735. ffio_wfourcc(pb, tag); /* type */
  2736. avio_wb32(pb, 0); /* version + flags */
  2737. if (!strcmp(tag, "yrrc"))
  2738. avio_wb16(pb, atoi(t->value));
  2739. else {
  2740. avio_wb16(pb, language_code("eng")); /* language */
  2741. avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
  2742. if (!strcmp(tag, "albm") &&
  2743. (t = av_dict_get(s->metadata, "track", NULL, 0)))
  2744. avio_w8(pb, atoi(t->value));
  2745. }
  2746. return update_size(pb, pos);
  2747. }
  2748. static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
  2749. {
  2750. int64_t pos = avio_tell(pb);
  2751. int i, nb_chapters = FFMIN(s->nb_chapters, 255);
  2752. avio_wb32(pb, 0); // size
  2753. ffio_wfourcc(pb, "chpl");
  2754. avio_wb32(pb, 0x01000000); // version + flags
  2755. avio_wb32(pb, 0); // unknown
  2756. avio_w8(pb, nb_chapters);
  2757. for (i = 0; i < nb_chapters; i++) {
  2758. AVChapter *c = s->chapters[i];
  2759. AVDictionaryEntry *t;
  2760. avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
  2761. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  2762. int len = FFMIN(strlen(t->value), 255);
  2763. avio_w8(pb, len);
  2764. avio_write(pb, t->value, len);
  2765. } else
  2766. avio_w8(pb, 0);
  2767. }
  2768. return update_size(pb, pos);
  2769. }
  2770. static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2771. AVFormatContext *s)
  2772. {
  2773. AVIOContext *pb_buf;
  2774. int ret, size;
  2775. uint8_t *buf;
  2776. ret = avio_open_dyn_buf(&pb_buf);
  2777. if (ret < 0)
  2778. return ret;
  2779. if (mov->mode & MODE_3GP) {
  2780. mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
  2781. mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
  2782. mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
  2783. mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
  2784. mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
  2785. mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
  2786. mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
  2787. mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
  2788. } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
  2789. mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
  2790. mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
  2791. mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
  2792. mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
  2793. mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
  2794. mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
  2795. // currently ignored by mov.c
  2796. mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
  2797. // add support for libquicktime, this atom is also actually read by mov.c
  2798. mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
  2799. mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
  2800. mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
  2801. mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
  2802. mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
  2803. mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
  2804. mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
  2805. } else {
  2806. /* iTunes meta data */
  2807. mov_write_meta_tag(pb_buf, mov, s);
  2808. }
  2809. if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
  2810. mov_write_chpl_tag(pb_buf, s);
  2811. if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
  2812. avio_wb32(pb, size + 8);
  2813. ffio_wfourcc(pb, "udta");
  2814. avio_write(pb, buf, size);
  2815. }
  2816. av_free(buf);
  2817. return 0;
  2818. }
  2819. static void mov_write_psp_udta_tag(AVIOContext *pb,
  2820. const char *str, const char *lang, int type)
  2821. {
  2822. int len = utf8len(str) + 1;
  2823. if (len <= 0)
  2824. return;
  2825. avio_wb16(pb, len * 2 + 10); /* size */
  2826. avio_wb32(pb, type); /* type */
  2827. avio_wb16(pb, language_code(lang)); /* language */
  2828. avio_wb16(pb, 0x01); /* ? */
  2829. ascii_to_wc(pb, str);
  2830. }
  2831. static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
  2832. {
  2833. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  2834. int64_t pos, pos2;
  2835. if (title) {
  2836. pos = avio_tell(pb);
  2837. avio_wb32(pb, 0); /* size placeholder*/
  2838. ffio_wfourcc(pb, "uuid");
  2839. ffio_wfourcc(pb, "USMT");
  2840. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  2841. avio_wb32(pb, 0xbb88695c);
  2842. avio_wb32(pb, 0xfac9c740);
  2843. pos2 = avio_tell(pb);
  2844. avio_wb32(pb, 0); /* size placeholder*/
  2845. ffio_wfourcc(pb, "MTDT");
  2846. avio_wb16(pb, 4);
  2847. // ?
  2848. avio_wb16(pb, 0x0C); /* size */
  2849. avio_wb32(pb, 0x0B); /* type */
  2850. avio_wb16(pb, language_code("und")); /* language */
  2851. avio_wb16(pb, 0x0); /* ? */
  2852. avio_wb16(pb, 0x021C); /* data */
  2853. if (!(s->flags & AVFMT_FLAG_BITEXACT))
  2854. mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
  2855. mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
  2856. mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
  2857. update_size(pb, pos2);
  2858. return update_size(pb, pos);
  2859. }
  2860. return 0;
  2861. }
  2862. static void build_chunks(MOVTrack *trk)
  2863. {
  2864. int i;
  2865. MOVIentry *chunk = &trk->cluster[0];
  2866. uint64_t chunkSize = chunk->size;
  2867. chunk->chunkNum = 1;
  2868. if (trk->chunkCount)
  2869. return;
  2870. trk->chunkCount = 1;
  2871. for (i = 1; i<trk->entry; i++){
  2872. if (chunk->pos + chunkSize == trk->cluster[i].pos &&
  2873. chunkSize + trk->cluster[i].size < (1<<20)){
  2874. chunkSize += trk->cluster[i].size;
  2875. chunk->samples_in_chunk += trk->cluster[i].entries;
  2876. } else {
  2877. trk->cluster[i].chunkNum = chunk->chunkNum+1;
  2878. chunk=&trk->cluster[i];
  2879. chunkSize = chunk->size;
  2880. trk->chunkCount++;
  2881. }
  2882. }
  2883. }
  2884. static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
  2885. AVFormatContext *s)
  2886. {
  2887. int i;
  2888. int64_t pos = avio_tell(pb);
  2889. avio_wb32(pb, 0); /* size placeholder*/
  2890. ffio_wfourcc(pb, "moov");
  2891. for (i = 0; i < mov->nb_streams; i++) {
  2892. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  2893. continue;
  2894. mov->tracks[i].time = mov->time;
  2895. mov->tracks[i].track_id = i + 1;
  2896. if (mov->tracks[i].entry)
  2897. build_chunks(&mov->tracks[i]);
  2898. }
  2899. if (mov->chapter_track)
  2900. for (i = 0; i < s->nb_streams; i++) {
  2901. mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
  2902. mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
  2903. }
  2904. for (i = 0; i < mov->nb_streams; i++) {
  2905. MOVTrack *track = &mov->tracks[i];
  2906. if (track->tag == MKTAG('r','t','p',' ')) {
  2907. track->tref_tag = MKTAG('h','i','n','t');
  2908. track->tref_id = mov->tracks[track->src_track].track_id;
  2909. } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
  2910. int * fallback, size;
  2911. fallback = (int*)av_stream_get_side_data(track->st,
  2912. AV_PKT_DATA_FALLBACK_TRACK,
  2913. &size);
  2914. if (fallback != NULL && size == sizeof(int)) {
  2915. if (*fallback >= 0 && *fallback < mov->nb_streams) {
  2916. track->tref_tag = MKTAG('f','a','l','l');
  2917. track->tref_id = mov->tracks[*fallback].track_id;
  2918. }
  2919. }
  2920. }
  2921. }
  2922. for (i = 0; i < mov->nb_streams; i++) {
  2923. if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
  2924. int src_trk = mov->tracks[i].src_track;
  2925. mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
  2926. mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
  2927. //src_trk may have a different timescale than the tmcd track
  2928. mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
  2929. mov->tracks[i].timescale,
  2930. mov->tracks[src_trk].timescale);
  2931. }
  2932. }
  2933. mov_write_mvhd_tag(pb, mov);
  2934. if (mov->mode != MODE_MOV && !mov->iods_skip)
  2935. mov_write_iods_tag(pb, mov);
  2936. for (i = 0; i < mov->nb_streams; i++) {
  2937. if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
  2938. int ret = mov_write_trak_tag(pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
  2939. if (ret < 0)
  2940. return ret;
  2941. }
  2942. }
  2943. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  2944. mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
  2945. if (mov->mode == MODE_PSP)
  2946. mov_write_uuidusmt_tag(pb, s);
  2947. else
  2948. mov_write_udta_tag(pb, mov, s);
  2949. return update_size(pb, pos);
  2950. }
  2951. static void param_write_int(AVIOContext *pb, const char *name, int value)
  2952. {
  2953. avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
  2954. }
  2955. static void param_write_string(AVIOContext *pb, const char *name, const char *value)
  2956. {
  2957. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
  2958. }
  2959. static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
  2960. {
  2961. char buf[150];
  2962. len = FFMIN(sizeof(buf) / 2 - 1, len);
  2963. ff_data_to_hex(buf, value, len, 0);
  2964. buf[2 * len] = '\0';
  2965. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
  2966. }
  2967. static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov)
  2968. {
  2969. int64_t pos = avio_tell(pb);
  2970. int i;
  2971. static const uint8_t uuid[] = {
  2972. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  2973. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  2974. };
  2975. avio_wb32(pb, 0);
  2976. ffio_wfourcc(pb, "uuid");
  2977. avio_write(pb, uuid, sizeof(uuid));
  2978. avio_wb32(pb, 0);
  2979. avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  2980. avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
  2981. avio_printf(pb, "<head>\n");
  2982. if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
  2983. avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
  2984. LIBAVFORMAT_IDENT);
  2985. avio_printf(pb, "</head>\n");
  2986. avio_printf(pb, "<body>\n");
  2987. avio_printf(pb, "<switch>\n");
  2988. for (i = 0; i < mov->nb_streams; i++) {
  2989. MOVTrack *track = &mov->tracks[i];
  2990. const char *type;
  2991. /* track->track_id is initialized in write_moov, and thus isn't known
  2992. * here yet */
  2993. int track_id = i + 1;
  2994. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  2995. type = "video";
  2996. } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
  2997. type = "audio";
  2998. } else {
  2999. continue;
  3000. }
  3001. avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
  3002. (int64_t)track->enc->bit_rate);
  3003. param_write_int(pb, "systemBitrate", track->enc->bit_rate);
  3004. param_write_int(pb, "trackID", track_id);
  3005. if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  3006. if (track->enc->codec_id == AV_CODEC_ID_H264) {
  3007. uint8_t *ptr;
  3008. int size = track->enc->extradata_size;
  3009. if (!ff_avc_write_annexb_extradata(track->enc->extradata, &ptr,
  3010. &size)) {
  3011. param_write_hex(pb, "CodecPrivateData",
  3012. ptr ? ptr : track->enc->extradata,
  3013. size);
  3014. av_free(ptr);
  3015. }
  3016. param_write_string(pb, "FourCC", "H264");
  3017. } else if (track->enc->codec_id == AV_CODEC_ID_VC1) {
  3018. param_write_string(pb, "FourCC", "WVC1");
  3019. param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
  3020. track->enc->extradata_size);
  3021. }
  3022. param_write_int(pb, "MaxWidth", track->enc->width);
  3023. param_write_int(pb, "MaxHeight", track->enc->height);
  3024. param_write_int(pb, "DisplayWidth", track->enc->width);
  3025. param_write_int(pb, "DisplayHeight", track->enc->height);
  3026. } else {
  3027. if (track->enc->codec_id == AV_CODEC_ID_AAC) {
  3028. switch (track->enc->profile)
  3029. {
  3030. case FF_PROFILE_AAC_HE_V2:
  3031. param_write_string(pb, "FourCC", "AACP");
  3032. break;
  3033. case FF_PROFILE_AAC_HE:
  3034. param_write_string(pb, "FourCC", "AACH");
  3035. break;
  3036. default:
  3037. param_write_string(pb, "FourCC", "AACL");
  3038. }
  3039. } else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO) {
  3040. param_write_string(pb, "FourCC", "WMAP");
  3041. }
  3042. param_write_hex(pb, "CodecPrivateData", track->enc->extradata,
  3043. track->enc->extradata_size);
  3044. param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
  3045. track->enc->codec_id));
  3046. param_write_int(pb, "Channels", track->enc->channels);
  3047. param_write_int(pb, "SamplingRate", track->enc->sample_rate);
  3048. param_write_int(pb, "BitsPerSample", 16);
  3049. param_write_int(pb, "PacketSize", track->enc->block_align ?
  3050. track->enc->block_align : 4);
  3051. }
  3052. avio_printf(pb, "</%s>\n", type);
  3053. }
  3054. avio_printf(pb, "</switch>\n");
  3055. avio_printf(pb, "</body>\n");
  3056. avio_printf(pb, "</smil>\n");
  3057. return update_size(pb, pos);
  3058. }
  3059. static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  3060. {
  3061. avio_wb32(pb, 16);
  3062. ffio_wfourcc(pb, "mfhd");
  3063. avio_wb32(pb, 0);
  3064. avio_wb32(pb, mov->fragments);
  3065. return 0;
  3066. }
  3067. static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
  3068. {
  3069. return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
  3070. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
  3071. }
  3072. static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  3073. MOVTrack *track, int64_t moof_offset)
  3074. {
  3075. int64_t pos = avio_tell(pb);
  3076. uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  3077. MOV_TFHD_BASE_DATA_OFFSET;
  3078. if (!track->entry) {
  3079. flags |= MOV_TFHD_DURATION_IS_EMPTY;
  3080. } else {
  3081. flags |= MOV_TFHD_DEFAULT_FLAGS;
  3082. }
  3083. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
  3084. flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
  3085. if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
  3086. flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
  3087. flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
  3088. }
  3089. /* Don't set a default sample size, the silverlight player refuses
  3090. * to play files with that set. Don't set a default sample duration,
  3091. * WMP freaks out if it is set. Don't set a base data offset, PIFF
  3092. * file format says it MUST NOT be set. */
  3093. if (track->mode == MODE_ISM)
  3094. flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  3095. MOV_TFHD_BASE_DATA_OFFSET);
  3096. avio_wb32(pb, 0); /* size placeholder */
  3097. ffio_wfourcc(pb, "tfhd");
  3098. avio_w8(pb, 0); /* version */
  3099. avio_wb24(pb, flags);
  3100. avio_wb32(pb, track->track_id); /* track-id */
  3101. if (flags & MOV_TFHD_BASE_DATA_OFFSET)
  3102. avio_wb64(pb, moof_offset);
  3103. if (flags & MOV_TFHD_DEFAULT_DURATION) {
  3104. track->default_duration = get_cluster_duration(track, 0);
  3105. avio_wb32(pb, track->default_duration);
  3106. }
  3107. if (flags & MOV_TFHD_DEFAULT_SIZE) {
  3108. track->default_size = track->entry ? track->cluster[0].size : 1;
  3109. avio_wb32(pb, track->default_size);
  3110. } else
  3111. track->default_size = -1;
  3112. if (flags & MOV_TFHD_DEFAULT_FLAGS) {
  3113. /* Set the default flags based on the second sample, if available.
  3114. * If the first sample is different, that can be signaled via a separate field. */
  3115. if (track->entry > 1)
  3116. track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
  3117. else
  3118. track->default_sample_flags =
  3119. track->enc->codec_type == AVMEDIA_TYPE_VIDEO ?
  3120. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
  3121. MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
  3122. avio_wb32(pb, track->default_sample_flags);
  3123. }
  3124. return update_size(pb, pos);
  3125. }
  3126. static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
  3127. MOVTrack *track, int moof_size,
  3128. int first, int end)
  3129. {
  3130. int64_t pos = avio_tell(pb);
  3131. uint32_t flags = MOV_TRUN_DATA_OFFSET;
  3132. int i;
  3133. for (i = first; i < end; i++) {
  3134. if (get_cluster_duration(track, i) != track->default_duration)
  3135. flags |= MOV_TRUN_SAMPLE_DURATION;
  3136. if (track->cluster[i].size != track->default_size)
  3137. flags |= MOV_TRUN_SAMPLE_SIZE;
  3138. if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
  3139. flags |= MOV_TRUN_SAMPLE_FLAGS;
  3140. }
  3141. if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
  3142. get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
  3143. flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
  3144. if (track->flags & MOV_TRACK_CTTS)
  3145. flags |= MOV_TRUN_SAMPLE_CTS;
  3146. avio_wb32(pb, 0); /* size placeholder */
  3147. ffio_wfourcc(pb, "trun");
  3148. avio_w8(pb, 0); /* version */
  3149. avio_wb24(pb, flags);
  3150. avio_wb32(pb, end - first); /* sample count */
  3151. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
  3152. !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
  3153. !mov->first_trun)
  3154. avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
  3155. else
  3156. avio_wb32(pb, moof_size + 8 + track->data_offset +
  3157. track->cluster[first].pos); /* data offset */
  3158. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
  3159. avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
  3160. for (i = first; i < end; i++) {
  3161. if (flags & MOV_TRUN_SAMPLE_DURATION)
  3162. avio_wb32(pb, get_cluster_duration(track, i));
  3163. if (flags & MOV_TRUN_SAMPLE_SIZE)
  3164. avio_wb32(pb, track->cluster[i].size);
  3165. if (flags & MOV_TRUN_SAMPLE_FLAGS)
  3166. avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
  3167. if (flags & MOV_TRUN_SAMPLE_CTS)
  3168. avio_wb32(pb, track->cluster[i].cts);
  3169. }
  3170. mov->first_trun = 0;
  3171. return update_size(pb, pos);
  3172. }
  3173. static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
  3174. {
  3175. int64_t pos = avio_tell(pb);
  3176. static const uint8_t uuid[] = {
  3177. 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
  3178. 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
  3179. };
  3180. avio_wb32(pb, 0); /* size placeholder */
  3181. ffio_wfourcc(pb, "uuid");
  3182. avio_write(pb, uuid, sizeof(uuid));
  3183. avio_w8(pb, 1);
  3184. avio_wb24(pb, 0);
  3185. avio_wb64(pb, track->start_dts + track->frag_start +
  3186. track->cluster[0].cts);
  3187. avio_wb64(pb, track->end_pts -
  3188. (track->cluster[0].dts + track->cluster[0].cts));
  3189. return update_size(pb, pos);
  3190. }
  3191. static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
  3192. MOVTrack *track, int entry)
  3193. {
  3194. int n = track->nb_frag_info - 1 - entry, i;
  3195. int size = 8 + 16 + 4 + 1 + 16*n;
  3196. static const uint8_t uuid[] = {
  3197. 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
  3198. 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
  3199. };
  3200. if (entry < 0)
  3201. return 0;
  3202. avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
  3203. avio_wb32(pb, size);
  3204. ffio_wfourcc(pb, "uuid");
  3205. avio_write(pb, uuid, sizeof(uuid));
  3206. avio_w8(pb, 1);
  3207. avio_wb24(pb, 0);
  3208. avio_w8(pb, n);
  3209. for (i = 0; i < n; i++) {
  3210. int index = entry + 1 + i;
  3211. avio_wb64(pb, track->frag_info[index].time);
  3212. avio_wb64(pb, track->frag_info[index].duration);
  3213. }
  3214. if (n < mov->ism_lookahead) {
  3215. int free_size = 16 * (mov->ism_lookahead - n);
  3216. avio_wb32(pb, free_size);
  3217. ffio_wfourcc(pb, "free");
  3218. ffio_fill(pb, 0, free_size - 8);
  3219. }
  3220. return 0;
  3221. }
  3222. static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
  3223. MOVTrack *track)
  3224. {
  3225. int64_t pos = avio_tell(pb);
  3226. int i;
  3227. for (i = 0; i < mov->ism_lookahead; i++) {
  3228. /* Update the tfrf tag for the last ism_lookahead fragments,
  3229. * nb_frag_info - 1 is the next fragment to be written. */
  3230. mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
  3231. }
  3232. avio_seek(pb, pos, SEEK_SET);
  3233. return 0;
  3234. }
  3235. static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
  3236. int size)
  3237. {
  3238. int i;
  3239. for (i = 0; i < mov->nb_streams; i++) {
  3240. MOVTrack *track = &mov->tracks[i];
  3241. MOVFragmentInfo *info;
  3242. if ((tracks >= 0 && i != tracks) || !track->entry)
  3243. continue;
  3244. track->nb_frag_info++;
  3245. if (track->nb_frag_info >= track->frag_info_capacity) {
  3246. unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
  3247. if (av_reallocp_array(&track->frag_info,
  3248. new_capacity,
  3249. sizeof(*track->frag_info)))
  3250. return AVERROR(ENOMEM);
  3251. track->frag_info_capacity = new_capacity;
  3252. }
  3253. info = &track->frag_info[track->nb_frag_info - 1];
  3254. info->offset = avio_tell(pb);
  3255. info->size = size;
  3256. // Try to recreate the original pts for the first packet
  3257. // from the fields we have stored
  3258. info->time = track->start_dts + track->frag_start +
  3259. track->cluster[0].cts;
  3260. info->duration = track->end_pts -
  3261. (track->cluster[0].dts + track->cluster[0].cts);
  3262. // If the pts is less than zero, we will have trimmed
  3263. // away parts of the media track using an edit list,
  3264. // and the corresponding start presentation time is zero.
  3265. if (info->time < 0) {
  3266. info->duration += info->time;
  3267. info->time = 0;
  3268. }
  3269. info->tfrf_offset = 0;
  3270. mov_write_tfrf_tags(pb, mov, track);
  3271. }
  3272. return 0;
  3273. }
  3274. static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
  3275. {
  3276. int64_t pos = avio_tell(pb);
  3277. avio_wb32(pb, 0); /* size */
  3278. ffio_wfourcc(pb, "tfdt");
  3279. avio_w8(pb, 1); /* version */
  3280. avio_wb24(pb, 0);
  3281. avio_wb64(pb, track->frag_start);
  3282. return update_size(pb, pos);
  3283. }
  3284. static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
  3285. MOVTrack *track, int64_t moof_offset,
  3286. int moof_size)
  3287. {
  3288. int64_t pos = avio_tell(pb);
  3289. int i, start = 0;
  3290. avio_wb32(pb, 0); /* size placeholder */
  3291. ffio_wfourcc(pb, "traf");
  3292. mov_write_tfhd_tag(pb, mov, track, moof_offset);
  3293. if (mov->mode != MODE_ISM)
  3294. mov_write_tfdt_tag(pb, track);
  3295. for (i = 1; i < track->entry; i++) {
  3296. if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
  3297. mov_write_trun_tag(pb, mov, track, moof_size, start, i);
  3298. start = i;
  3299. }
  3300. }
  3301. mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
  3302. if (mov->mode == MODE_ISM) {
  3303. mov_write_tfxd_tag(pb, track);
  3304. if (mov->ism_lookahead) {
  3305. int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
  3306. if (track->nb_frag_info > 0) {
  3307. MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
  3308. if (!info->tfrf_offset)
  3309. info->tfrf_offset = avio_tell(pb);
  3310. }
  3311. avio_wb32(pb, 8 + size);
  3312. ffio_wfourcc(pb, "free");
  3313. for (i = 0; i < size; i++)
  3314. avio_w8(pb, 0);
  3315. }
  3316. }
  3317. return update_size(pb, pos);
  3318. }
  3319. static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
  3320. int tracks, int moof_size)
  3321. {
  3322. int64_t pos = avio_tell(pb);
  3323. int i;
  3324. avio_wb32(pb, 0); /* size placeholder */
  3325. ffio_wfourcc(pb, "moof");
  3326. mov->first_trun = 1;
  3327. mov_write_mfhd_tag(pb, mov);
  3328. for (i = 0; i < mov->nb_streams; i++) {
  3329. MOVTrack *track = &mov->tracks[i];
  3330. if (tracks >= 0 && i != tracks)
  3331. continue;
  3332. if (!track->entry)
  3333. continue;
  3334. mov_write_traf_tag(pb, mov, track, pos, moof_size);
  3335. }
  3336. return update_size(pb, pos);
  3337. }
  3338. static int mov_write_sidx_tag(AVIOContext *pb,
  3339. MOVTrack *track, int ref_size, int total_sidx_size)
  3340. {
  3341. int64_t pos = avio_tell(pb), offset_pos, end_pos;
  3342. int64_t presentation_time, duration, offset;
  3343. int starts_with_SAP, i, entries;
  3344. if (track->entry) {
  3345. entries = 1;
  3346. presentation_time = track->start_dts + track->frag_start +
  3347. track->cluster[0].cts;
  3348. duration = track->end_pts -
  3349. (track->cluster[0].dts + track->cluster[0].cts);
  3350. starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
  3351. // pts<0 should be cut away using edts
  3352. if (presentation_time < 0) {
  3353. duration += presentation_time;
  3354. presentation_time = 0;
  3355. }
  3356. } else {
  3357. entries = track->nb_frag_info;
  3358. if (entries <= 0)
  3359. return 0;
  3360. presentation_time = track->frag_info[0].time;
  3361. }
  3362. avio_wb32(pb, 0); /* size */
  3363. ffio_wfourcc(pb, "sidx");
  3364. avio_w8(pb, 1); /* version */
  3365. avio_wb24(pb, 0);
  3366. avio_wb32(pb, track->track_id); /* reference_ID */
  3367. avio_wb32(pb, track->timescale); /* timescale */
  3368. avio_wb64(pb, presentation_time); /* earliest_presentation_time */
  3369. offset_pos = avio_tell(pb);
  3370. avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
  3371. avio_wb16(pb, 0); /* reserved */
  3372. avio_wb16(pb, entries); /* reference_count */
  3373. for (i = 0; i < entries; i++) {
  3374. if (!track->entry) {
  3375. if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
  3376. av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
  3377. }
  3378. duration = track->frag_info[i].duration;
  3379. ref_size = track->frag_info[i].size;
  3380. starts_with_SAP = 1;
  3381. }
  3382. avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
  3383. avio_wb32(pb, duration); /* subsegment_duration */
  3384. avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
  3385. }
  3386. end_pos = avio_tell(pb);
  3387. offset = pos + total_sidx_size - end_pos;
  3388. avio_seek(pb, offset_pos, SEEK_SET);
  3389. avio_wb64(pb, offset);
  3390. avio_seek(pb, end_pos, SEEK_SET);
  3391. return update_size(pb, pos);
  3392. }
  3393. static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
  3394. int tracks, int ref_size)
  3395. {
  3396. int i, round, ret;
  3397. AVIOContext *avio_buf;
  3398. int total_size = 0;
  3399. for (round = 0; round < 2; round++) {
  3400. // First run one round to calculate the total size of all
  3401. // sidx atoms.
  3402. // This would be much simpler if we'd only write one sidx
  3403. // atom, for the first track in the moof.
  3404. if (round == 0) {
  3405. if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
  3406. return ret;
  3407. } else {
  3408. avio_buf = pb;
  3409. }
  3410. for (i = 0; i < mov->nb_streams; i++) {
  3411. MOVTrack *track = &mov->tracks[i];
  3412. if (tracks >= 0 && i != tracks)
  3413. continue;
  3414. // When writing a sidx for the full file, entry is 0, but
  3415. // we want to include all tracks. ref_size is 0 in this case,
  3416. // since we read it from frag_info instead.
  3417. if (!track->entry && ref_size > 0)
  3418. continue;
  3419. total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
  3420. total_size);
  3421. }
  3422. if (round == 0)
  3423. total_size = ffio_close_null_buf(avio_buf);
  3424. }
  3425. return 0;
  3426. }
  3427. static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
  3428. int64_t mdat_size)
  3429. {
  3430. AVIOContext *avio_buf;
  3431. int ret, moof_size;
  3432. if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
  3433. return ret;
  3434. mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
  3435. moof_size = ffio_close_null_buf(avio_buf);
  3436. if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
  3437. mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
  3438. if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
  3439. return ret;
  3440. return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
  3441. }
  3442. static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
  3443. {
  3444. int64_t pos = avio_tell(pb);
  3445. int i;
  3446. avio_wb32(pb, 0); /* size placeholder */
  3447. ffio_wfourcc(pb, "tfra");
  3448. avio_w8(pb, 1); /* version */
  3449. avio_wb24(pb, 0);
  3450. avio_wb32(pb, track->track_id);
  3451. avio_wb32(pb, 0); /* length of traf/trun/sample num */
  3452. avio_wb32(pb, track->nb_frag_info);
  3453. for (i = 0; i < track->nb_frag_info; i++) {
  3454. avio_wb64(pb, track->frag_info[i].time);
  3455. avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
  3456. avio_w8(pb, 1); /* traf number */
  3457. avio_w8(pb, 1); /* trun number */
  3458. avio_w8(pb, 1); /* sample number */
  3459. }
  3460. return update_size(pb, pos);
  3461. }
  3462. static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
  3463. {
  3464. int64_t pos = avio_tell(pb);
  3465. int i;
  3466. avio_wb32(pb, 0); /* size placeholder */
  3467. ffio_wfourcc(pb, "mfra");
  3468. /* An empty mfra atom is enough to indicate to the publishing point that
  3469. * the stream has ended. */
  3470. if (mov->flags & FF_MOV_FLAG_ISML)
  3471. return update_size(pb, pos);
  3472. for (i = 0; i < mov->nb_streams; i++) {
  3473. MOVTrack *track = &mov->tracks[i];
  3474. if (track->nb_frag_info)
  3475. mov_write_tfra_tag(pb, track);
  3476. }
  3477. avio_wb32(pb, 16);
  3478. ffio_wfourcc(pb, "mfro");
  3479. avio_wb32(pb, 0); /* version + flags */
  3480. avio_wb32(pb, avio_tell(pb) + 4 - pos);
  3481. return update_size(pb, pos);
  3482. }
  3483. static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
  3484. {
  3485. avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
  3486. ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
  3487. mov->mdat_pos = avio_tell(pb);
  3488. avio_wb32(pb, 0); /* size placeholder*/
  3489. ffio_wfourcc(pb, "mdat");
  3490. return 0;
  3491. }
  3492. /* TODO: This needs to be more general */
  3493. static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
  3494. {
  3495. MOVMuxContext *mov = s->priv_data;
  3496. int64_t pos = avio_tell(pb);
  3497. int has_h264 = 0, has_video = 0;
  3498. int minor = 0x200;
  3499. int i;
  3500. for (i = 0; i < s->nb_streams; i++) {
  3501. AVStream *st = s->streams[i];
  3502. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  3503. has_video = 1;
  3504. if (st->codec->codec_id == AV_CODEC_ID_H264)
  3505. has_h264 = 1;
  3506. }
  3507. avio_wb32(pb, 0); /* size */
  3508. ffio_wfourcc(pb, "ftyp");
  3509. if (mov->major_brand && strlen(mov->major_brand) >= 4)
  3510. ffio_wfourcc(pb, mov->major_brand);
  3511. else if (mov->mode == MODE_3GP) {
  3512. ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
  3513. minor = has_h264 ? 0x100 : 0x200;
  3514. } else if (mov->mode & MODE_3G2) {
  3515. ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
  3516. minor = has_h264 ? 0x20000 : 0x10000;
  3517. } else if (mov->mode == MODE_PSP)
  3518. ffio_wfourcc(pb, "MSNV");
  3519. else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
  3520. ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
  3521. else if (mov->mode == MODE_MP4)
  3522. ffio_wfourcc(pb, "isom");
  3523. else if (mov->mode == MODE_IPOD)
  3524. ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
  3525. else if (mov->mode == MODE_ISM)
  3526. ffio_wfourcc(pb, "isml");
  3527. else if (mov->mode == MODE_F4V)
  3528. ffio_wfourcc(pb, "f4v ");
  3529. else
  3530. ffio_wfourcc(pb, "qt ");
  3531. avio_wb32(pb, minor);
  3532. if (mov->mode == MODE_MOV)
  3533. ffio_wfourcc(pb, "qt ");
  3534. else if (mov->mode == MODE_ISM) {
  3535. ffio_wfourcc(pb, "piff");
  3536. } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
  3537. ffio_wfourcc(pb, "isom");
  3538. ffio_wfourcc(pb, "iso2");
  3539. if (has_h264)
  3540. ffio_wfourcc(pb, "avc1");
  3541. }
  3542. // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
  3543. // brand. This is compatible with users that don't understand tfdt.
  3544. if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
  3545. ffio_wfourcc(pb, "iso6");
  3546. if (mov->mode == MODE_3GP)
  3547. ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
  3548. else if (mov->mode & MODE_3G2)
  3549. ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
  3550. else if (mov->mode == MODE_PSP)
  3551. ffio_wfourcc(pb, "MSNV");
  3552. else if (mov->mode == MODE_MP4)
  3553. ffio_wfourcc(pb, "mp41");
  3554. if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  3555. ffio_wfourcc(pb, "dash");
  3556. return update_size(pb, pos);
  3557. }
  3558. static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
  3559. {
  3560. AVStream *video_st = s->streams[0];
  3561. AVCodecContext *video_codec = s->streams[0]->codec;
  3562. AVCodecContext *audio_codec = s->streams[1]->codec;
  3563. int audio_rate = audio_codec->sample_rate;
  3564. // TODO: should be avg_frame_rate
  3565. int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);
  3566. int audio_kbitrate = audio_codec->bit_rate / 1000;
  3567. int video_kbitrate = FFMIN(video_codec->bit_rate / 1000, 800 - audio_kbitrate);
  3568. avio_wb32(pb, 0x94); /* size */
  3569. ffio_wfourcc(pb, "uuid");
  3570. ffio_wfourcc(pb, "PROF");
  3571. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  3572. avio_wb32(pb, 0xbb88695c);
  3573. avio_wb32(pb, 0xfac9c740);
  3574. avio_wb32(pb, 0x0); /* ? */
  3575. avio_wb32(pb, 0x3); /* 3 sections ? */
  3576. avio_wb32(pb, 0x14); /* size */
  3577. ffio_wfourcc(pb, "FPRF");
  3578. avio_wb32(pb, 0x0); /* ? */
  3579. avio_wb32(pb, 0x0); /* ? */
  3580. avio_wb32(pb, 0x0); /* ? */
  3581. avio_wb32(pb, 0x2c); /* size */
  3582. ffio_wfourcc(pb, "APRF"); /* audio */
  3583. avio_wb32(pb, 0x0);
  3584. avio_wb32(pb, 0x2); /* TrackID */
  3585. ffio_wfourcc(pb, "mp4a");
  3586. avio_wb32(pb, 0x20f);
  3587. avio_wb32(pb, 0x0);
  3588. avio_wb32(pb, audio_kbitrate);
  3589. avio_wb32(pb, audio_kbitrate);
  3590. avio_wb32(pb, audio_rate);
  3591. avio_wb32(pb, audio_codec->channels);
  3592. avio_wb32(pb, 0x34); /* size */
  3593. ffio_wfourcc(pb, "VPRF"); /* video */
  3594. avio_wb32(pb, 0x0);
  3595. avio_wb32(pb, 0x1); /* TrackID */
  3596. if (video_codec->codec_id == AV_CODEC_ID_H264) {
  3597. ffio_wfourcc(pb, "avc1");
  3598. avio_wb16(pb, 0x014D);
  3599. avio_wb16(pb, 0x0015);
  3600. } else {
  3601. ffio_wfourcc(pb, "mp4v");
  3602. avio_wb16(pb, 0x0000);
  3603. avio_wb16(pb, 0x0103);
  3604. }
  3605. avio_wb32(pb, 0x0);
  3606. avio_wb32(pb, video_kbitrate);
  3607. avio_wb32(pb, video_kbitrate);
  3608. avio_wb32(pb, frame_rate);
  3609. avio_wb32(pb, frame_rate);
  3610. avio_wb16(pb, video_codec->width);
  3611. avio_wb16(pb, video_codec->height);
  3612. avio_wb32(pb, 0x010001); /* ? */
  3613. }
  3614. static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
  3615. {
  3616. MOVMuxContext *mov = s->priv_data;
  3617. int i;
  3618. mov_write_ftyp_tag(pb,s);
  3619. if (mov->mode == MODE_PSP) {
  3620. int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
  3621. for (i = 0; i < s->nb_streams; i++) {
  3622. AVStream *st = s->streams[i];
  3623. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  3624. video_streams_nb++;
  3625. else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  3626. audio_streams_nb++;
  3627. else
  3628. other_streams_nb++;
  3629. }
  3630. if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
  3631. av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
  3632. return AVERROR(EINVAL);
  3633. }
  3634. mov_write_uuidprof_tag(pb, s);
  3635. }
  3636. return 0;
  3637. }
  3638. static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
  3639. {
  3640. uint32_t c = -1;
  3641. int i, closed_gop = 0;
  3642. for (i = 0; i < pkt->size - 4; i++) {
  3643. c = (c << 8) + pkt->data[i];
  3644. if (c == 0x1b8) { // gop
  3645. closed_gop = pkt->data[i + 4] >> 6 & 0x01;
  3646. } else if (c == 0x100) { // pic
  3647. int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
  3648. if (!temp_ref || closed_gop) // I picture is not reordered
  3649. *flags = MOV_SYNC_SAMPLE;
  3650. else
  3651. *flags = MOV_PARTIAL_SYNC_SAMPLE;
  3652. break;
  3653. }
  3654. }
  3655. return 0;
  3656. }
  3657. static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
  3658. {
  3659. const uint8_t *start, *next, *end = pkt->data + pkt->size;
  3660. int seq = 0, entry = 0;
  3661. int key = pkt->flags & AV_PKT_FLAG_KEY;
  3662. start = find_next_marker(pkt->data, end);
  3663. for (next = start; next < end; start = next) {
  3664. next = find_next_marker(start + 4, end);
  3665. switch (AV_RB32(start)) {
  3666. case VC1_CODE_SEQHDR:
  3667. seq = 1;
  3668. break;
  3669. case VC1_CODE_ENTRYPOINT:
  3670. entry = 1;
  3671. break;
  3672. case VC1_CODE_SLICE:
  3673. trk->vc1_info.slices = 1;
  3674. break;
  3675. }
  3676. }
  3677. if (!trk->entry && trk->vc1_info.first_packet_seen)
  3678. trk->vc1_info.first_frag_written = 1;
  3679. if (!trk->entry && !trk->vc1_info.first_frag_written) {
  3680. /* First packet in first fragment */
  3681. trk->vc1_info.first_packet_seq = seq;
  3682. trk->vc1_info.first_packet_entry = entry;
  3683. trk->vc1_info.first_packet_seen = 1;
  3684. } else if ((seq && !trk->vc1_info.packet_seq) ||
  3685. (entry && !trk->vc1_info.packet_entry)) {
  3686. int i;
  3687. for (i = 0; i < trk->entry; i++)
  3688. trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
  3689. trk->has_keyframes = 0;
  3690. if (seq)
  3691. trk->vc1_info.packet_seq = 1;
  3692. if (entry)
  3693. trk->vc1_info.packet_entry = 1;
  3694. if (!trk->vc1_info.first_frag_written) {
  3695. /* First fragment */
  3696. if ((!seq || trk->vc1_info.first_packet_seq) &&
  3697. (!entry || trk->vc1_info.first_packet_entry)) {
  3698. /* First packet had the same headers as this one, readd the
  3699. * sync sample flag. */
  3700. trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
  3701. trk->has_keyframes = 1;
  3702. }
  3703. }
  3704. }
  3705. if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
  3706. key = seq && entry;
  3707. else if (trk->vc1_info.packet_seq)
  3708. key = seq;
  3709. else if (trk->vc1_info.packet_entry)
  3710. key = entry;
  3711. if (key) {
  3712. trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
  3713. trk->has_keyframes++;
  3714. }
  3715. }
  3716. static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
  3717. {
  3718. MOVMuxContext *mov = s->priv_data;
  3719. int ret, buf_size;
  3720. uint8_t *buf;
  3721. int i, offset;
  3722. if (!track->mdat_buf)
  3723. return 0;
  3724. if (!mov->mdat_buf) {
  3725. if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
  3726. return ret;
  3727. }
  3728. buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
  3729. track->mdat_buf = NULL;
  3730. offset = avio_tell(mov->mdat_buf);
  3731. avio_write(mov->mdat_buf, buf, buf_size);
  3732. av_free(buf);
  3733. for (i = track->entries_flushed; i < track->entry; i++)
  3734. track->cluster[i].pos += offset;
  3735. track->entries_flushed = track->entry;
  3736. return 0;
  3737. }
  3738. static int mov_flush_fragment(AVFormatContext *s, int force)
  3739. {
  3740. MOVMuxContext *mov = s->priv_data;
  3741. int i, first_track = -1;
  3742. int64_t mdat_size = 0;
  3743. int ret;
  3744. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3745. return 0;
  3746. for (i = 0; i < mov->nb_streams; i++) {
  3747. MOVTrack *track = &mov->tracks[i];
  3748. if (track->entry <= 1)
  3749. continue;
  3750. // Sample durations are calculated as the diff of dts values,
  3751. // but for the last sample in a fragment, we don't know the dts
  3752. // of the first sample in the next fragment, so we have to rely
  3753. // on what was set as duration in the AVPacket. Not all callers
  3754. // set this though, so we might want to replace it with an
  3755. // estimate if it currently is zero.
  3756. if (get_cluster_duration(track, track->entry - 1) != 0)
  3757. continue;
  3758. // Use the duration (i.e. dts diff) of the second last sample for
  3759. // the last one. This is a wild guess (and fatal if it turns out
  3760. // to be too long), but probably the best we can do - having a zero
  3761. // duration is bad as well.
  3762. track->track_duration += get_cluster_duration(track, track->entry - 2);
  3763. track->end_pts += get_cluster_duration(track, track->entry - 2);
  3764. if (!mov->missing_duration_warned) {
  3765. av_log(s, AV_LOG_WARNING,
  3766. "Estimating the duration of the last packet in a "
  3767. "fragment, consider setting the duration field in "
  3768. "AVPacket instead.\n");
  3769. mov->missing_duration_warned = 1;
  3770. }
  3771. }
  3772. if (!mov->moov_written) {
  3773. int64_t pos = avio_tell(s->pb);
  3774. uint8_t *buf;
  3775. int buf_size, moov_size;
  3776. for (i = 0; i < mov->nb_streams; i++)
  3777. if (!mov->tracks[i].entry)
  3778. break;
  3779. /* Don't write the initial moov unless all tracks have data */
  3780. if (i < mov->nb_streams && !force)
  3781. return 0;
  3782. moov_size = get_moov_size(s);
  3783. for (i = 0; i < mov->nb_streams; i++)
  3784. mov->tracks[i].data_offset = pos + moov_size + 8;
  3785. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  3786. mov_write_identification(s->pb, s);
  3787. if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
  3788. return ret;
  3789. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
  3790. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  3791. mov->reserved_header_pos = avio_tell(s->pb);
  3792. avio_flush(s->pb);
  3793. mov->moov_written = 1;
  3794. return 0;
  3795. }
  3796. buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
  3797. mov->mdat_buf = NULL;
  3798. avio_wb32(s->pb, buf_size + 8);
  3799. ffio_wfourcc(s->pb, "mdat");
  3800. avio_write(s->pb, buf, buf_size);
  3801. av_free(buf);
  3802. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  3803. mov->reserved_header_pos = avio_tell(s->pb);
  3804. mov->moov_written = 1;
  3805. mov->mdat_size = 0;
  3806. for (i = 0; i < mov->nb_streams; i++) {
  3807. if (mov->tracks[i].entry)
  3808. mov->tracks[i].frag_start += mov->tracks[i].start_dts +
  3809. mov->tracks[i].track_duration -
  3810. mov->tracks[i].cluster[0].dts;
  3811. mov->tracks[i].entry = 0;
  3812. }
  3813. avio_flush(s->pb);
  3814. return 0;
  3815. }
  3816. if (mov->frag_interleave) {
  3817. for (i = 0; i < mov->nb_streams; i++) {
  3818. MOVTrack *track = &mov->tracks[i];
  3819. int ret;
  3820. if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
  3821. return ret;
  3822. }
  3823. if (!mov->mdat_buf)
  3824. return 0;
  3825. mdat_size = avio_tell(mov->mdat_buf);
  3826. }
  3827. for (i = 0; i < mov->nb_streams; i++) {
  3828. MOVTrack *track = &mov->tracks[i];
  3829. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
  3830. track->data_offset = 0;
  3831. else
  3832. track->data_offset = mdat_size;
  3833. if (!track->entry)
  3834. continue;
  3835. if (track->mdat_buf)
  3836. mdat_size += avio_tell(track->mdat_buf);
  3837. if (first_track < 0)
  3838. first_track = i;
  3839. }
  3840. if (!mdat_size)
  3841. return 0;
  3842. for (i = 0; i < mov->nb_streams; i++) {
  3843. MOVTrack *track = &mov->tracks[i];
  3844. int buf_size, write_moof = 1, moof_tracks = -1;
  3845. uint8_t *buf;
  3846. int64_t duration = 0;
  3847. if (track->entry)
  3848. duration = track->start_dts + track->track_duration -
  3849. track->cluster[0].dts;
  3850. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
  3851. if (!track->mdat_buf)
  3852. continue;
  3853. mdat_size = avio_tell(track->mdat_buf);
  3854. moof_tracks = i;
  3855. } else {
  3856. write_moof = i == first_track;
  3857. }
  3858. if (write_moof) {
  3859. avio_flush(s->pb);
  3860. mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
  3861. mov->fragments++;
  3862. avio_wb32(s->pb, mdat_size + 8);
  3863. ffio_wfourcc(s->pb, "mdat");
  3864. }
  3865. if (track->entry)
  3866. track->frag_start += duration;
  3867. track->entry = 0;
  3868. track->entries_flushed = 0;
  3869. if (!mov->frag_interleave) {
  3870. if (!track->mdat_buf)
  3871. continue;
  3872. buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
  3873. track->mdat_buf = NULL;
  3874. } else {
  3875. if (!mov->mdat_buf)
  3876. continue;
  3877. buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
  3878. mov->mdat_buf = NULL;
  3879. }
  3880. avio_write(s->pb, buf, buf_size);
  3881. av_free(buf);
  3882. }
  3883. mov->mdat_size = 0;
  3884. avio_flush(s->pb);
  3885. return 0;
  3886. }
  3887. static int mov_auto_flush_fragment(AVFormatContext *s, int force)
  3888. {
  3889. MOVMuxContext *mov = s->priv_data;
  3890. int had_moov = mov->moov_written;
  3891. int ret = mov_flush_fragment(s, force);
  3892. if (ret < 0)
  3893. return ret;
  3894. // If using delay_moov, the first flush only wrote the moov,
  3895. // not the actual moof+mdat pair, thus flush once again.
  3896. if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  3897. ret = mov_flush_fragment(s, force);
  3898. return ret;
  3899. }
  3900. int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  3901. {
  3902. MOVMuxContext *mov = s->priv_data;
  3903. AVIOContext *pb = s->pb;
  3904. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  3905. AVCodecContext *enc = trk->enc;
  3906. unsigned int samples_in_chunk = 0;
  3907. int size = pkt->size, ret = 0;
  3908. uint8_t *reformatted_data = NULL;
  3909. if (trk->entry) {
  3910. int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts;
  3911. if (duration < 0 || duration > INT_MAX) {
  3912. av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
  3913. duration, pkt->dts
  3914. );
  3915. pkt->dts = trk->cluster[trk->entry - 1].dts + 1;
  3916. pkt->pts = AV_NOPTS_VALUE;
  3917. }
  3918. }
  3919. if (pkt->duration < 0 || pkt->duration > INT_MAX) {
  3920. av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
  3921. return AVERROR(EINVAL);
  3922. }
  3923. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  3924. int ret;
  3925. if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  3926. if (mov->frag_interleave && mov->fragments > 0) {
  3927. if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
  3928. if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
  3929. return ret;
  3930. }
  3931. }
  3932. if (!trk->mdat_buf) {
  3933. if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
  3934. return ret;
  3935. }
  3936. pb = trk->mdat_buf;
  3937. } else {
  3938. if (!mov->mdat_buf) {
  3939. if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
  3940. return ret;
  3941. }
  3942. pb = mov->mdat_buf;
  3943. }
  3944. }
  3945. if (enc->codec_id == AV_CODEC_ID_AMR_NB) {
  3946. /* We must find out how many AMR blocks there are in one packet */
  3947. static const uint16_t packed_size[16] =
  3948. {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
  3949. int len = 0;
  3950. while (len < size && samples_in_chunk < 100) {
  3951. len += packed_size[(pkt->data[len] >> 3) & 0x0F];
  3952. samples_in_chunk++;
  3953. }
  3954. if (samples_in_chunk > 1) {
  3955. av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
  3956. return -1;
  3957. }
  3958. } else if (enc->codec_id == AV_CODEC_ID_ADPCM_MS ||
  3959. enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
  3960. samples_in_chunk = enc->frame_size;
  3961. } else if (trk->sample_size)
  3962. samples_in_chunk = size / trk->sample_size;
  3963. else
  3964. samples_in_chunk = 1;
  3965. /* copy extradata if it exists */
  3966. if (trk->vos_len == 0 && enc->extradata_size > 0 &&
  3967. !TAG_IS_AVCI(trk->tag) &&
  3968. (enc->codec_id != AV_CODEC_ID_DNXHD)) {
  3969. trk->vos_len = enc->extradata_size;
  3970. trk->vos_data = av_malloc(trk->vos_len);
  3971. if (!trk->vos_data) {
  3972. ret = AVERROR(ENOMEM);
  3973. goto err;
  3974. }
  3975. memcpy(trk->vos_data, enc->extradata, trk->vos_len);
  3976. }
  3977. if (enc->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
  3978. (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
  3979. if (!s->streams[pkt->stream_index]->nb_frames) {
  3980. av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
  3981. "use the audio bitstream filter 'aac_adtstoasc' to fix it "
  3982. "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
  3983. return -1;
  3984. }
  3985. av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
  3986. }
  3987. if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
  3988. /* from x264 or from bytestream h264 */
  3989. /* nal reformating needed */
  3990. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  3991. ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
  3992. &size);
  3993. avio_write(pb, reformatted_data, size);
  3994. } else {
  3995. if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
  3996. size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
  3997. if (size < 0) {
  3998. ret = size;
  3999. goto err;
  4000. }
  4001. } else {
  4002. size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
  4003. }
  4004. }
  4005. } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
  4006. (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
  4007. /* extradata is Annex B, assume the bitstream is too and convert it */
  4008. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  4009. ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
  4010. avio_write(pb, reformatted_data, size);
  4011. } else {
  4012. size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
  4013. }
  4014. #if CONFIG_AC3_PARSER
  4015. } else if (enc->codec_id == AV_CODEC_ID_EAC3) {
  4016. size = handle_eac3(mov, pkt, trk);
  4017. if (size < 0)
  4018. return size;
  4019. else if (!size)
  4020. goto end;
  4021. avio_write(pb, pkt->data, size);
  4022. #endif
  4023. } else {
  4024. if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
  4025. if (enc->codec_id == AV_CODEC_ID_H264 && enc->extradata_size > 4) {
  4026. int nal_size_length = (enc->extradata[4] & 0x3) + 1;
  4027. ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
  4028. } else {
  4029. ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
  4030. }
  4031. if (ret) {
  4032. goto err;
  4033. }
  4034. } else {
  4035. avio_write(pb, pkt->data, size);
  4036. }
  4037. }
  4038. if ((enc->codec_id == AV_CODEC_ID_DNXHD ||
  4039. enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
  4040. /* copy frame to create needed atoms */
  4041. trk->vos_len = size;
  4042. trk->vos_data = av_malloc(size);
  4043. if (!trk->vos_data) {
  4044. ret = AVERROR(ENOMEM);
  4045. goto err;
  4046. }
  4047. memcpy(trk->vos_data, pkt->data, size);
  4048. }
  4049. if (trk->entry >= trk->cluster_capacity) {
  4050. unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
  4051. if (av_reallocp_array(&trk->cluster, new_capacity,
  4052. sizeof(*trk->cluster))) {
  4053. ret = AVERROR(ENOMEM);
  4054. goto err;
  4055. }
  4056. trk->cluster_capacity = new_capacity;
  4057. }
  4058. trk->cluster[trk->entry].pos = avio_tell(pb) - size;
  4059. trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
  4060. trk->cluster[trk->entry].chunkNum = 0;
  4061. trk->cluster[trk->entry].size = size;
  4062. trk->cluster[trk->entry].entries = samples_in_chunk;
  4063. trk->cluster[trk->entry].dts = pkt->dts;
  4064. if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
  4065. if (!trk->frag_discont) {
  4066. /* First packet of a new fragment. We already wrote the duration
  4067. * of the last packet of the previous fragment based on track_duration,
  4068. * which might not exactly match our dts. Therefore adjust the dts
  4069. * of this packet to be what the previous packets duration implies. */
  4070. trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
  4071. /* We also may have written the pts and the corresponding duration
  4072. * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
  4073. * the next fragment. This means the cts of the first sample must
  4074. * be the same in all fragments. */
  4075. if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
  4076. mov->mode == MODE_ISM)
  4077. pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
  4078. } else {
  4079. /* New fragment, but discontinuous from previous fragments.
  4080. * Pretend the duration sum of the earlier fragments is
  4081. * pkt->dts - trk->start_dts. */
  4082. trk->frag_start = pkt->dts - trk->start_dts;
  4083. trk->end_pts = AV_NOPTS_VALUE;
  4084. trk->frag_discont = 0;
  4085. }
  4086. }
  4087. if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
  4088. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
  4089. /* Not using edit lists and shifting the first track to start from zero.
  4090. * If the other streams start from a later timestamp, we won't be able
  4091. * to signal the difference in starting time without an edit list.
  4092. * Thus move the timestamp for this first sample to 0, increasing
  4093. * its duration instead. */
  4094. trk->cluster[trk->entry].dts = trk->start_dts = 0;
  4095. }
  4096. if (trk->start_dts == AV_NOPTS_VALUE) {
  4097. trk->start_dts = pkt->dts;
  4098. if (trk->frag_discont) {
  4099. if (mov->use_editlist) {
  4100. /* Pretend the whole stream started at pts=0, with earlier fragments
  4101. * already written. If the stream started at pts=0, the duration sum
  4102. * of earlier fragments would have been pkt->pts. */
  4103. trk->frag_start = pkt->pts;
  4104. trk->start_dts = pkt->dts - pkt->pts;
  4105. } else {
  4106. /* Pretend the whole stream started at dts=0, with earlier fragments
  4107. * already written, with a duration summing up to pkt->dts. */
  4108. trk->frag_start = pkt->dts;
  4109. trk->start_dts = 0;
  4110. }
  4111. trk->frag_discont = 0;
  4112. } else if (pkt->dts && mov->moov_written)
  4113. av_log(s, AV_LOG_WARNING,
  4114. "Track %d starts with a nonzero dts %"PRId64", while the moov "
  4115. "already has been written. Set the delay_moov flag to handle "
  4116. "this case.\n",
  4117. pkt->stream_index, pkt->dts);
  4118. }
  4119. trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
  4120. trk->last_sample_is_subtitle_end = 0;
  4121. if (pkt->pts == AV_NOPTS_VALUE) {
  4122. av_log(s, AV_LOG_WARNING, "pts has no value\n");
  4123. pkt->pts = pkt->dts;
  4124. }
  4125. if (pkt->dts != pkt->pts)
  4126. trk->flags |= MOV_TRACK_CTTS;
  4127. trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
  4128. trk->cluster[trk->entry].flags = 0;
  4129. if (trk->start_cts == AV_NOPTS_VALUE)
  4130. trk->start_cts = pkt->pts - pkt->dts;
  4131. if (trk->end_pts == AV_NOPTS_VALUE)
  4132. trk->end_pts = trk->cluster[trk->entry].dts +
  4133. trk->cluster[trk->entry].cts + pkt->duration;
  4134. else
  4135. trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
  4136. trk->cluster[trk->entry].cts +
  4137. pkt->duration);
  4138. if (enc->codec_id == AV_CODEC_ID_VC1) {
  4139. mov_parse_vc1_frame(pkt, trk);
  4140. } else if (pkt->flags & AV_PKT_FLAG_KEY) {
  4141. if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
  4142. trk->entry > 0) { // force sync sample for the first key frame
  4143. mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
  4144. if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
  4145. trk->flags |= MOV_TRACK_STPS;
  4146. } else {
  4147. trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
  4148. }
  4149. if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
  4150. trk->has_keyframes++;
  4151. }
  4152. trk->entry++;
  4153. trk->sample_count += samples_in_chunk;
  4154. mov->mdat_size += size;
  4155. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
  4156. ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
  4157. reformatted_data, size);
  4158. end:
  4159. err:
  4160. av_free(reformatted_data);
  4161. return ret;
  4162. }
  4163. static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
  4164. {
  4165. MOVMuxContext *mov = s->priv_data;
  4166. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4167. AVCodecContext *enc = trk->enc;
  4168. int64_t frag_duration = 0;
  4169. int size = pkt->size;
  4170. if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
  4171. int i;
  4172. for (i = 0; i < s->nb_streams; i++)
  4173. mov->tracks[i].frag_discont = 1;
  4174. mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
  4175. }
  4176. if (!pkt->size) {
  4177. if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
  4178. trk->start_dts = pkt->dts;
  4179. if (pkt->pts != AV_NOPTS_VALUE)
  4180. trk->start_cts = pkt->pts - pkt->dts;
  4181. else
  4182. trk->start_cts = 0;
  4183. }
  4184. return 0; /* Discard 0 sized packets */
  4185. }
  4186. if (trk->entry && pkt->stream_index < s->nb_streams)
  4187. frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
  4188. s->streams[pkt->stream_index]->time_base,
  4189. AV_TIME_BASE_Q);
  4190. if ((mov->max_fragment_duration &&
  4191. frag_duration >= mov->max_fragment_duration) ||
  4192. (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
  4193. (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
  4194. enc->codec_type == AVMEDIA_TYPE_VIDEO &&
  4195. trk->entry && pkt->flags & AV_PKT_FLAG_KEY)) {
  4196. if (frag_duration >= mov->min_fragment_duration) {
  4197. // Set the duration of this track to line up with the next
  4198. // sample in this track. This avoids relying on AVPacket
  4199. // duration, but only helps for this particular track, not
  4200. // for the other ones that are flushed at the same time.
  4201. trk->track_duration = pkt->dts - trk->start_dts;
  4202. trk->end_pts = pkt->pts;
  4203. mov_auto_flush_fragment(s, 0);
  4204. }
  4205. }
  4206. return ff_mov_write_packet(s, pkt);
  4207. }
  4208. static int mov_write_subtitle_end_packet(AVFormatContext *s,
  4209. int stream_index,
  4210. int64_t dts) {
  4211. AVPacket end;
  4212. uint8_t data[2] = {0};
  4213. int ret;
  4214. av_init_packet(&end);
  4215. end.size = sizeof(data);
  4216. end.data = data;
  4217. end.pts = dts;
  4218. end.dts = dts;
  4219. end.duration = 0;
  4220. end.stream_index = stream_index;
  4221. ret = mov_write_single_packet(s, &end);
  4222. av_packet_unref(&end);
  4223. return ret;
  4224. }
  4225. static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  4226. {
  4227. if (!pkt) {
  4228. mov_flush_fragment(s, 1);
  4229. return 1;
  4230. } else {
  4231. int i;
  4232. MOVMuxContext *mov = s->priv_data;
  4233. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4234. if (!pkt->size)
  4235. return mov_write_single_packet(s, pkt); /* Passthrough. */
  4236. /*
  4237. * Subtitles require special handling.
  4238. *
  4239. * 1) For full complaince, every track must have a sample at
  4240. * dts == 0, which is rarely true for subtitles. So, as soon
  4241. * as we see any packet with dts > 0, write an empty subtitle
  4242. * at dts == 0 for any subtitle track with no samples in it.
  4243. *
  4244. * 2) For each subtitle track, check if the current packet's
  4245. * dts is past the duration of the last subtitle sample. If
  4246. * so, we now need to write an end sample for that subtitle.
  4247. *
  4248. * This must be done conditionally to allow for subtitles that
  4249. * immediately replace each other, in which case an end sample
  4250. * is not needed, and is, in fact, actively harmful.
  4251. *
  4252. * 3) See mov_write_trailer for how the final end sample is
  4253. * handled.
  4254. */
  4255. for (i = 0; i < mov->nb_streams; i++) {
  4256. MOVTrack *trk = &mov->tracks[i];
  4257. int ret;
  4258. if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
  4259. trk->track_duration < pkt->dts &&
  4260. (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
  4261. ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
  4262. if (ret < 0) return ret;
  4263. trk->last_sample_is_subtitle_end = 1;
  4264. }
  4265. }
  4266. if (trk->is_unaligned_qt_rgb) {
  4267. const uint8_t *data = pkt->data;
  4268. int size = pkt->size;
  4269. int64_t bpc = trk->enc->bits_per_coded_sample != 15 ? trk->enc->bits_per_coded_sample : 16;
  4270. int expected_stride = ((trk->enc->width * bpc + 15) >> 4)*2;
  4271. int ret = ff_reshuffle_raw_rgb(s, &pkt, trk->enc, expected_stride);
  4272. if (ret < 0)
  4273. return ret;
  4274. if (ret == CONTAINS_PAL && !trk->pal_done) {
  4275. int pal_size = 1 << trk->enc->bits_per_coded_sample;
  4276. memset(trk->palette, 0, AVPALETTE_SIZE);
  4277. memcpy(trk->palette, data + size - 4*pal_size, 4*pal_size);
  4278. trk->pal_done++;
  4279. } else if (trk->enc->pix_fmt == AV_PIX_FMT_GRAY8 ||
  4280. trk->enc->pix_fmt == AV_PIX_FMT_MONOBLACK) {
  4281. for (i = 0; i < pkt->size; i++)
  4282. pkt->data[i] = ~pkt->data[i];
  4283. }
  4284. if (ret) {
  4285. ret = mov_write_single_packet(s, pkt);
  4286. av_packet_free(&pkt);
  4287. return ret;
  4288. }
  4289. }
  4290. return mov_write_single_packet(s, pkt);
  4291. }
  4292. }
  4293. // QuickTime chapters involve an additional text track with the chapter names
  4294. // as samples, and a tref pointing from the other tracks to the chapter one.
  4295. static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
  4296. {
  4297. AVIOContext *pb;
  4298. MOVMuxContext *mov = s->priv_data;
  4299. MOVTrack *track = &mov->tracks[tracknum];
  4300. AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
  4301. int i, len;
  4302. track->mode = mov->mode;
  4303. track->tag = MKTAG('t','e','x','t');
  4304. track->timescale = MOV_TIMESCALE;
  4305. track->enc = avcodec_alloc_context3(NULL);
  4306. if (!track->enc)
  4307. return AVERROR(ENOMEM);
  4308. track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
  4309. #if 0
  4310. // These properties are required to make QT recognize the chapter track
  4311. uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
  4312. if (ff_alloc_extradata(track->enc, sizeof(chapter_properties)))
  4313. return AVERROR(ENOMEM);
  4314. memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));
  4315. #else
  4316. if (avio_open_dyn_buf(&pb) >= 0) {
  4317. int size;
  4318. uint8_t *buf;
  4319. /* Stub header (usually for Quicktime chapter track) */
  4320. // TextSampleEntry
  4321. avio_wb32(pb, 0x01); // displayFlags
  4322. avio_w8(pb, 0x00); // horizontal justification
  4323. avio_w8(pb, 0x00); // vertical justification
  4324. avio_w8(pb, 0x00); // bgColourRed
  4325. avio_w8(pb, 0x00); // bgColourGreen
  4326. avio_w8(pb, 0x00); // bgColourBlue
  4327. avio_w8(pb, 0x00); // bgColourAlpha
  4328. // BoxRecord
  4329. avio_wb16(pb, 0x00); // defTextBoxTop
  4330. avio_wb16(pb, 0x00); // defTextBoxLeft
  4331. avio_wb16(pb, 0x00); // defTextBoxBottom
  4332. avio_wb16(pb, 0x00); // defTextBoxRight
  4333. // StyleRecord
  4334. avio_wb16(pb, 0x00); // startChar
  4335. avio_wb16(pb, 0x00); // endChar
  4336. avio_wb16(pb, 0x01); // fontID
  4337. avio_w8(pb, 0x00); // fontStyleFlags
  4338. avio_w8(pb, 0x00); // fontSize
  4339. avio_w8(pb, 0x00); // fgColourRed
  4340. avio_w8(pb, 0x00); // fgColourGreen
  4341. avio_w8(pb, 0x00); // fgColourBlue
  4342. avio_w8(pb, 0x00); // fgColourAlpha
  4343. // FontTableBox
  4344. avio_wb32(pb, 0x0D); // box size
  4345. ffio_wfourcc(pb, "ftab"); // box atom name
  4346. avio_wb16(pb, 0x01); // entry count
  4347. // FontRecord
  4348. avio_wb16(pb, 0x01); // font ID
  4349. avio_w8(pb, 0x00); // font name length
  4350. if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
  4351. track->enc->extradata = buf;
  4352. track->enc->extradata_size = size;
  4353. } else {
  4354. av_freep(&buf);
  4355. }
  4356. }
  4357. #endif
  4358. for (i = 0; i < s->nb_chapters; i++) {
  4359. AVChapter *c = s->chapters[i];
  4360. AVDictionaryEntry *t;
  4361. int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
  4362. pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
  4363. pkt.duration = end - pkt.dts;
  4364. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  4365. const char encd[12] = {
  4366. 0x00, 0x00, 0x00, 0x0C,
  4367. 'e', 'n', 'c', 'd',
  4368. 0x00, 0x00, 0x01, 0x00 };
  4369. len = strlen(t->value);
  4370. pkt.size = len + 2 + 12;
  4371. pkt.data = av_malloc(pkt.size);
  4372. if (!pkt.data)
  4373. return AVERROR(ENOMEM);
  4374. AV_WB16(pkt.data, len);
  4375. memcpy(pkt.data + 2, t->value, len);
  4376. memcpy(pkt.data + len + 2, encd, sizeof(encd));
  4377. ff_mov_write_packet(s, &pkt);
  4378. av_freep(&pkt.data);
  4379. }
  4380. }
  4381. return 0;
  4382. }
  4383. static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)
  4384. {
  4385. int ret;
  4386. MOVMuxContext *mov = s->priv_data;
  4387. MOVTrack *track = &mov->tracks[index];
  4388. AVStream *src_st = s->streams[src_index];
  4389. AVTimecode tc;
  4390. AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
  4391. AVRational rate = find_fps(s, src_st);
  4392. /* compute the frame number */
  4393. ret = av_timecode_init_from_string(&tc, rate, tcstr, s);
  4394. if (ret < 0)
  4395. return ret;
  4396. /* tmcd track based on video stream */
  4397. track->mode = mov->mode;
  4398. track->tag = MKTAG('t','m','c','d');
  4399. track->src_track = src_index;
  4400. track->timescale = mov->tracks[src_index].timescale;
  4401. if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
  4402. track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
  4403. /* set st to src_st for metadata access*/
  4404. track->st = src_st;
  4405. /* encode context: tmcd data stream */
  4406. track->enc = avcodec_alloc_context3(NULL);
  4407. if (!track->enc)
  4408. return AVERROR(ENOMEM);
  4409. track->enc->codec_type = AVMEDIA_TYPE_DATA;
  4410. track->enc->codec_tag = track->tag;
  4411. track->enc->time_base = av_inv_q(rate);
  4412. /* the tmcd track just contains one packet with the frame number */
  4413. pkt.data = av_malloc(pkt.size);
  4414. if (!pkt.data)
  4415. return AVERROR(ENOMEM);
  4416. AV_WB32(pkt.data, tc.start);
  4417. ret = ff_mov_write_packet(s, &pkt);
  4418. av_free(pkt.data);
  4419. return ret;
  4420. }
  4421. /*
  4422. * st->disposition controls the "enabled" flag in the tkhd tag.
  4423. * QuickTime will not play a track if it is not enabled. So make sure
  4424. * that one track of each type (audio, video, subtitle) is enabled.
  4425. *
  4426. * Subtitles are special. For audio and video, setting "enabled" also
  4427. * makes the track "default" (i.e. it is rendered when played). For
  4428. * subtitles, an "enabled" subtitle is not rendered by default, but
  4429. * if no subtitle is enabled, the subtitle menu in QuickTime will be
  4430. * empty!
  4431. */
  4432. static void enable_tracks(AVFormatContext *s)
  4433. {
  4434. MOVMuxContext *mov = s->priv_data;
  4435. int i;
  4436. int enabled[AVMEDIA_TYPE_NB];
  4437. int first[AVMEDIA_TYPE_NB];
  4438. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  4439. enabled[i] = 0;
  4440. first[i] = -1;
  4441. }
  4442. for (i = 0; i < s->nb_streams; i++) {
  4443. AVStream *st = s->streams[i];
  4444. if (st->codec->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
  4445. st->codec->codec_type >= AVMEDIA_TYPE_NB)
  4446. continue;
  4447. if (first[st->codec->codec_type] < 0)
  4448. first[st->codec->codec_type] = i;
  4449. if (st->disposition & AV_DISPOSITION_DEFAULT) {
  4450. mov->tracks[i].flags |= MOV_TRACK_ENABLED;
  4451. enabled[st->codec->codec_type]++;
  4452. }
  4453. }
  4454. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  4455. switch (i) {
  4456. case AVMEDIA_TYPE_VIDEO:
  4457. case AVMEDIA_TYPE_AUDIO:
  4458. case AVMEDIA_TYPE_SUBTITLE:
  4459. if (enabled[i] > 1)
  4460. mov->per_stream_grouping = 1;
  4461. if (!enabled[i] && first[i] >= 0)
  4462. mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
  4463. break;
  4464. }
  4465. }
  4466. }
  4467. static void mov_free(AVFormatContext *s)
  4468. {
  4469. MOVMuxContext *mov = s->priv_data;
  4470. int i;
  4471. if (mov->chapter_track) {
  4472. if (mov->tracks[mov->chapter_track].enc)
  4473. av_freep(&mov->tracks[mov->chapter_track].enc->extradata);
  4474. av_freep(&mov->tracks[mov->chapter_track].enc);
  4475. }
  4476. for (i = 0; i < mov->nb_streams; i++) {
  4477. if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
  4478. ff_mov_close_hinting(&mov->tracks[i]);
  4479. else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
  4480. av_freep(&mov->tracks[i].enc);
  4481. av_freep(&mov->tracks[i].cluster);
  4482. av_freep(&mov->tracks[i].frag_info);
  4483. if (mov->tracks[i].vos_len)
  4484. av_freep(&mov->tracks[i].vos_data);
  4485. ff_mov_cenc_free(&mov->tracks[i].cenc);
  4486. }
  4487. av_freep(&mov->tracks);
  4488. }
  4489. static uint32_t rgb_to_yuv(uint32_t rgb)
  4490. {
  4491. uint8_t r, g, b;
  4492. int y, cb, cr;
  4493. r = (rgb >> 16) & 0xFF;
  4494. g = (rgb >> 8) & 0xFF;
  4495. b = (rgb ) & 0xFF;
  4496. y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
  4497. cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
  4498. cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
  4499. return (y << 16) | (cr << 8) | cb;
  4500. }
  4501. static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
  4502. AVStream *st)
  4503. {
  4504. int i, width = 720, height = 480;
  4505. int have_palette = 0, have_size = 0;
  4506. uint32_t palette[16];
  4507. char *cur = st->codec->extradata;
  4508. while (cur && *cur) {
  4509. if (strncmp("palette:", cur, 8) == 0) {
  4510. int i, count;
  4511. count = sscanf(cur + 8,
  4512. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  4513. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  4514. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  4515. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
  4516. &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
  4517. &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
  4518. &palette[ 8], &palette[ 9], &palette[10], &palette[11],
  4519. &palette[12], &palette[13], &palette[14], &palette[15]);
  4520. for (i = 0; i < count; i++) {
  4521. palette[i] = rgb_to_yuv(palette[i]);
  4522. }
  4523. have_palette = 1;
  4524. } else if (!strncmp("size:", cur, 5)) {
  4525. sscanf(cur + 5, "%dx%d", &width, &height);
  4526. have_size = 1;
  4527. }
  4528. if (have_palette && have_size)
  4529. break;
  4530. cur += strcspn(cur, "\n\r");
  4531. cur += strspn(cur, "\n\r");
  4532. }
  4533. if (have_palette) {
  4534. track->vos_data = av_malloc(16*4);
  4535. if (!track->vos_data)
  4536. return AVERROR(ENOMEM);
  4537. for (i = 0; i < 16; i++) {
  4538. AV_WB32(track->vos_data + i * 4, palette[i]);
  4539. }
  4540. track->vos_len = 16 * 4;
  4541. }
  4542. st->codec->width = width;
  4543. st->codec->height = track->height = height;
  4544. return 0;
  4545. }
  4546. static int mov_write_header(AVFormatContext *s)
  4547. {
  4548. AVIOContext *pb = s->pb;
  4549. MOVMuxContext *mov = s->priv_data;
  4550. AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  4551. int i, ret, hint_track = 0, tmcd_track = 0;
  4552. mov->fc = s;
  4553. /* Default mode == MP4 */
  4554. mov->mode = MODE_MP4;
  4555. if (s->oformat) {
  4556. if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
  4557. else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
  4558. else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
  4559. else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
  4560. else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
  4561. else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
  4562. else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
  4563. }
  4564. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  4565. mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
  4566. /* Set the FRAGMENT flag if any of the fragmentation methods are
  4567. * enabled. */
  4568. if (mov->max_fragment_duration || mov->max_fragment_size ||
  4569. mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
  4570. FF_MOV_FLAG_FRAG_KEYFRAME |
  4571. FF_MOV_FLAG_FRAG_CUSTOM))
  4572. mov->flags |= FF_MOV_FLAG_FRAGMENT;
  4573. /* Set other implicit flags immediately */
  4574. if (mov->mode == MODE_ISM)
  4575. mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
  4576. FF_MOV_FLAG_FRAGMENT;
  4577. if (mov->flags & FF_MOV_FLAG_DASH)
  4578. mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
  4579. FF_MOV_FLAG_DEFAULT_BASE_MOOF;
  4580. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  4581. mov->reserved_moov_size = -1;
  4582. }
  4583. if (mov->use_editlist < 0) {
  4584. mov->use_editlist = 1;
  4585. if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
  4586. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  4587. // If we can avoid needing an edit list by shifting the
  4588. // tracks, prefer that over (trying to) write edit lists
  4589. // in fragmented output.
  4590. if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
  4591. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
  4592. mov->use_editlist = 0;
  4593. }
  4594. }
  4595. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
  4596. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
  4597. av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
  4598. if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
  4599. s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
  4600. /* Clear the omit_tfhd_offset flag if default_base_moof is set;
  4601. * if the latter is set that's enough and omit_tfhd_offset doesn't
  4602. * add anything extra on top of that. */
  4603. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
  4604. mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
  4605. mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
  4606. if (mov->frag_interleave &&
  4607. mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
  4608. av_log(s, AV_LOG_ERROR,
  4609. "Sample interleaving in fragments is mutually exclusive with "
  4610. "omit_tfhd_offset and separate_moof\n");
  4611. return AVERROR(EINVAL);
  4612. }
  4613. /* Non-seekable output is ok if using fragmentation. If ism_lookahead
  4614. * is enabled, we don't support non-seekable output at all. */
  4615. if (!s->pb->seekable &&
  4616. (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
  4617. av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
  4618. return AVERROR(EINVAL);
  4619. }
  4620. if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  4621. if ((ret = mov_write_identification(pb, s)) < 0)
  4622. return ret;
  4623. }
  4624. mov->nb_streams = s->nb_streams;
  4625. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
  4626. mov->chapter_track = mov->nb_streams++;
  4627. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  4628. /* Add hint tracks for each audio and video stream */
  4629. hint_track = mov->nb_streams;
  4630. for (i = 0; i < s->nb_streams; i++) {
  4631. AVStream *st = s->streams[i];
  4632. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  4633. st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  4634. mov->nb_streams++;
  4635. }
  4636. }
  4637. }
  4638. if (mov->mode == MODE_MOV) {
  4639. tmcd_track = mov->nb_streams;
  4640. /* +1 tmcd track for each video stream with a timecode */
  4641. for (i = 0; i < s->nb_streams; i++) {
  4642. AVStream *st = s->streams[i];
  4643. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  4644. (global_tcr || av_dict_get(st->metadata, "timecode", NULL, 0)))
  4645. mov->nb_meta_tmcd++;
  4646. }
  4647. /* check if there is already a tmcd track to remux */
  4648. if (mov->nb_meta_tmcd) {
  4649. for (i = 0; i < s->nb_streams; i++) {
  4650. AVStream *st = s->streams[i];
  4651. if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
  4652. av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
  4653. "so timecode metadata are now ignored\n");
  4654. mov->nb_meta_tmcd = 0;
  4655. }
  4656. }
  4657. }
  4658. mov->nb_streams += mov->nb_meta_tmcd;
  4659. }
  4660. // Reserve an extra stream for chapters for the case where chapters
  4661. // are written in the trailer
  4662. mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
  4663. if (!mov->tracks)
  4664. return AVERROR(ENOMEM);
  4665. if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
  4666. if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
  4667. mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
  4668. if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
  4669. av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
  4670. mov->encryption_key_len, AES_CTR_KEY_SIZE);
  4671. ret = AVERROR(EINVAL);
  4672. goto error;
  4673. }
  4674. if (mov->encryption_kid_len != CENC_KID_SIZE) {
  4675. av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
  4676. mov->encryption_kid_len, CENC_KID_SIZE);
  4677. ret = AVERROR(EINVAL);
  4678. goto error;
  4679. }
  4680. } else {
  4681. av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
  4682. mov->encryption_scheme_str);
  4683. ret = AVERROR(EINVAL);
  4684. goto error;
  4685. }
  4686. }
  4687. for (i = 0; i < s->nb_streams; i++) {
  4688. AVStream *st= s->streams[i];
  4689. MOVTrack *track= &mov->tracks[i];
  4690. AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
  4691. track->st = st;
  4692. track->enc = st->codec;
  4693. track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
  4694. if (track->language < 0)
  4695. track->language = 0;
  4696. track->mode = mov->mode;
  4697. track->tag = mov_find_codec_tag(s, track);
  4698. if (!track->tag) {
  4699. av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
  4700. "codec not currently supported in container\n",
  4701. avcodec_get_name(st->codec->codec_id), i);
  4702. ret = AVERROR(EINVAL);
  4703. goto error;
  4704. }
  4705. /* If hinting of this track is enabled by a later hint track,
  4706. * this is updated. */
  4707. track->hint_track = -1;
  4708. track->start_dts = AV_NOPTS_VALUE;
  4709. track->start_cts = AV_NOPTS_VALUE;
  4710. track->end_pts = AV_NOPTS_VALUE;
  4711. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  4712. if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
  4713. track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
  4714. track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
  4715. if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {
  4716. av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
  4717. ret = AVERROR(EINVAL);
  4718. goto error;
  4719. }
  4720. track->height = track->tag >> 24 == 'n' ? 486 : 576;
  4721. }
  4722. if (mov->video_track_timescale) {
  4723. track->timescale = mov->video_track_timescale;
  4724. } else {
  4725. track->timescale = st->time_base.den;
  4726. while(track->timescale < 10000)
  4727. track->timescale *= 2;
  4728. }
  4729. if (st->codec->width > 65535 || st->codec->height > 65535) {
  4730. av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codec->width, st->codec->height);
  4731. ret = AVERROR(EINVAL);
  4732. goto error;
  4733. }
  4734. if (track->mode == MODE_MOV && track->timescale > 100000)
  4735. av_log(s, AV_LOG_WARNING,
  4736. "WARNING codec timebase is very high. If duration is too long,\n"
  4737. "file may not be playable by quicktime. Specify a shorter timebase\n"
  4738. "or choose different container.\n");
  4739. if (track->mode == MODE_MOV &&
  4740. track->enc->codec_id == AV_CODEC_ID_RAWVIDEO &&
  4741. track->tag == MKTAG('r','a','w',' ')) {
  4742. enum AVPixelFormat pix_fmt = track->enc->pix_fmt;
  4743. if (pix_fmt == AV_PIX_FMT_NONE && track->enc->bits_per_coded_sample == 1)
  4744. pix_fmt = AV_PIX_FMT_MONOWHITE;
  4745. track->is_unaligned_qt_rgb =
  4746. pix_fmt == AV_PIX_FMT_RGB24 ||
  4747. pix_fmt == AV_PIX_FMT_BGR24 ||
  4748. pix_fmt == AV_PIX_FMT_PAL8 ||
  4749. pix_fmt == AV_PIX_FMT_GRAY8 ||
  4750. pix_fmt == AV_PIX_FMT_MONOWHITE ||
  4751. pix_fmt == AV_PIX_FMT_MONOBLACK;
  4752. }
  4753. } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  4754. track->timescale = st->codec->sample_rate;
  4755. if (!st->codec->frame_size && !av_get_bits_per_sample(st->codec->codec_id)) {
  4756. av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
  4757. track->audio_vbr = 1;
  4758. }else if (st->codec->codec_id == AV_CODEC_ID_ADPCM_MS ||
  4759. st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  4760. st->codec->codec_id == AV_CODEC_ID_ILBC){
  4761. if (!st->codec->block_align) {
  4762. av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
  4763. ret = AVERROR(EINVAL);
  4764. goto error;
  4765. }
  4766. track->sample_size = st->codec->block_align;
  4767. }else if (st->codec->frame_size > 1){ /* assume compressed audio */
  4768. track->audio_vbr = 1;
  4769. }else{
  4770. track->sample_size = (av_get_bits_per_sample(st->codec->codec_id) >> 3) * st->codec->channels;
  4771. }
  4772. if (st->codec->codec_id == AV_CODEC_ID_ILBC ||
  4773. st->codec->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
  4774. track->audio_vbr = 1;
  4775. }
  4776. if (track->mode != MODE_MOV &&
  4777. track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
  4778. if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
  4779. av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
  4780. i, track->enc->sample_rate);
  4781. ret = AVERROR(EINVAL);
  4782. goto error;
  4783. } else {
  4784. av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
  4785. i, track->enc->sample_rate);
  4786. }
  4787. }
  4788. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  4789. track->timescale = st->time_base.den;
  4790. } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
  4791. track->timescale = st->time_base.den;
  4792. } else {
  4793. track->timescale = MOV_TIMESCALE;
  4794. }
  4795. if (!track->height)
  4796. track->height = st->codec->height;
  4797. /* The ism specific timescale isn't mandatory, but is assumed by
  4798. * some tools, such as mp4split. */
  4799. if (mov->mode == MODE_ISM)
  4800. track->timescale = 10000000;
  4801. avpriv_set_pts_info(st, 64, 1, track->timescale);
  4802. /* copy extradata if it exists */
  4803. if (st->codec->extradata_size) {
  4804. if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  4805. mov_create_dvd_sub_decoder_specific_info(track, st);
  4806. else if (!TAG_IS_AVCI(track->tag) && st->codec->codec_id != AV_CODEC_ID_DNXHD) {
  4807. track->vos_len = st->codec->extradata_size;
  4808. track->vos_data = av_malloc(track->vos_len);
  4809. if (!track->vos_data) {
  4810. ret = AVERROR(ENOMEM);
  4811. goto error;
  4812. }
  4813. memcpy(track->vos_data, st->codec->extradata, track->vos_len);
  4814. }
  4815. }
  4816. if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
  4817. ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
  4818. track->enc->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
  4819. if (ret) {
  4820. goto error;
  4821. }
  4822. }
  4823. }
  4824. for (i = 0; i < s->nb_streams; i++) {
  4825. int j;
  4826. AVStream *st= s->streams[i];
  4827. MOVTrack *track= &mov->tracks[i];
  4828. if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
  4829. track->enc->channel_layout != AV_CH_LAYOUT_MONO)
  4830. continue;
  4831. for (j = 0; j < s->nb_streams; j++) {
  4832. AVStream *stj= s->streams[j];
  4833. MOVTrack *trackj= &mov->tracks[j];
  4834. if (j == i)
  4835. continue;
  4836. if (stj->codec->codec_type != AVMEDIA_TYPE_AUDIO ||
  4837. trackj->enc->channel_layout != AV_CH_LAYOUT_MONO ||
  4838. trackj->language != track->language ||
  4839. trackj->tag != track->tag
  4840. )
  4841. continue;
  4842. track->multichannel_as_mono++;
  4843. }
  4844. }
  4845. enable_tracks(s);
  4846. if (mov->reserved_moov_size){
  4847. mov->reserved_header_pos = avio_tell(pb);
  4848. if (mov->reserved_moov_size > 0)
  4849. avio_skip(pb, mov->reserved_moov_size);
  4850. }
  4851. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  4852. /* If no fragmentation options have been set, set a default. */
  4853. if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
  4854. FF_MOV_FLAG_FRAG_CUSTOM)) &&
  4855. !mov->max_fragment_duration && !mov->max_fragment_size)
  4856. mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
  4857. } else {
  4858. if (mov->flags & FF_MOV_FLAG_FASTSTART)
  4859. mov->reserved_header_pos = avio_tell(pb);
  4860. mov_write_mdat_tag(pb, mov);
  4861. }
  4862. ff_parse_creation_time_metadata(s, &mov->time, 1);
  4863. if (mov->time)
  4864. mov->time += 0x7C25B080; // 1970 based -> 1904 based
  4865. if (mov->chapter_track)
  4866. if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  4867. goto error;
  4868. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  4869. /* Initialize the hint tracks for each audio and video stream */
  4870. for (i = 0; i < s->nb_streams; i++) {
  4871. AVStream *st = s->streams[i];
  4872. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  4873. st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  4874. if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
  4875. goto error;
  4876. hint_track++;
  4877. }
  4878. }
  4879. }
  4880. if (mov->nb_meta_tmcd) {
  4881. /* Initialize the tmcd tracks */
  4882. for (i = 0; i < s->nb_streams; i++) {
  4883. AVStream *st = s->streams[i];
  4884. t = global_tcr;
  4885. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  4886. if (!t)
  4887. t = av_dict_get(st->metadata, "timecode", NULL, 0);
  4888. if (!t)
  4889. continue;
  4890. if ((ret = mov_create_timecode_track(s, tmcd_track, i, t->value)) < 0)
  4891. goto error;
  4892. tmcd_track++;
  4893. }
  4894. }
  4895. }
  4896. avio_flush(pb);
  4897. if (mov->flags & FF_MOV_FLAG_ISML)
  4898. mov_write_isml_manifest(pb, mov);
  4899. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
  4900. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  4901. if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
  4902. return ret;
  4903. avio_flush(pb);
  4904. mov->moov_written = 1;
  4905. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  4906. mov->reserved_header_pos = avio_tell(pb);
  4907. }
  4908. return 0;
  4909. error:
  4910. mov_free(s);
  4911. return ret;
  4912. }
  4913. static int get_moov_size(AVFormatContext *s)
  4914. {
  4915. int ret;
  4916. AVIOContext *moov_buf;
  4917. MOVMuxContext *mov = s->priv_data;
  4918. if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
  4919. return ret;
  4920. if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
  4921. return ret;
  4922. return ffio_close_null_buf(moov_buf);
  4923. }
  4924. static int get_sidx_size(AVFormatContext *s)
  4925. {
  4926. int ret;
  4927. AVIOContext *buf;
  4928. MOVMuxContext *mov = s->priv_data;
  4929. if ((ret = ffio_open_null_buf(&buf)) < 0)
  4930. return ret;
  4931. mov_write_sidx_tags(buf, mov, -1, 0);
  4932. return ffio_close_null_buf(buf);
  4933. }
  4934. /*
  4935. * This function gets the moov size if moved to the top of the file: the chunk
  4936. * offset table can switch between stco (32-bit entries) to co64 (64-bit
  4937. * entries) when the moov is moved to the beginning, so the size of the moov
  4938. * would change. It also updates the chunk offset tables.
  4939. */
  4940. static int compute_moov_size(AVFormatContext *s)
  4941. {
  4942. int i, moov_size, moov_size2;
  4943. MOVMuxContext *mov = s->priv_data;
  4944. moov_size = get_moov_size(s);
  4945. if (moov_size < 0)
  4946. return moov_size;
  4947. for (i = 0; i < mov->nb_streams; i++)
  4948. mov->tracks[i].data_offset += moov_size;
  4949. moov_size2 = get_moov_size(s);
  4950. if (moov_size2 < 0)
  4951. return moov_size2;
  4952. /* if the size changed, we just switched from stco to co64 and need to
  4953. * update the offsets */
  4954. if (moov_size2 != moov_size)
  4955. for (i = 0; i < mov->nb_streams; i++)
  4956. mov->tracks[i].data_offset += moov_size2 - moov_size;
  4957. return moov_size2;
  4958. }
  4959. static int compute_sidx_size(AVFormatContext *s)
  4960. {
  4961. int i, sidx_size;
  4962. MOVMuxContext *mov = s->priv_data;
  4963. sidx_size = get_sidx_size(s);
  4964. if (sidx_size < 0)
  4965. return sidx_size;
  4966. for (i = 0; i < mov->nb_streams; i++)
  4967. mov->tracks[i].data_offset += sidx_size;
  4968. return sidx_size;
  4969. }
  4970. static int shift_data(AVFormatContext *s)
  4971. {
  4972. int ret = 0, moov_size;
  4973. MOVMuxContext *mov = s->priv_data;
  4974. int64_t pos, pos_end = avio_tell(s->pb);
  4975. uint8_t *buf, *read_buf[2];
  4976. int read_buf_id = 0;
  4977. int read_size[2];
  4978. AVIOContext *read_pb;
  4979. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  4980. moov_size = compute_sidx_size(s);
  4981. else
  4982. moov_size = compute_moov_size(s);
  4983. if (moov_size < 0)
  4984. return moov_size;
  4985. buf = av_malloc(moov_size * 2);
  4986. if (!buf)
  4987. return AVERROR(ENOMEM);
  4988. read_buf[0] = buf;
  4989. read_buf[1] = buf + moov_size;
  4990. /* Shift the data: the AVIO context of the output can only be used for
  4991. * writing, so we re-open the same output, but for reading. It also avoids
  4992. * a read/seek/write/seek back and forth. */
  4993. avio_flush(s->pb);
  4994. ret = s->io_open(s, &read_pb, s->filename, AVIO_FLAG_READ, NULL);
  4995. if (ret < 0) {
  4996. av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
  4997. "the second pass (faststart)\n", s->filename);
  4998. goto end;
  4999. }
  5000. /* mark the end of the shift to up to the last data we wrote, and get ready
  5001. * for writing */
  5002. pos_end = avio_tell(s->pb);
  5003. avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
  5004. /* start reading at where the new moov will be placed */
  5005. avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
  5006. pos = avio_tell(read_pb);
  5007. #define READ_BLOCK do { \
  5008. read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
  5009. read_buf_id ^= 1; \
  5010. } while (0)
  5011. /* shift data by chunk of at most moov_size */
  5012. READ_BLOCK;
  5013. do {
  5014. int n;
  5015. READ_BLOCK;
  5016. n = read_size[read_buf_id];
  5017. if (n <= 0)
  5018. break;
  5019. avio_write(s->pb, read_buf[read_buf_id], n);
  5020. pos += n;
  5021. } while (pos < pos_end);
  5022. ff_format_io_close(s, &read_pb);
  5023. end:
  5024. av_free(buf);
  5025. return ret;
  5026. }
  5027. static int mov_write_trailer(AVFormatContext *s)
  5028. {
  5029. MOVMuxContext *mov = s->priv_data;
  5030. AVIOContext *pb = s->pb;
  5031. int res = 0;
  5032. int i;
  5033. int64_t moov_pos;
  5034. /*
  5035. * Before actually writing the trailer, make sure that there are no
  5036. * dangling subtitles, that need a terminating sample.
  5037. */
  5038. for (i = 0; i < mov->nb_streams; i++) {
  5039. MOVTrack *trk = &mov->tracks[i];
  5040. if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&
  5041. !trk->last_sample_is_subtitle_end) {
  5042. mov_write_subtitle_end_packet(s, i, trk->track_duration);
  5043. trk->last_sample_is_subtitle_end = 1;
  5044. }
  5045. }
  5046. // If there were no chapters when the header was written, but there
  5047. // are chapters now, write them in the trailer. This only works
  5048. // when we are not doing fragments.
  5049. if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  5050. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
  5051. mov->chapter_track = mov->nb_streams++;
  5052. if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  5053. goto error;
  5054. }
  5055. }
  5056. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  5057. moov_pos = avio_tell(pb);
  5058. /* Write size of mdat tag */
  5059. if (mov->mdat_size + 8 <= UINT32_MAX) {
  5060. avio_seek(pb, mov->mdat_pos, SEEK_SET);
  5061. avio_wb32(pb, mov->mdat_size + 8);
  5062. } else {
  5063. /* overwrite 'wide' placeholder atom */
  5064. avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
  5065. /* special value: real atom size will be 64 bit value after
  5066. * tag field */
  5067. avio_wb32(pb, 1);
  5068. ffio_wfourcc(pb, "mdat");
  5069. avio_wb64(pb, mov->mdat_size + 16);
  5070. }
  5071. avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
  5072. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  5073. av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
  5074. res = shift_data(s);
  5075. if (res == 0) {
  5076. avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
  5077. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  5078. goto error;
  5079. }
  5080. } else if (mov->reserved_moov_size > 0) {
  5081. int64_t size;
  5082. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  5083. goto error;
  5084. size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
  5085. if (size < 8){
  5086. av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
  5087. res = AVERROR(EINVAL);
  5088. goto error;
  5089. }
  5090. avio_wb32(pb, size);
  5091. ffio_wfourcc(pb, "free");
  5092. ffio_fill(pb, 0, size - 8);
  5093. avio_seek(pb, moov_pos, SEEK_SET);
  5094. } else {
  5095. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  5096. goto error;
  5097. }
  5098. res = 0;
  5099. } else {
  5100. mov_auto_flush_fragment(s, 1);
  5101. for (i = 0; i < mov->nb_streams; i++)
  5102. mov->tracks[i].data_offset = 0;
  5103. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
  5104. av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
  5105. res = shift_data(s);
  5106. if (res == 0) {
  5107. int64_t end = avio_tell(pb);
  5108. avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
  5109. mov_write_sidx_tags(pb, mov, -1, 0);
  5110. avio_seek(pb, end, SEEK_SET);
  5111. mov_write_mfra_tag(pb, mov);
  5112. }
  5113. } else {
  5114. mov_write_mfra_tag(pb, mov);
  5115. }
  5116. }
  5117. error:
  5118. mov_free(s);
  5119. return res;
  5120. }
  5121. #if CONFIG_MOV_MUXER
  5122. MOV_CLASS(mov)
  5123. AVOutputFormat ff_mov_muxer = {
  5124. .name = "mov",
  5125. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  5126. .extensions = "mov",
  5127. .priv_data_size = sizeof(MOVMuxContext),
  5128. .audio_codec = AV_CODEC_ID_AAC,
  5129. .video_codec = CONFIG_LIBX264_ENCODER ?
  5130. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  5131. .write_header = mov_write_header,
  5132. .write_packet = mov_write_packet,
  5133. .write_trailer = mov_write_trailer,
  5134. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5135. .codec_tag = (const AVCodecTag* const []){
  5136. ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
  5137. },
  5138. .priv_class = &mov_muxer_class,
  5139. };
  5140. #endif
  5141. #if CONFIG_TGP_MUXER
  5142. MOV_CLASS(tgp)
  5143. AVOutputFormat ff_tgp_muxer = {
  5144. .name = "3gp",
  5145. .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
  5146. .extensions = "3gp",
  5147. .priv_data_size = sizeof(MOVMuxContext),
  5148. .audio_codec = AV_CODEC_ID_AMR_NB,
  5149. .video_codec = AV_CODEC_ID_H263,
  5150. .write_header = mov_write_header,
  5151. .write_packet = mov_write_packet,
  5152. .write_trailer = mov_write_trailer,
  5153. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5154. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  5155. .priv_class = &tgp_muxer_class,
  5156. };
  5157. #endif
  5158. #if CONFIG_MP4_MUXER
  5159. MOV_CLASS(mp4)
  5160. AVOutputFormat ff_mp4_muxer = {
  5161. .name = "mp4",
  5162. .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
  5163. .mime_type = "video/mp4",
  5164. .extensions = "mp4",
  5165. .priv_data_size = sizeof(MOVMuxContext),
  5166. .audio_codec = AV_CODEC_ID_AAC,
  5167. .video_codec = CONFIG_LIBX264_ENCODER ?
  5168. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  5169. .write_header = mov_write_header,
  5170. .write_packet = mov_write_packet,
  5171. .write_trailer = mov_write_trailer,
  5172. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5173. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  5174. .priv_class = &mp4_muxer_class,
  5175. };
  5176. #endif
  5177. #if CONFIG_PSP_MUXER
  5178. MOV_CLASS(psp)
  5179. AVOutputFormat ff_psp_muxer = {
  5180. .name = "psp",
  5181. .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
  5182. .extensions = "mp4,psp",
  5183. .priv_data_size = sizeof(MOVMuxContext),
  5184. .audio_codec = AV_CODEC_ID_AAC,
  5185. .video_codec = CONFIG_LIBX264_ENCODER ?
  5186. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  5187. .write_header = mov_write_header,
  5188. .write_packet = mov_write_packet,
  5189. .write_trailer = mov_write_trailer,
  5190. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5191. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  5192. .priv_class = &psp_muxer_class,
  5193. };
  5194. #endif
  5195. #if CONFIG_TG2_MUXER
  5196. MOV_CLASS(tg2)
  5197. AVOutputFormat ff_tg2_muxer = {
  5198. .name = "3g2",
  5199. .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
  5200. .extensions = "3g2",
  5201. .priv_data_size = sizeof(MOVMuxContext),
  5202. .audio_codec = AV_CODEC_ID_AMR_NB,
  5203. .video_codec = AV_CODEC_ID_H263,
  5204. .write_header = mov_write_header,
  5205. .write_packet = mov_write_packet,
  5206. .write_trailer = mov_write_trailer,
  5207. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5208. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  5209. .priv_class = &tg2_muxer_class,
  5210. };
  5211. #endif
  5212. #if CONFIG_IPOD_MUXER
  5213. MOV_CLASS(ipod)
  5214. AVOutputFormat ff_ipod_muxer = {
  5215. .name = "ipod",
  5216. .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
  5217. .mime_type = "video/mp4",
  5218. .extensions = "m4v,m4a",
  5219. .priv_data_size = sizeof(MOVMuxContext),
  5220. .audio_codec = AV_CODEC_ID_AAC,
  5221. .video_codec = AV_CODEC_ID_H264,
  5222. .write_header = mov_write_header,
  5223. .write_packet = mov_write_packet,
  5224. .write_trailer = mov_write_trailer,
  5225. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5226. .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
  5227. .priv_class = &ipod_muxer_class,
  5228. };
  5229. #endif
  5230. #if CONFIG_ISMV_MUXER
  5231. MOV_CLASS(ismv)
  5232. AVOutputFormat ff_ismv_muxer = {
  5233. .name = "ismv",
  5234. .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
  5235. .mime_type = "video/mp4",
  5236. .extensions = "ismv,isma",
  5237. .priv_data_size = sizeof(MOVMuxContext),
  5238. .audio_codec = AV_CODEC_ID_AAC,
  5239. .video_codec = AV_CODEC_ID_H264,
  5240. .write_header = mov_write_header,
  5241. .write_packet = mov_write_packet,
  5242. .write_trailer = mov_write_trailer,
  5243. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  5244. .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
  5245. .priv_class = &ismv_muxer_class,
  5246. };
  5247. #endif
  5248. #if CONFIG_F4V_MUXER
  5249. MOV_CLASS(f4v)
  5250. AVOutputFormat ff_f4v_muxer = {
  5251. .name = "f4v",
  5252. .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
  5253. .mime_type = "application/f4v",
  5254. .extensions = "f4v",
  5255. .priv_data_size = sizeof(MOVMuxContext),
  5256. .audio_codec = AV_CODEC_ID_AAC,
  5257. .video_codec = AV_CODEC_ID_H264,
  5258. .write_header = mov_write_header,
  5259. .write_packet = mov_write_packet,
  5260. .write_trailer = mov_write_trailer,
  5261. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
  5262. .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
  5263. .priv_class = &f4v_muxer_class,
  5264. };
  5265. #endif