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.

7427 lines
271KB

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