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.

6892 lines
250KB

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