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.

7193 lines
263KB

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