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.

7268 lines
265KB

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