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.

7167 lines
262KB

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