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.

7100 lines
259KB

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