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.

7194 lines
263KB

  1. /*
  2. * MOV, 3GP, MP4 muxer
  3. * Copyright (c) 2003 Thomas Raivio
  4. * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
  5. * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  6. *
  7. * This file is part of FFmpeg.
  8. *
  9. * FFmpeg is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2.1 of the License, or (at your option) any later version.
  13. *
  14. * FFmpeg is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with FFmpeg; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. #include <stdint.h>
  24. #include <inttypes.h>
  25. #include "movenc.h"
  26. #include "avformat.h"
  27. #include "avio_internal.h"
  28. #include "riff.h"
  29. #include "avio.h"
  30. #include "isom.h"
  31. #include "av1.h"
  32. #include "avc.h"
  33. #include "libavcodec/ac3_parser_internal.h"
  34. #include "libavcodec/dnxhddata.h"
  35. #include "libavcodec/flac.h"
  36. #include "libavcodec/get_bits.h"
  37. #include "libavcodec/internal.h"
  38. #include "libavcodec/put_bits.h"
  39. #include "libavcodec/vc1_common.h"
  40. #include "libavcodec/raw.h"
  41. #include "internal.h"
  42. #include "libavutil/avstring.h"
  43. #include "libavutil/intfloat.h"
  44. #include "libavutil/mathematics.h"
  45. #include "libavutil/libm.h"
  46. #include "libavutil/opt.h"
  47. #include "libavutil/dict.h"
  48. #include "libavutil/pixdesc.h"
  49. #include "libavutil/stereo3d.h"
  50. #include "libavutil/timecode.h"
  51. #include "libavutil/color_utils.h"
  52. #include "hevc.h"
  53. #include "rtpenc.h"
  54. #include "mov_chan.h"
  55. #include "vpcc.h"
  56. static const AVOption options[] = {
  57. { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  58. { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  59. { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
  60. { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  61. { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  62. { "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  63. { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  64. { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  65. { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  66. { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  67. { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  68. { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  69. { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  70. { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  71. { "cmaf", "Write CMAF compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_CMAF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  72. { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  73. { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  74. { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  75. { "skip_sidx", "Skip writing of sidx atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
  76. { "write_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. if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
  1688. track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
  1689. track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
  1690. if ((track->par->width >= 1920 && track->par->height >= 1080)
  1691. || (track->par->width == 1280 && track->par->height == 720)) {
  1692. av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
  1693. track->par->color_primaries = AVCOL_PRI_BT709;
  1694. } else if (track->par->width == 720 && track->height == 576) {
  1695. av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
  1696. track->par->color_primaries = AVCOL_PRI_BT470BG;
  1697. } else if (track->par->width == 720 &&
  1698. (track->height == 486 || track->height == 480)) {
  1699. av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
  1700. track->par->color_primaries = AVCOL_PRI_SMPTE170M;
  1701. } else {
  1702. av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
  1703. }
  1704. switch (track->par->color_primaries) {
  1705. case AVCOL_PRI_BT709:
  1706. track->par->color_trc = AVCOL_TRC_BT709;
  1707. track->par->color_space = AVCOL_SPC_BT709;
  1708. break;
  1709. case AVCOL_PRI_SMPTE170M:
  1710. case AVCOL_PRI_BT470BG:
  1711. track->par->color_trc = AVCOL_TRC_BT709;
  1712. track->par->color_space = AVCOL_SPC_SMPTE170M;
  1713. break;
  1714. }
  1715. }
  1716. /* We should only ever be called by MOV or MP4. */
  1717. av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
  1718. avio_wb32(pb, 0); /* size */
  1719. ffio_wfourcc(pb, "colr");
  1720. if (track->mode == MODE_MP4)
  1721. ffio_wfourcc(pb, "nclx");
  1722. else
  1723. ffio_wfourcc(pb, "nclc");
  1724. avio_wb16(pb, track->par->color_primaries);
  1725. avio_wb16(pb, track->par->color_trc);
  1726. avio_wb16(pb, track->par->color_space);
  1727. if (track->mode == MODE_MP4) {
  1728. int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
  1729. avio_w8(pb, full_range << 7);
  1730. }
  1731. return update_size(pb, pos);
  1732. }
  1733. static int mov_write_clli_tag(AVIOContext *pb, MOVTrack *track)
  1734. {
  1735. const uint8_t *side_data;
  1736. const AVContentLightMetadata *content_light_metadata;
  1737. side_data = av_stream_get_side_data(track->st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL, NULL);
  1738. if (!side_data) {
  1739. av_log(NULL, AV_LOG_WARNING, "Not writing 'clli' atom. No content light level info.\n");
  1740. return 0;
  1741. }
  1742. content_light_metadata = (const AVContentLightMetadata*)side_data;
  1743. avio_wb32(pb, 12); // size
  1744. ffio_wfourcc(pb, "clli");
  1745. avio_wb16(pb, content_light_metadata->MaxCLL);
  1746. avio_wb16(pb, content_light_metadata->MaxFALL);
  1747. return 12;
  1748. }
  1749. static void find_compressor(char * compressor_name, int len, MOVTrack *track)
  1750. {
  1751. AVDictionaryEntry *encoder;
  1752. int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
  1753. || (track->par->width == 1440 && track->par->height == 1080)
  1754. || (track->par->width == 1920 && track->par->height == 1080);
  1755. if (track->mode == MODE_MOV &&
  1756. (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
  1757. av_strlcpy(compressor_name, encoder->value, 32);
  1758. } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
  1759. int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
  1760. AVStream *st = track->st;
  1761. int rate = defined_frame_rate(NULL, st);
  1762. av_strlcatf(compressor_name, len, "XDCAM");
  1763. if (track->par->format == AV_PIX_FMT_YUV422P) {
  1764. av_strlcatf(compressor_name, len, " HD422");
  1765. } else if(track->par->width == 1440) {
  1766. av_strlcatf(compressor_name, len, " HD");
  1767. } else
  1768. av_strlcatf(compressor_name, len, " EX");
  1769. av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
  1770. av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
  1771. }
  1772. }
  1773. static int mov_write_video_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  1774. {
  1775. int64_t pos = avio_tell(pb);
  1776. char compressor_name[32] = { 0 };
  1777. int avid = 0;
  1778. int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
  1779. || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
  1780. || track->par->codec_id == AV_CODEC_ID_V308
  1781. || track->par->codec_id == AV_CODEC_ID_V408
  1782. || track->par->codec_id == AV_CODEC_ID_V410
  1783. || track->par->codec_id == AV_CODEC_ID_V210);
  1784. avio_wb32(pb, 0); /* size */
  1785. if (mov->encryption_scheme != MOV_ENC_NONE) {
  1786. ffio_wfourcc(pb, "encv");
  1787. } else {
  1788. avio_wl32(pb, track->tag); // store it byteswapped
  1789. }
  1790. avio_wb32(pb, 0); /* Reserved */
  1791. avio_wb16(pb, 0); /* Reserved */
  1792. avio_wb16(pb, 1); /* Data-reference index */
  1793. if (uncompressed_ycbcr) {
  1794. avio_wb16(pb, 2); /* Codec stream version */
  1795. } else {
  1796. avio_wb16(pb, 0); /* Codec stream version */
  1797. }
  1798. avio_wb16(pb, 0); /* Codec stream revision (=0) */
  1799. if (track->mode == MODE_MOV) {
  1800. ffio_wfourcc(pb, "FFMP"); /* Vendor */
  1801. if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
  1802. avio_wb32(pb, 0); /* Temporal Quality */
  1803. avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
  1804. } else {
  1805. avio_wb32(pb, 0x200); /* Temporal Quality = normal */
  1806. avio_wb32(pb, 0x200); /* Spatial Quality = normal */
  1807. }
  1808. } else {
  1809. avio_wb32(pb, 0); /* Reserved */
  1810. avio_wb32(pb, 0); /* Reserved */
  1811. avio_wb32(pb, 0); /* Reserved */
  1812. }
  1813. avio_wb16(pb, track->par->width); /* Video width */
  1814. avio_wb16(pb, track->height); /* Video height */
  1815. avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
  1816. avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
  1817. avio_wb32(pb, 0); /* Data size (= 0) */
  1818. avio_wb16(pb, 1); /* Frame count (= 1) */
  1819. /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
  1820. find_compressor(compressor_name, 32, track);
  1821. avio_w8(pb, strlen(compressor_name));
  1822. avio_write(pb, compressor_name, 31);
  1823. if (track->mode == MODE_MOV &&
  1824. (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
  1825. avio_wb16(pb, 0x18);
  1826. else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
  1827. avio_wb16(pb, track->par->bits_per_coded_sample |
  1828. (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
  1829. else
  1830. avio_wb16(pb, 0x18); /* Reserved */
  1831. if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
  1832. int pal_size = 1 << track->par->bits_per_coded_sample;
  1833. int i;
  1834. avio_wb16(pb, 0); /* Color table ID */
  1835. avio_wb32(pb, 0); /* Color table seed */
  1836. avio_wb16(pb, 0x8000); /* Color table flags */
  1837. avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
  1838. for (i = 0; i < pal_size; i++) {
  1839. uint32_t rgb = track->palette[i];
  1840. uint16_t r = (rgb >> 16) & 0xff;
  1841. uint16_t g = (rgb >> 8) & 0xff;
  1842. uint16_t b = rgb & 0xff;
  1843. avio_wb16(pb, 0);
  1844. avio_wb16(pb, (r << 8) | r);
  1845. avio_wb16(pb, (g << 8) | g);
  1846. avio_wb16(pb, (b << 8) | b);
  1847. }
  1848. } else
  1849. avio_wb16(pb, 0xffff); /* Reserved */
  1850. if (track->tag == MKTAG('m','p','4','v'))
  1851. mov_write_esds_tag(pb, track);
  1852. else if (track->par->codec_id == AV_CODEC_ID_H263)
  1853. mov_write_d263_tag(pb);
  1854. else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
  1855. track->par->codec_id == AV_CODEC_ID_SVQ3) {
  1856. mov_write_extradata_tag(pb, track);
  1857. avio_wb32(pb, 0);
  1858. } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
  1859. mov_write_avid_tag(pb, track);
  1860. avid = 1;
  1861. } else if (track->par->codec_id == AV_CODEC_ID_HEVC)
  1862. mov_write_hvcc_tag(pb, track);
  1863. else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
  1864. mov_write_avcc_tag(pb, track);
  1865. if (track->mode == MODE_IPOD)
  1866. mov_write_uuid_tag_ipod(pb);
  1867. } else if (track->par->codec_id == AV_CODEC_ID_VP9) {
  1868. mov_write_vpcc_tag(mov->fc, pb, track);
  1869. } else if (track->par->codec_id == AV_CODEC_ID_AV1) {
  1870. mov_write_av1c_tag(pb, track);
  1871. } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
  1872. mov_write_dvc1_tag(pb, track);
  1873. else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
  1874. track->par->codec_id == AV_CODEC_ID_VP6A) {
  1875. /* Don't write any potential extradata here - the cropping
  1876. * is signalled via the normal width/height fields. */
  1877. } else if (track->par->codec_id == AV_CODEC_ID_R10K) {
  1878. if (track->par->codec_tag == MKTAG('R','1','0','k'))
  1879. mov_write_dpxe_tag(pb, track);
  1880. } else if (track->vos_len > 0)
  1881. mov_write_glbl_tag(pb, track);
  1882. if (track->par->codec_id != AV_CODEC_ID_H264 &&
  1883. track->par->codec_id != AV_CODEC_ID_MPEG4 &&
  1884. track->par->codec_id != AV_CODEC_ID_DNXHD) {
  1885. int field_order = track->par->field_order;
  1886. #if FF_API_LAVF_AVCTX
  1887. FF_DISABLE_DEPRECATION_WARNINGS
  1888. if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
  1889. field_order = track->st->codec->field_order;
  1890. FF_ENABLE_DEPRECATION_WARNINGS
  1891. #endif
  1892. if (field_order != AV_FIELD_UNKNOWN)
  1893. mov_write_fiel_tag(pb, track, field_order);
  1894. }
  1895. if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
  1896. if (track->mode == MODE_MOV)
  1897. mov_write_gama_tag(s, pb, track, mov->gamma);
  1898. else
  1899. av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
  1900. }
  1901. if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
  1902. if (track->mode == MODE_MOV || track->mode == MODE_MP4)
  1903. mov_write_colr_tag(pb, track, mov->flags & FF_MOV_FLAG_PREFER_ICC);
  1904. else
  1905. av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
  1906. }
  1907. if (mov->flags & FF_MOV_FLAG_WRITE_CLLI) {
  1908. if (track->mode == MODE_MOV || track->mode == MODE_MP4)
  1909. mov_write_clli_tag(pb, track);
  1910. else
  1911. av_log(mov->fc, AV_LOG_WARNING, "Not writing 'clli' atom. Format is not MOV or MP4.\n");
  1912. }
  1913. if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
  1914. AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
  1915. AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
  1916. if (stereo_3d)
  1917. mov_write_st3d_tag(s, pb, stereo_3d);
  1918. if (spherical_mapping)
  1919. mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
  1920. }
  1921. if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
  1922. mov_write_pasp_tag(pb, track);
  1923. }
  1924. if (uncompressed_ycbcr){
  1925. mov_write_clap_tag(pb, track);
  1926. }
  1927. if (mov->encryption_scheme != MOV_ENC_NONE) {
  1928. ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
  1929. }
  1930. /* extra padding for avid stsd */
  1931. /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
  1932. if (avid)
  1933. avio_wb32(pb, 0);
  1934. return update_size(pb, pos);
  1935. }
  1936. static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
  1937. {
  1938. int64_t pos = avio_tell(pb);
  1939. avio_wb32(pb, 0); /* size */
  1940. ffio_wfourcc(pb, "rtp ");
  1941. avio_wb32(pb, 0); /* Reserved */
  1942. avio_wb16(pb, 0); /* Reserved */
  1943. avio_wb16(pb, 1); /* Data-reference index */
  1944. avio_wb16(pb, 1); /* Hint track version */
  1945. avio_wb16(pb, 1); /* Highest compatible version */
  1946. avio_wb32(pb, track->max_packet_size); /* Max packet size */
  1947. avio_wb32(pb, 12); /* size */
  1948. ffio_wfourcc(pb, "tims");
  1949. avio_wb32(pb, track->timescale);
  1950. return update_size(pb, pos);
  1951. }
  1952. static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
  1953. {
  1954. uint64_t str_size =strlen(reel_name);
  1955. int64_t pos = avio_tell(pb);
  1956. if (str_size >= UINT16_MAX){
  1957. av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
  1958. avio_wb16(pb, 0);
  1959. return AVERROR(EINVAL);
  1960. }
  1961. avio_wb32(pb, 0); /* size */
  1962. ffio_wfourcc(pb, "name"); /* Data format */
  1963. avio_wb16(pb, str_size); /* string size */
  1964. avio_wb16(pb, track->language); /* langcode */
  1965. avio_write(pb, reel_name, str_size); /* reel name */
  1966. return update_size(pb,pos);
  1967. }
  1968. static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
  1969. {
  1970. int64_t pos = avio_tell(pb);
  1971. #if 1
  1972. int frame_duration;
  1973. int nb_frames;
  1974. AVDictionaryEntry *t = NULL;
  1975. if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
  1976. #if FF_API_LAVF_AVCTX
  1977. FF_DISABLE_DEPRECATION_WARNINGS
  1978. frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
  1979. nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
  1980. FF_ENABLE_DEPRECATION_WARNINGS
  1981. #else
  1982. av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
  1983. return AVERROR(EINVAL);
  1984. #endif
  1985. } else {
  1986. frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
  1987. nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
  1988. }
  1989. if (nb_frames > 255) {
  1990. av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
  1991. return AVERROR(EINVAL);
  1992. }
  1993. avio_wb32(pb, 0); /* size */
  1994. ffio_wfourcc(pb, "tmcd"); /* Data format */
  1995. avio_wb32(pb, 0); /* Reserved */
  1996. avio_wb32(pb, 1); /* Data reference index */
  1997. avio_wb32(pb, 0); /* Flags */
  1998. avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
  1999. avio_wb32(pb, track->timescale); /* Timescale */
  2000. avio_wb32(pb, frame_duration); /* Frame duration */
  2001. avio_w8(pb, nb_frames); /* Number of frames */
  2002. avio_w8(pb, 0); /* Reserved */
  2003. t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
  2004. if (t && utf8len(t->value) && track->mode != MODE_MP4)
  2005. mov_write_source_reference_tag(pb, track, t->value);
  2006. else
  2007. avio_wb16(pb, 0); /* zero size */
  2008. #else
  2009. avio_wb32(pb, 0); /* size */
  2010. ffio_wfourcc(pb, "tmcd"); /* Data format */
  2011. avio_wb32(pb, 0); /* Reserved */
  2012. avio_wb32(pb, 1); /* Data reference index */
  2013. if (track->par->extradata_size)
  2014. avio_write(pb, track->par->extradata, track->par->extradata_size);
  2015. #endif
  2016. return update_size(pb, pos);
  2017. }
  2018. static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
  2019. {
  2020. int64_t pos = avio_tell(pb);
  2021. avio_wb32(pb, 0); /* size */
  2022. ffio_wfourcc(pb, "gpmd");
  2023. avio_wb32(pb, 0); /* Reserved */
  2024. avio_wb16(pb, 0); /* Reserved */
  2025. avio_wb16(pb, 1); /* Data-reference index */
  2026. avio_wb32(pb, 0); /* Reserved */
  2027. return update_size(pb, pos);
  2028. }
  2029. static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  2030. {
  2031. int64_t pos = avio_tell(pb);
  2032. int ret = 0;
  2033. avio_wb32(pb, 0); /* size */
  2034. ffio_wfourcc(pb, "stsd");
  2035. avio_wb32(pb, 0); /* version & flags */
  2036. avio_wb32(pb, 1); /* entry count */
  2037. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
  2038. ret = mov_write_video_tag(s, pb, mov, track);
  2039. else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  2040. ret = mov_write_audio_tag(s, pb, mov, track);
  2041. else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
  2042. ret = mov_write_subtitle_tag(pb, track);
  2043. else if (track->par->codec_tag == MKTAG('r','t','p',' '))
  2044. ret = mov_write_rtp_tag(pb, track);
  2045. else if (track->par->codec_tag == MKTAG('t','m','c','d'))
  2046. ret = mov_write_tmcd_tag(pb, track);
  2047. else if (track->par->codec_tag == MKTAG('g','p','m','d'))
  2048. ret = mov_write_gpmd_tag(pb, track);
  2049. if (ret < 0)
  2050. return ret;
  2051. return update_size(pb, pos);
  2052. }
  2053. static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  2054. {
  2055. MOVMuxContext *mov = s->priv_data;
  2056. MOVStts *ctts_entries;
  2057. uint32_t entries = 0;
  2058. uint32_t atom_size;
  2059. int i;
  2060. ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
  2061. if (!ctts_entries)
  2062. return AVERROR(ENOMEM);
  2063. ctts_entries[0].count = 1;
  2064. ctts_entries[0].duration = track->cluster[0].cts;
  2065. for (i = 1; i < track->entry; i++) {
  2066. if (track->cluster[i].cts == ctts_entries[entries].duration) {
  2067. ctts_entries[entries].count++; /* compress */
  2068. } else {
  2069. entries++;
  2070. ctts_entries[entries].duration = track->cluster[i].cts;
  2071. ctts_entries[entries].count = 1;
  2072. }
  2073. }
  2074. entries++; /* last one */
  2075. atom_size = 16 + (entries * 8);
  2076. avio_wb32(pb, atom_size); /* size */
  2077. ffio_wfourcc(pb, "ctts");
  2078. if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
  2079. avio_w8(pb, 1); /* version */
  2080. else
  2081. avio_w8(pb, 0); /* version */
  2082. avio_wb24(pb, 0); /* flags */
  2083. avio_wb32(pb, entries); /* entry count */
  2084. for (i = 0; i < entries; i++) {
  2085. avio_wb32(pb, ctts_entries[i].count);
  2086. avio_wb32(pb, ctts_entries[i].duration);
  2087. }
  2088. av_free(ctts_entries);
  2089. return atom_size;
  2090. }
  2091. /* Time to sample atom */
  2092. static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
  2093. {
  2094. MOVStts *stts_entries = NULL;
  2095. uint32_t entries = -1;
  2096. uint32_t atom_size;
  2097. int i;
  2098. if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
  2099. stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
  2100. if (!stts_entries)
  2101. return AVERROR(ENOMEM);
  2102. stts_entries[0].count = track->sample_count;
  2103. stts_entries[0].duration = 1;
  2104. entries = 1;
  2105. } else {
  2106. if (track->entry) {
  2107. stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
  2108. if (!stts_entries)
  2109. return AVERROR(ENOMEM);
  2110. }
  2111. for (i = 0; i < track->entry; i++) {
  2112. int duration = get_cluster_duration(track, i);
  2113. if (i && duration == stts_entries[entries].duration) {
  2114. stts_entries[entries].count++; /* compress */
  2115. } else {
  2116. entries++;
  2117. stts_entries[entries].duration = duration;
  2118. stts_entries[entries].count = 1;
  2119. }
  2120. }
  2121. entries++; /* last one */
  2122. }
  2123. atom_size = 16 + (entries * 8);
  2124. avio_wb32(pb, atom_size); /* size */
  2125. ffio_wfourcc(pb, "stts");
  2126. avio_wb32(pb, 0); /* version & flags */
  2127. avio_wb32(pb, entries); /* entry count */
  2128. for (i = 0; i < entries; i++) {
  2129. avio_wb32(pb, stts_entries[i].count);
  2130. avio_wb32(pb, stts_entries[i].duration);
  2131. }
  2132. av_free(stts_entries);
  2133. return atom_size;
  2134. }
  2135. static int mov_write_dref_tag(AVIOContext *pb)
  2136. {
  2137. avio_wb32(pb, 28); /* size */
  2138. ffio_wfourcc(pb, "dref");
  2139. avio_wb32(pb, 0); /* version & flags */
  2140. avio_wb32(pb, 1); /* entry count */
  2141. avio_wb32(pb, 0xc); /* size */
  2142. //FIXME add the alis and rsrc atom
  2143. ffio_wfourcc(pb, "url ");
  2144. avio_wb32(pb, 1); /* version & flags */
  2145. return 28;
  2146. }
  2147. static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
  2148. {
  2149. struct sgpd_entry {
  2150. int count;
  2151. int16_t roll_distance;
  2152. int group_description_index;
  2153. };
  2154. struct sgpd_entry *sgpd_entries = NULL;
  2155. int entries = -1;
  2156. int group = 0;
  2157. int i, j;
  2158. const int OPUS_SEEK_PREROLL_MS = 80;
  2159. int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
  2160. (AVRational){1, 1000},
  2161. (AVRational){1, 48000});
  2162. if (!track->entry)
  2163. return 0;
  2164. sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
  2165. if (!sgpd_entries)
  2166. return AVERROR(ENOMEM);
  2167. av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
  2168. if (track->par->codec_id == AV_CODEC_ID_OPUS) {
  2169. for (i = 0; i < track->entry; i++) {
  2170. int roll_samples_remaining = roll_samples;
  2171. int distance = 0;
  2172. for (j = i - 1; j >= 0; j--) {
  2173. roll_samples_remaining -= get_cluster_duration(track, j);
  2174. distance++;
  2175. if (roll_samples_remaining <= 0)
  2176. break;
  2177. }
  2178. /* We don't have enough preceeding samples to compute a valid
  2179. roll_distance here, so this sample can't be independently
  2180. decoded. */
  2181. if (roll_samples_remaining > 0)
  2182. distance = 0;
  2183. /* Verify distance is a maximum of 32 (2.5ms) packets. */
  2184. if (distance > 32)
  2185. return AVERROR_INVALIDDATA;
  2186. if (i && distance == sgpd_entries[entries].roll_distance) {
  2187. sgpd_entries[entries].count++;
  2188. } else {
  2189. entries++;
  2190. sgpd_entries[entries].count = 1;
  2191. sgpd_entries[entries].roll_distance = distance;
  2192. sgpd_entries[entries].group_description_index = distance ? ++group : 0;
  2193. }
  2194. }
  2195. } else {
  2196. entries++;
  2197. sgpd_entries[entries].count = track->sample_count;
  2198. sgpd_entries[entries].roll_distance = 1;
  2199. sgpd_entries[entries].group_description_index = ++group;
  2200. }
  2201. entries++;
  2202. if (!group) {
  2203. av_free(sgpd_entries);
  2204. return 0;
  2205. }
  2206. /* Write sgpd tag */
  2207. avio_wb32(pb, 24 + (group * 2)); /* size */
  2208. ffio_wfourcc(pb, "sgpd");
  2209. avio_wb32(pb, 1 << 24); /* fullbox */
  2210. ffio_wfourcc(pb, "roll");
  2211. avio_wb32(pb, 2); /* default_length */
  2212. avio_wb32(pb, group); /* entry_count */
  2213. for (i = 0; i < entries; i++) {
  2214. if (sgpd_entries[i].group_description_index) {
  2215. avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
  2216. }
  2217. }
  2218. /* Write sbgp tag */
  2219. avio_wb32(pb, 20 + (entries * 8)); /* size */
  2220. ffio_wfourcc(pb, "sbgp");
  2221. avio_wb32(pb, 0); /* fullbox */
  2222. ffio_wfourcc(pb, "roll");
  2223. avio_wb32(pb, entries); /* entry_count */
  2224. for (i = 0; i < entries; i++) {
  2225. avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
  2226. avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
  2227. }
  2228. av_free(sgpd_entries);
  2229. return 0;
  2230. }
  2231. static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  2232. {
  2233. int64_t pos = avio_tell(pb);
  2234. int ret = 0;
  2235. avio_wb32(pb, 0); /* size */
  2236. ffio_wfourcc(pb, "stbl");
  2237. if ((ret = mov_write_stsd_tag(s, pb, mov, track)) < 0)
  2238. return ret;
  2239. mov_write_stts_tag(pb, track);
  2240. if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
  2241. track->par->codec_id == AV_CODEC_ID_TRUEHD ||
  2242. track->par->codec_id == AV_CODEC_ID_MPEGH_3D_AUDIO ||
  2243. track->par->codec_tag == MKTAG('r','t','p',' ')) &&
  2244. track->has_keyframes && track->has_keyframes < track->entry)
  2245. mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
  2246. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
  2247. mov_write_sdtp_tag(pb, track);
  2248. if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
  2249. mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
  2250. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
  2251. track->flags & MOV_TRACK_CTTS && track->entry) {
  2252. if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
  2253. return ret;
  2254. }
  2255. mov_write_stsc_tag(pb, track);
  2256. mov_write_stsz_tag(pb, track);
  2257. mov_write_stco_tag(pb, track);
  2258. if (track->cenc.aes_ctr) {
  2259. ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
  2260. }
  2261. if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
  2262. mov_preroll_write_stbl_atoms(pb, track);
  2263. }
  2264. return update_size(pb, pos);
  2265. }
  2266. static int mov_write_dinf_tag(AVIOContext *pb)
  2267. {
  2268. int64_t pos = avio_tell(pb);
  2269. avio_wb32(pb, 0); /* size */
  2270. ffio_wfourcc(pb, "dinf");
  2271. mov_write_dref_tag(pb);
  2272. return update_size(pb, pos);
  2273. }
  2274. static int mov_write_nmhd_tag(AVIOContext *pb)
  2275. {
  2276. avio_wb32(pb, 12);
  2277. ffio_wfourcc(pb, "nmhd");
  2278. avio_wb32(pb, 0);
  2279. return 12;
  2280. }
  2281. static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
  2282. {
  2283. int64_t pos = avio_tell(pb);
  2284. const char *font = "Lucida Grande";
  2285. avio_wb32(pb, 0); /* size */
  2286. ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
  2287. avio_wb32(pb, 0); /* version & flags */
  2288. avio_wb16(pb, 0); /* text font */
  2289. avio_wb16(pb, 0); /* text face */
  2290. avio_wb16(pb, 12); /* text size */
  2291. avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
  2292. avio_wb16(pb, 0x0000); /* text color (red) */
  2293. avio_wb16(pb, 0x0000); /* text color (green) */
  2294. avio_wb16(pb, 0x0000); /* text color (blue) */
  2295. avio_wb16(pb, 0xffff); /* background color (red) */
  2296. avio_wb16(pb, 0xffff); /* background color (green) */
  2297. avio_wb16(pb, 0xffff); /* background color (blue) */
  2298. avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
  2299. avio_write(pb, font, strlen(font)); /* font name */
  2300. return update_size(pb, pos);
  2301. }
  2302. static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
  2303. {
  2304. int64_t pos = avio_tell(pb);
  2305. avio_wb32(pb, 0); /* size */
  2306. ffio_wfourcc(pb, "gmhd");
  2307. avio_wb32(pb, 0x18); /* gmin size */
  2308. ffio_wfourcc(pb, "gmin");/* generic media info */
  2309. avio_wb32(pb, 0); /* version & flags */
  2310. avio_wb16(pb, 0x40); /* graphics mode = */
  2311. avio_wb16(pb, 0x8000); /* opColor (r?) */
  2312. avio_wb16(pb, 0x8000); /* opColor (g?) */
  2313. avio_wb16(pb, 0x8000); /* opColor (b?) */
  2314. avio_wb16(pb, 0); /* balance */
  2315. avio_wb16(pb, 0); /* reserved */
  2316. /*
  2317. * This special text atom is required for
  2318. * Apple Quicktime chapters. The contents
  2319. * don't appear to be documented, so the
  2320. * bytes are copied verbatim.
  2321. */
  2322. if (track->tag != MKTAG('c','6','0','8')) {
  2323. avio_wb32(pb, 0x2C); /* size */
  2324. ffio_wfourcc(pb, "text");
  2325. avio_wb16(pb, 0x01);
  2326. avio_wb32(pb, 0x00);
  2327. avio_wb32(pb, 0x00);
  2328. avio_wb32(pb, 0x00);
  2329. avio_wb32(pb, 0x01);
  2330. avio_wb32(pb, 0x00);
  2331. avio_wb32(pb, 0x00);
  2332. avio_wb32(pb, 0x00);
  2333. avio_wb32(pb, 0x00004000);
  2334. avio_wb16(pb, 0x0000);
  2335. }
  2336. if (track->par->codec_tag == MKTAG('t','m','c','d')) {
  2337. int64_t tmcd_pos = avio_tell(pb);
  2338. avio_wb32(pb, 0); /* size */
  2339. ffio_wfourcc(pb, "tmcd");
  2340. mov_write_tcmi_tag(pb, track);
  2341. update_size(pb, tmcd_pos);
  2342. } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
  2343. int64_t gpmd_pos = avio_tell(pb);
  2344. avio_wb32(pb, 0); /* size */
  2345. ffio_wfourcc(pb, "gpmd");
  2346. avio_wb32(pb, 0); /* version */
  2347. update_size(pb, gpmd_pos);
  2348. }
  2349. return update_size(pb, pos);
  2350. }
  2351. static int mov_write_smhd_tag(AVIOContext *pb)
  2352. {
  2353. avio_wb32(pb, 16); /* size */
  2354. ffio_wfourcc(pb, "smhd");
  2355. avio_wb32(pb, 0); /* version & flags */
  2356. avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
  2357. avio_wb16(pb, 0); /* reserved */
  2358. return 16;
  2359. }
  2360. static int mov_write_vmhd_tag(AVIOContext *pb)
  2361. {
  2362. avio_wb32(pb, 0x14); /* size (always 0x14) */
  2363. ffio_wfourcc(pb, "vmhd");
  2364. avio_wb32(pb, 0x01); /* version & flags */
  2365. avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
  2366. return 0x14;
  2367. }
  2368. static int is_clcp_track(MOVTrack *track)
  2369. {
  2370. return track->tag == MKTAG('c','7','0','8') ||
  2371. track->tag == MKTAG('c','6','0','8');
  2372. }
  2373. static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
  2374. {
  2375. MOVMuxContext *mov = s->priv_data;
  2376. const char *hdlr, *descr = NULL, *hdlr_type = NULL;
  2377. int64_t pos = avio_tell(pb);
  2378. hdlr = "dhlr";
  2379. hdlr_type = "url ";
  2380. descr = "DataHandler";
  2381. if (track) {
  2382. hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
  2383. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  2384. hdlr_type = "vide";
  2385. descr = "VideoHandler";
  2386. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  2387. hdlr_type = "soun";
  2388. descr = "SoundHandler";
  2389. } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  2390. if (is_clcp_track(track)) {
  2391. hdlr_type = "clcp";
  2392. descr = "ClosedCaptionHandler";
  2393. } else {
  2394. if (track->tag == MKTAG('t','x','3','g')) {
  2395. hdlr_type = "sbtl";
  2396. } else if (track->tag == MKTAG('m','p','4','s')) {
  2397. hdlr_type = "subp";
  2398. } else {
  2399. hdlr_type = "text";
  2400. }
  2401. descr = "SubtitleHandler";
  2402. }
  2403. } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
  2404. hdlr_type = "hint";
  2405. descr = "HintHandler";
  2406. } else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
  2407. hdlr_type = "tmcd";
  2408. descr = "TimeCodeHandler";
  2409. } else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
  2410. hdlr_type = "meta";
  2411. descr = "GoPro MET"; // GoPro Metadata
  2412. } else {
  2413. av_log(s, AV_LOG_WARNING,
  2414. "Unknown hldr_type for %s, writing dummy values\n",
  2415. av_fourcc2str(track->par->codec_tag));
  2416. }
  2417. if (track->st) {
  2418. // hdlr.name is used by some players to identify the content title
  2419. // of the track. So if an alternate handler description is
  2420. // specified, use it.
  2421. AVDictionaryEntry *t;
  2422. t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
  2423. if (t && utf8len(t->value))
  2424. descr = t->value;
  2425. }
  2426. }
  2427. if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
  2428. descr = "";
  2429. avio_wb32(pb, 0); /* size */
  2430. ffio_wfourcc(pb, "hdlr");
  2431. avio_wb32(pb, 0); /* Version & flags */
  2432. avio_write(pb, hdlr, 4); /* handler */
  2433. ffio_wfourcc(pb, hdlr_type); /* handler type */
  2434. avio_wb32(pb, 0); /* reserved */
  2435. avio_wb32(pb, 0); /* reserved */
  2436. avio_wb32(pb, 0); /* reserved */
  2437. if (!track || track->mode == MODE_MOV)
  2438. avio_w8(pb, strlen(descr)); /* pascal string */
  2439. avio_write(pb, descr, strlen(descr)); /* handler description */
  2440. if (track && track->mode != MODE_MOV)
  2441. avio_w8(pb, 0); /* c string */
  2442. return update_size(pb, pos);
  2443. }
  2444. static int mov_write_hmhd_tag(AVIOContext *pb)
  2445. {
  2446. /* This atom must be present, but leaving the values at zero
  2447. * seems harmless. */
  2448. avio_wb32(pb, 28); /* size */
  2449. ffio_wfourcc(pb, "hmhd");
  2450. avio_wb32(pb, 0); /* version, flags */
  2451. avio_wb16(pb, 0); /* maxPDUsize */
  2452. avio_wb16(pb, 0); /* avgPDUsize */
  2453. avio_wb32(pb, 0); /* maxbitrate */
  2454. avio_wb32(pb, 0); /* avgbitrate */
  2455. avio_wb32(pb, 0); /* reserved */
  2456. return 28;
  2457. }
  2458. static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
  2459. {
  2460. int64_t pos = avio_tell(pb);
  2461. int ret;
  2462. avio_wb32(pb, 0); /* size */
  2463. ffio_wfourcc(pb, "minf");
  2464. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
  2465. mov_write_vmhd_tag(pb);
  2466. else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  2467. mov_write_smhd_tag(pb);
  2468. else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  2469. if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
  2470. mov_write_gmhd_tag(pb, track);
  2471. } else {
  2472. mov_write_nmhd_tag(pb);
  2473. }
  2474. } else if (track->tag == MKTAG('r','t','p',' ')) {
  2475. mov_write_hmhd_tag(pb);
  2476. } else if (track->tag == MKTAG('t','m','c','d')) {
  2477. if (track->mode != MODE_MOV)
  2478. mov_write_nmhd_tag(pb);
  2479. else
  2480. mov_write_gmhd_tag(pb, track);
  2481. } else if (track->tag == MKTAG('g','p','m','d')) {
  2482. mov_write_gmhd_tag(pb, track);
  2483. }
  2484. if (track->mode == MODE_MOV) /* ISO 14496-12 8.4.3.1 specifies hdlr only within mdia or meta boxes */
  2485. mov_write_hdlr_tag(s, pb, NULL);
  2486. mov_write_dinf_tag(pb);
  2487. if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
  2488. return ret;
  2489. return update_size(pb, pos);
  2490. }
  2491. static int64_t calc_pts_duration(MOVMuxContext *mov, MOVTrack *track)
  2492. {
  2493. if (track->tag == MKTAG('t','m','c','d')) {
  2494. // tmcd tracks gets track_duration set in mov_write_moov_tag from
  2495. // another track's duration, while the end_pts may be left at zero.
  2496. // Calculate the pts duration for that track instead.
  2497. return av_rescale(calc_pts_duration(mov, &mov->tracks[track->src_track]),
  2498. track->timescale, mov->tracks[track->src_track].timescale);
  2499. }
  2500. if (track->end_pts != AV_NOPTS_VALUE &&
  2501. track->start_dts != AV_NOPTS_VALUE &&
  2502. track->start_cts != AV_NOPTS_VALUE) {
  2503. return track->end_pts - (track->start_dts + track->start_cts);
  2504. }
  2505. return track->track_duration;
  2506. }
  2507. static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  2508. MOVTrack *track)
  2509. {
  2510. int64_t duration = calc_pts_duration(mov, track);
  2511. int version = duration < INT32_MAX ? 0 : 1;
  2512. if (track->mode == MODE_ISM)
  2513. version = 1;
  2514. (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
  2515. ffio_wfourcc(pb, "mdhd");
  2516. avio_w8(pb, version);
  2517. avio_wb24(pb, 0); /* flags */
  2518. if (version == 1) {
  2519. avio_wb64(pb, track->time);
  2520. avio_wb64(pb, track->time);
  2521. } else {
  2522. avio_wb32(pb, track->time); /* creation time */
  2523. avio_wb32(pb, track->time); /* modification time */
  2524. }
  2525. avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
  2526. if (!track->entry && mov->mode == MODE_ISM)
  2527. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  2528. else if (!track->entry)
  2529. (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
  2530. else
  2531. (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration); /* duration */
  2532. avio_wb16(pb, track->language); /* language */
  2533. avio_wb16(pb, 0); /* reserved (quality) */
  2534. if (version != 0 && track->mode == MODE_MOV) {
  2535. av_log(NULL, AV_LOG_ERROR,
  2536. "FATAL error, file duration too long for timebase, this file will not be\n"
  2537. "playable with QuickTime. Choose a different timebase with "
  2538. "-video_track_timescale or a different container format\n");
  2539. }
  2540. return 32;
  2541. }
  2542. static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
  2543. MOVMuxContext *mov, MOVTrack *track)
  2544. {
  2545. int64_t pos = avio_tell(pb);
  2546. int ret;
  2547. avio_wb32(pb, 0); /* size */
  2548. ffio_wfourcc(pb, "mdia");
  2549. mov_write_mdhd_tag(pb, mov, track);
  2550. mov_write_hdlr_tag(s, pb, track);
  2551. if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
  2552. return ret;
  2553. return update_size(pb, pos);
  2554. }
  2555. /* transformation matrix
  2556. |a b u|
  2557. |c d v|
  2558. |tx ty w| */
  2559. static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
  2560. int16_t d, int16_t tx, int16_t ty)
  2561. {
  2562. avio_wb32(pb, a << 16); /* 16.16 format */
  2563. avio_wb32(pb, b << 16); /* 16.16 format */
  2564. avio_wb32(pb, 0); /* u in 2.30 format */
  2565. avio_wb32(pb, c << 16); /* 16.16 format */
  2566. avio_wb32(pb, d << 16); /* 16.16 format */
  2567. avio_wb32(pb, 0); /* v in 2.30 format */
  2568. avio_wb32(pb, tx << 16); /* 16.16 format */
  2569. avio_wb32(pb, ty << 16); /* 16.16 format */
  2570. avio_wb32(pb, 1 << 30); /* w in 2.30 format */
  2571. }
  2572. static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  2573. MOVTrack *track, AVStream *st)
  2574. {
  2575. int64_t duration = av_rescale_rnd(calc_pts_duration(mov, track),
  2576. MOV_TIMESCALE, track->timescale,
  2577. AV_ROUND_UP);
  2578. int version = duration < INT32_MAX ? 0 : 1;
  2579. int flags = MOV_TKHD_FLAG_IN_MOVIE;
  2580. int rotation = 0;
  2581. int group = 0;
  2582. uint32_t *display_matrix = NULL;
  2583. int display_matrix_size, i;
  2584. if (st) {
  2585. if (mov->per_stream_grouping)
  2586. group = st->index;
  2587. else
  2588. group = st->codecpar->codec_type;
  2589. display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
  2590. &display_matrix_size);
  2591. if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
  2592. display_matrix = NULL;
  2593. }
  2594. if (track->flags & MOV_TRACK_ENABLED)
  2595. flags |= MOV_TKHD_FLAG_ENABLED;
  2596. if (track->mode == MODE_ISM)
  2597. version = 1;
  2598. (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
  2599. ffio_wfourcc(pb, "tkhd");
  2600. avio_w8(pb, version);
  2601. avio_wb24(pb, flags);
  2602. if (version == 1) {
  2603. avio_wb64(pb, track->time);
  2604. avio_wb64(pb, track->time);
  2605. } else {
  2606. avio_wb32(pb, track->time); /* creation time */
  2607. avio_wb32(pb, track->time); /* modification time */
  2608. }
  2609. avio_wb32(pb, track->track_id); /* track-id */
  2610. avio_wb32(pb, 0); /* reserved */
  2611. if (!track->entry && mov->mode == MODE_ISM)
  2612. (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
  2613. else if (!track->entry)
  2614. (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
  2615. else
  2616. (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
  2617. avio_wb32(pb, 0); /* reserved */
  2618. avio_wb32(pb, 0); /* reserved */
  2619. avio_wb16(pb, 0); /* layer */
  2620. avio_wb16(pb, group); /* alternate group) */
  2621. /* Volume, only for audio */
  2622. if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
  2623. avio_wb16(pb, 0x0100);
  2624. else
  2625. avio_wb16(pb, 0);
  2626. avio_wb16(pb, 0); /* reserved */
  2627. /* Matrix structure */
  2628. #if FF_API_OLD_ROTATE_API
  2629. if (st && st->metadata) {
  2630. AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
  2631. rotation = (rot && rot->value) ? atoi(rot->value) : 0;
  2632. }
  2633. #endif
  2634. if (display_matrix) {
  2635. for (i = 0; i < 9; i++)
  2636. avio_wb32(pb, display_matrix[i]);
  2637. #if FF_API_OLD_ROTATE_API
  2638. } else if (rotation == 90) {
  2639. write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
  2640. } else if (rotation == 180) {
  2641. write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
  2642. } else if (rotation == 270) {
  2643. write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
  2644. #endif
  2645. } else {
  2646. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  2647. }
  2648. /* Track width and height, for visual only */
  2649. if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
  2650. track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
  2651. int64_t track_width_1616;
  2652. if (track->mode == MODE_MOV) {
  2653. track_width_1616 = track->par->width * 0x10000ULL;
  2654. } else {
  2655. track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
  2656. track->par->width * 0x10000LL,
  2657. st->sample_aspect_ratio.den);
  2658. if (!track_width_1616 ||
  2659. track->height != track->par->height ||
  2660. track_width_1616 > UINT32_MAX)
  2661. track_width_1616 = track->par->width * 0x10000ULL;
  2662. }
  2663. if (track_width_1616 > UINT32_MAX) {
  2664. av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
  2665. track_width_1616 = 0;
  2666. }
  2667. avio_wb32(pb, track_width_1616);
  2668. if (track->height > 0xFFFF) {
  2669. av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
  2670. avio_wb32(pb, 0);
  2671. } else
  2672. avio_wb32(pb, track->height * 0x10000U);
  2673. } else {
  2674. avio_wb32(pb, 0);
  2675. avio_wb32(pb, 0);
  2676. }
  2677. return 0x5c;
  2678. }
  2679. static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
  2680. {
  2681. int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
  2682. track->par->sample_aspect_ratio.den);
  2683. int64_t pos = avio_tell(pb);
  2684. avio_wb32(pb, 0); /* size */
  2685. ffio_wfourcc(pb, "tapt");
  2686. avio_wb32(pb, 20);
  2687. ffio_wfourcc(pb, "clef");
  2688. avio_wb32(pb, 0);
  2689. avio_wb32(pb, width << 16);
  2690. avio_wb32(pb, track->par->height << 16);
  2691. avio_wb32(pb, 20);
  2692. ffio_wfourcc(pb, "prof");
  2693. avio_wb32(pb, 0);
  2694. avio_wb32(pb, width << 16);
  2695. avio_wb32(pb, track->par->height << 16);
  2696. avio_wb32(pb, 20);
  2697. ffio_wfourcc(pb, "enof");
  2698. avio_wb32(pb, 0);
  2699. avio_wb32(pb, track->par->width << 16);
  2700. avio_wb32(pb, track->par->height << 16);
  2701. return update_size(pb, pos);
  2702. }
  2703. // This box seems important for the psp playback ... without it the movie seems to hang
  2704. static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
  2705. MOVTrack *track)
  2706. {
  2707. int64_t duration = av_rescale_rnd(calc_pts_duration(mov, track),
  2708. MOV_TIMESCALE, track->timescale,
  2709. AV_ROUND_UP);
  2710. int version = duration < INT32_MAX ? 0 : 1;
  2711. int entry_size, entry_count, size;
  2712. int64_t delay, start_ct = track->start_cts;
  2713. int64_t start_dts = track->start_dts;
  2714. if (track->entry) {
  2715. if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
  2716. av_log(mov->fc, AV_LOG_DEBUG,
  2717. "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
  2718. track->cluster[0].dts, track->cluster[0].cts,
  2719. start_dts, start_ct, track->track_id);
  2720. start_dts = track->cluster[0].dts;
  2721. start_ct = track->cluster[0].cts;
  2722. }
  2723. }
  2724. delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
  2725. track->timescale, AV_ROUND_DOWN);
  2726. version |= delay < INT32_MAX ? 0 : 1;
  2727. entry_size = (version == 1) ? 20 : 12;
  2728. entry_count = 1 + (delay > 0);
  2729. size = 24 + entry_count * entry_size;
  2730. /* write the atom data */
  2731. avio_wb32(pb, size);
  2732. ffio_wfourcc(pb, "edts");
  2733. avio_wb32(pb, size - 8);
  2734. ffio_wfourcc(pb, "elst");
  2735. avio_w8(pb, version);
  2736. avio_wb24(pb, 0); /* flags */
  2737. avio_wb32(pb, entry_count);
  2738. if (delay > 0) { /* add an empty edit to delay presentation */
  2739. /* In the positive delay case, the delay includes the cts
  2740. * offset, and the second edit list entry below trims out
  2741. * the same amount from the actual content. This makes sure
  2742. * that the offset last sample is included in the edit
  2743. * list duration as well. */
  2744. if (version == 1) {
  2745. avio_wb64(pb, delay);
  2746. avio_wb64(pb, -1);
  2747. } else {
  2748. avio_wb32(pb, delay);
  2749. avio_wb32(pb, -1);
  2750. }
  2751. avio_wb32(pb, 0x00010000);
  2752. } else {
  2753. /* Avoid accidentally ending up with start_ct = -1 which has got a
  2754. * special meaning. Normally start_ct should end up positive or zero
  2755. * here, but use FFMIN in case dts is a small positive integer
  2756. * rounded to 0 when represented in MOV_TIMESCALE units. */
  2757. av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
  2758. start_ct = -FFMIN(start_dts, 0);
  2759. /* Note, this delay is calculated from the pts of the first sample,
  2760. * ensuring that we don't reduce the duration for cases with
  2761. * dts<0 pts=0. */
  2762. duration += delay;
  2763. }
  2764. /* For fragmented files, we don't know the full length yet. Setting
  2765. * duration to 0 allows us to only specify the offset, including
  2766. * the rest of the content (from all future fragments) without specifying
  2767. * an explicit duration. */
  2768. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  2769. duration = 0;
  2770. /* duration */
  2771. if (version == 1) {
  2772. avio_wb64(pb, duration);
  2773. avio_wb64(pb, start_ct);
  2774. } else {
  2775. avio_wb32(pb, duration);
  2776. avio_wb32(pb, start_ct);
  2777. }
  2778. avio_wb32(pb, 0x00010000);
  2779. return size;
  2780. }
  2781. static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
  2782. {
  2783. avio_wb32(pb, 20); // size
  2784. ffio_wfourcc(pb, "tref");
  2785. avio_wb32(pb, 12); // size (subatom)
  2786. avio_wl32(pb, track->tref_tag);
  2787. avio_wb32(pb, track->tref_id);
  2788. return 20;
  2789. }
  2790. // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
  2791. static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
  2792. {
  2793. avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
  2794. ffio_wfourcc(pb, "uuid");
  2795. ffio_wfourcc(pb, "USMT");
  2796. avio_wb32(pb, 0x21d24fce);
  2797. avio_wb32(pb, 0xbb88695c);
  2798. avio_wb32(pb, 0xfac9c740);
  2799. avio_wb32(pb, 0x1c); // another size here!
  2800. ffio_wfourcc(pb, "MTDT");
  2801. avio_wb32(pb, 0x00010012);
  2802. avio_wb32(pb, 0x0a);
  2803. avio_wb32(pb, 0x55c40000);
  2804. avio_wb32(pb, 0x1);
  2805. avio_wb32(pb, 0x0);
  2806. return 0x34;
  2807. }
  2808. static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
  2809. {
  2810. AVFormatContext *ctx = track->rtp_ctx;
  2811. char buf[1000] = "";
  2812. int len;
  2813. ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
  2814. NULL, NULL, 0, 0, ctx);
  2815. av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
  2816. len = strlen(buf);
  2817. avio_wb32(pb, len + 24);
  2818. ffio_wfourcc(pb, "udta");
  2819. avio_wb32(pb, len + 16);
  2820. ffio_wfourcc(pb, "hnti");
  2821. avio_wb32(pb, len + 8);
  2822. ffio_wfourcc(pb, "sdp ");
  2823. avio_write(pb, buf, len);
  2824. return len + 24;
  2825. }
  2826. static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
  2827. const char *tag, const char *str)
  2828. {
  2829. int64_t pos = avio_tell(pb);
  2830. AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
  2831. if (!t || !utf8len(t->value))
  2832. return 0;
  2833. avio_wb32(pb, 0); /* size */
  2834. ffio_wfourcc(pb, tag); /* type */
  2835. avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
  2836. return update_size(pb, pos);
  2837. }
  2838. static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
  2839. AVStream *st)
  2840. {
  2841. AVIOContext *pb_buf;
  2842. int ret, size;
  2843. uint8_t *buf;
  2844. if (!st)
  2845. return 0;
  2846. ret = avio_open_dyn_buf(&pb_buf);
  2847. if (ret < 0)
  2848. return ret;
  2849. if (mov->mode & (MODE_MP4|MODE_MOV))
  2850. mov_write_track_metadata(pb_buf, st, "name", "title");
  2851. if ((size = avio_get_dyn_buf(pb_buf, &buf)) > 0) {
  2852. avio_wb32(pb, size + 8);
  2853. ffio_wfourcc(pb, "udta");
  2854. avio_write(pb, buf, size);
  2855. }
  2856. ffio_free_dyn_buf(&pb_buf);
  2857. return 0;
  2858. }
  2859. static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
  2860. MOVTrack *track, AVStream *st)
  2861. {
  2862. int64_t pos = avio_tell(pb);
  2863. int entry_backup = track->entry;
  2864. int chunk_backup = track->chunkCount;
  2865. int ret;
  2866. /* If we want to have an empty moov, but some samples already have been
  2867. * buffered (delay_moov), pretend that no samples have been written yet. */
  2868. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
  2869. track->chunkCount = track->entry = 0;
  2870. avio_wb32(pb, 0); /* size */
  2871. ffio_wfourcc(pb, "trak");
  2872. mov_write_tkhd_tag(pb, mov, track, st);
  2873. av_assert2(mov->use_editlist >= 0);
  2874. if (track->start_dts != AV_NOPTS_VALUE) {
  2875. if (mov->use_editlist)
  2876. mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
  2877. else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
  2878. av_log(mov->fc, AV_LOG_WARNING,
  2879. "Not writing any edit list even though one would have been required\n");
  2880. }
  2881. if (track->tref_tag)
  2882. mov_write_tref_tag(pb, track);
  2883. if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
  2884. return ret;
  2885. if (track->mode == MODE_PSP)
  2886. mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
  2887. if (track->tag == MKTAG('r','t','p',' '))
  2888. mov_write_udta_sdp(pb, track);
  2889. if (track->mode == MODE_MOV) {
  2890. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  2891. double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
  2892. if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
  2893. mov_write_tapt_tag(pb, track);
  2894. }
  2895. }
  2896. if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
  2897. mov_write_tapt_tag(pb, track);
  2898. }
  2899. }
  2900. mov_write_track_udta_tag(pb, mov, st);
  2901. track->entry = entry_backup;
  2902. track->chunkCount = chunk_backup;
  2903. return update_size(pb, pos);
  2904. }
  2905. static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
  2906. {
  2907. int i, has_audio = 0, has_video = 0;
  2908. int64_t pos = avio_tell(pb);
  2909. int audio_profile = mov->iods_audio_profile;
  2910. int video_profile = mov->iods_video_profile;
  2911. for (i = 0; i < mov->nb_streams; i++) {
  2912. if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  2913. has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
  2914. has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
  2915. }
  2916. }
  2917. if (audio_profile < 0)
  2918. audio_profile = 0xFF - has_audio;
  2919. if (video_profile < 0)
  2920. video_profile = 0xFF - has_video;
  2921. avio_wb32(pb, 0x0); /* size */
  2922. ffio_wfourcc(pb, "iods");
  2923. avio_wb32(pb, 0); /* version & flags */
  2924. put_descr(pb, 0x10, 7);
  2925. avio_wb16(pb, 0x004f);
  2926. avio_w8(pb, 0xff);
  2927. avio_w8(pb, 0xff);
  2928. avio_w8(pb, audio_profile);
  2929. avio_w8(pb, video_profile);
  2930. avio_w8(pb, 0xff);
  2931. return update_size(pb, pos);
  2932. }
  2933. static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
  2934. {
  2935. avio_wb32(pb, 0x20); /* size */
  2936. ffio_wfourcc(pb, "trex");
  2937. avio_wb32(pb, 0); /* version & flags */
  2938. avio_wb32(pb, track->track_id); /* track ID */
  2939. avio_wb32(pb, 1); /* default sample description index */
  2940. avio_wb32(pb, 0); /* default sample duration */
  2941. avio_wb32(pb, 0); /* default sample size */
  2942. avio_wb32(pb, 0); /* default sample flags */
  2943. return 0;
  2944. }
  2945. static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
  2946. {
  2947. int64_t pos = avio_tell(pb);
  2948. int i;
  2949. avio_wb32(pb, 0x0); /* size */
  2950. ffio_wfourcc(pb, "mvex");
  2951. for (i = 0; i < mov->nb_streams; i++)
  2952. mov_write_trex_tag(pb, &mov->tracks[i]);
  2953. return update_size(pb, pos);
  2954. }
  2955. static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  2956. {
  2957. int max_track_id = 1, i;
  2958. int64_t max_track_len = 0;
  2959. int version;
  2960. for (i = 0; i < mov->nb_streams; i++) {
  2961. if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
  2962. int64_t max_track_len_temp = av_rescale_rnd(
  2963. calc_pts_duration(mov, &mov->tracks[i]),
  2964. MOV_TIMESCALE,
  2965. mov->tracks[i].timescale,
  2966. AV_ROUND_UP);
  2967. if (max_track_len < max_track_len_temp)
  2968. max_track_len = max_track_len_temp;
  2969. if (max_track_id < mov->tracks[i].track_id)
  2970. max_track_id = mov->tracks[i].track_id;
  2971. }
  2972. }
  2973. /* If using delay_moov, make sure the output is the same as if no
  2974. * samples had been written yet. */
  2975. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  2976. max_track_len = 0;
  2977. max_track_id = 1;
  2978. }
  2979. version = max_track_len < UINT32_MAX ? 0 : 1;
  2980. avio_wb32(pb, version == 1 ? 120 : 108); /* size */
  2981. ffio_wfourcc(pb, "mvhd");
  2982. avio_w8(pb, version);
  2983. avio_wb24(pb, 0); /* flags */
  2984. if (version == 1) {
  2985. avio_wb64(pb, mov->time);
  2986. avio_wb64(pb, mov->time);
  2987. } else {
  2988. avio_wb32(pb, mov->time); /* creation time */
  2989. avio_wb32(pb, mov->time); /* modification time */
  2990. }
  2991. avio_wb32(pb, MOV_TIMESCALE);
  2992. (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
  2993. avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
  2994. avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
  2995. avio_wb16(pb, 0); /* reserved */
  2996. avio_wb32(pb, 0); /* reserved */
  2997. avio_wb32(pb, 0); /* reserved */
  2998. /* Matrix structure */
  2999. write_matrix(pb, 1, 0, 0, 1, 0, 0);
  3000. avio_wb32(pb, 0); /* reserved (preview time) */
  3001. avio_wb32(pb, 0); /* reserved (preview duration) */
  3002. avio_wb32(pb, 0); /* reserved (poster time) */
  3003. avio_wb32(pb, 0); /* reserved (selection time) */
  3004. avio_wb32(pb, 0); /* reserved (selection duration) */
  3005. avio_wb32(pb, 0); /* reserved (current time) */
  3006. avio_wb32(pb, max_track_id + 1); /* Next track id */
  3007. return 0x6c;
  3008. }
  3009. static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
  3010. AVFormatContext *s)
  3011. {
  3012. avio_wb32(pb, 33); /* size */
  3013. ffio_wfourcc(pb, "hdlr");
  3014. avio_wb32(pb, 0);
  3015. avio_wb32(pb, 0);
  3016. ffio_wfourcc(pb, "mdir");
  3017. ffio_wfourcc(pb, "appl");
  3018. avio_wb32(pb, 0);
  3019. avio_wb32(pb, 0);
  3020. avio_w8(pb, 0);
  3021. return 33;
  3022. }
  3023. /* helper function to write a data tag with the specified string as data */
  3024. static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
  3025. {
  3026. if (long_style) {
  3027. int size = 16 + strlen(data);
  3028. avio_wb32(pb, size); /* size */
  3029. ffio_wfourcc(pb, "data");
  3030. avio_wb32(pb, 1);
  3031. avio_wb32(pb, 0);
  3032. avio_write(pb, data, strlen(data));
  3033. return size;
  3034. } else {
  3035. if (!lang)
  3036. lang = ff_mov_iso639_to_lang("und", 1);
  3037. avio_wb16(pb, strlen(data)); /* string length */
  3038. avio_wb16(pb, lang);
  3039. avio_write(pb, data, strlen(data));
  3040. return strlen(data) + 4;
  3041. }
  3042. }
  3043. static int mov_write_string_tag(AVIOContext *pb, const char *name,
  3044. const char *value, int lang, int long_style)
  3045. {
  3046. int size = 0;
  3047. if (value && value[0]) {
  3048. int64_t pos = avio_tell(pb);
  3049. avio_wb32(pb, 0); /* size */
  3050. ffio_wfourcc(pb, name);
  3051. mov_write_string_data_tag(pb, value, lang, long_style);
  3052. size = update_size(pb, pos);
  3053. }
  3054. return size;
  3055. }
  3056. static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
  3057. const char *tag, int *lang)
  3058. {
  3059. int l, len, len2;
  3060. AVDictionaryEntry *t, *t2 = NULL;
  3061. char tag2[16];
  3062. *lang = 0;
  3063. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  3064. return NULL;
  3065. len = strlen(t->key);
  3066. snprintf(tag2, sizeof(tag2), "%s-", tag);
  3067. while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
  3068. len2 = strlen(t2->key);
  3069. if (len2 == len + 4 && !strcmp(t->value, t2->value)
  3070. && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
  3071. *lang = l;
  3072. return t;
  3073. }
  3074. }
  3075. return t;
  3076. }
  3077. static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
  3078. const char *name, const char *tag,
  3079. int long_style)
  3080. {
  3081. int lang;
  3082. AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
  3083. if (!t)
  3084. return 0;
  3085. return mov_write_string_tag(pb, name, t->value, lang, long_style);
  3086. }
  3087. /* iTunes bpm number */
  3088. static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
  3089. {
  3090. AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
  3091. int size = 0, tmpo = t ? atoi(t->value) : 0;
  3092. if (tmpo) {
  3093. size = 26;
  3094. avio_wb32(pb, size);
  3095. ffio_wfourcc(pb, "tmpo");
  3096. avio_wb32(pb, size-8); /* size */
  3097. ffio_wfourcc(pb, "data");
  3098. avio_wb32(pb, 0x15); //type specifier
  3099. avio_wb32(pb, 0);
  3100. avio_wb16(pb, tmpo); // data
  3101. }
  3102. return size;
  3103. }
  3104. /* 3GPP TS 26.244 */
  3105. static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
  3106. {
  3107. int lang;
  3108. int64_t pos = avio_tell(pb);
  3109. double latitude, longitude, altitude;
  3110. int32_t latitude_fix, longitude_fix, altitude_fix;
  3111. AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
  3112. const char *ptr, *place = "";
  3113. char *end;
  3114. static const char *astronomical_body = "earth";
  3115. if (!t)
  3116. return 0;
  3117. ptr = t->value;
  3118. longitude = strtod(ptr, &end);
  3119. if (end == ptr) {
  3120. av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
  3121. return 0;
  3122. }
  3123. ptr = end;
  3124. latitude = strtod(ptr, &end);
  3125. if (end == ptr) {
  3126. av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
  3127. return 0;
  3128. }
  3129. ptr = end;
  3130. altitude = strtod(ptr, &end);
  3131. /* If no altitude was present, the default 0 should be fine */
  3132. if (*end == '/')
  3133. place = end + 1;
  3134. latitude_fix = (int32_t) ((1 << 16) * latitude);
  3135. longitude_fix = (int32_t) ((1 << 16) * longitude);
  3136. altitude_fix = (int32_t) ((1 << 16) * altitude);
  3137. avio_wb32(pb, 0); /* size */
  3138. ffio_wfourcc(pb, "loci"); /* type */
  3139. avio_wb32(pb, 0); /* version + flags */
  3140. avio_wb16(pb, lang);
  3141. avio_write(pb, place, strlen(place) + 1);
  3142. avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
  3143. avio_wb32(pb, latitude_fix);
  3144. avio_wb32(pb, longitude_fix);
  3145. avio_wb32(pb, altitude_fix);
  3146. avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
  3147. avio_w8(pb, 0); /* additional notes, null terminated string */
  3148. return update_size(pb, pos);
  3149. }
  3150. /* iTunes track or disc number */
  3151. static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
  3152. AVFormatContext *s, int disc)
  3153. {
  3154. AVDictionaryEntry *t = av_dict_get(s->metadata,
  3155. disc ? "disc" : "track",
  3156. NULL, 0);
  3157. int size = 0, track = t ? atoi(t->value) : 0;
  3158. if (track) {
  3159. int tracks = 0;
  3160. char *slash = strchr(t->value, '/');
  3161. if (slash)
  3162. tracks = atoi(slash + 1);
  3163. avio_wb32(pb, 32); /* size */
  3164. ffio_wfourcc(pb, disc ? "disk" : "trkn");
  3165. avio_wb32(pb, 24); /* size */
  3166. ffio_wfourcc(pb, "data");
  3167. avio_wb32(pb, 0); // 8 bytes empty
  3168. avio_wb32(pb, 0);
  3169. avio_wb16(pb, 0); // empty
  3170. avio_wb16(pb, track); // track / disc number
  3171. avio_wb16(pb, tracks); // total track / disc number
  3172. avio_wb16(pb, 0); // empty
  3173. size = 32;
  3174. }
  3175. return size;
  3176. }
  3177. static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
  3178. const char *name, const char *tag,
  3179. int len)
  3180. {
  3181. AVDictionaryEntry *t = NULL;
  3182. uint8_t num;
  3183. int size = 24 + len;
  3184. if (len != 1 && len != 4)
  3185. return -1;
  3186. if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
  3187. return 0;
  3188. num = atoi(t->value);
  3189. avio_wb32(pb, size);
  3190. ffio_wfourcc(pb, name);
  3191. avio_wb32(pb, size - 8);
  3192. ffio_wfourcc(pb, "data");
  3193. avio_wb32(pb, 0x15);
  3194. avio_wb32(pb, 0);
  3195. if (len==4) avio_wb32(pb, num);
  3196. else avio_w8 (pb, num);
  3197. return size;
  3198. }
  3199. static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
  3200. {
  3201. MOVMuxContext *mov = s->priv_data;
  3202. int64_t pos = 0;
  3203. int i;
  3204. for (i = 0; i < s->nb_streams; i++) {
  3205. MOVTrack *trk = &mov->tracks[i];
  3206. if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
  3207. continue;
  3208. if (!pos) {
  3209. pos = avio_tell(pb);
  3210. avio_wb32(pb, 0);
  3211. ffio_wfourcc(pb, "covr");
  3212. }
  3213. avio_wb32(pb, 16 + trk->cover_image.size);
  3214. ffio_wfourcc(pb, "data");
  3215. avio_wb32(pb, trk->tag);
  3216. avio_wb32(pb , 0);
  3217. avio_write(pb, trk->cover_image.data, trk->cover_image.size);
  3218. }
  3219. return pos ? update_size(pb, pos) : 0;
  3220. }
  3221. /* iTunes meta data list */
  3222. static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
  3223. AVFormatContext *s)
  3224. {
  3225. int64_t pos = avio_tell(pb);
  3226. avio_wb32(pb, 0); /* size */
  3227. ffio_wfourcc(pb, "ilst");
  3228. mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
  3229. mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
  3230. mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
  3231. mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
  3232. mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
  3233. mov_write_string_metadata(s, pb, "\251day", "date" , 1);
  3234. if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
  3235. if (!(s->flags & AVFMT_FLAG_BITEXACT))
  3236. mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
  3237. }
  3238. mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
  3239. mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
  3240. mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
  3241. mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
  3242. mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
  3243. mov_write_string_metadata(s, pb, "desc", "description",1);
  3244. mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
  3245. mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
  3246. mov_write_string_metadata(s, pb, "tven", "episode_id",1);
  3247. mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
  3248. mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
  3249. mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
  3250. mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
  3251. mov_write_int8_metadata (s, pb, "stik", "media_type",1);
  3252. mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
  3253. mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
  3254. mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
  3255. mov_write_covr(pb, s);
  3256. mov_write_trkn_tag(pb, mov, s, 0); // track number
  3257. mov_write_trkn_tag(pb, mov, s, 1); // disc number
  3258. mov_write_tmpo_tag(pb, s);
  3259. return update_size(pb, pos);
  3260. }
  3261. static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
  3262. AVFormatContext *s)
  3263. {
  3264. avio_wb32(pb, 33); /* size */
  3265. ffio_wfourcc(pb, "hdlr");
  3266. avio_wb32(pb, 0);
  3267. avio_wb32(pb, 0);
  3268. ffio_wfourcc(pb, "mdta");
  3269. avio_wb32(pb, 0);
  3270. avio_wb32(pb, 0);
  3271. avio_wb32(pb, 0);
  3272. avio_w8(pb, 0);
  3273. return 33;
  3274. }
  3275. static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
  3276. AVFormatContext *s)
  3277. {
  3278. AVDictionaryEntry *t = NULL;
  3279. int64_t pos = avio_tell(pb);
  3280. int64_t curpos, entry_pos;
  3281. int count = 0;
  3282. avio_wb32(pb, 0); /* size */
  3283. ffio_wfourcc(pb, "keys");
  3284. avio_wb32(pb, 0);
  3285. entry_pos = avio_tell(pb);
  3286. avio_wb32(pb, 0); /* entry count */
  3287. while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
  3288. avio_wb32(pb, strlen(t->key) + 8);
  3289. ffio_wfourcc(pb, "mdta");
  3290. avio_write(pb, t->key, strlen(t->key));
  3291. count += 1;
  3292. }
  3293. curpos = avio_tell(pb);
  3294. avio_seek(pb, entry_pos, SEEK_SET);
  3295. avio_wb32(pb, count); // rewrite entry count
  3296. avio_seek(pb, curpos, SEEK_SET);
  3297. return update_size(pb, pos);
  3298. }
  3299. static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
  3300. AVFormatContext *s)
  3301. {
  3302. AVDictionaryEntry *t = NULL;
  3303. int64_t pos = avio_tell(pb);
  3304. int count = 1; /* keys are 1-index based */
  3305. avio_wb32(pb, 0); /* size */
  3306. ffio_wfourcc(pb, "ilst");
  3307. while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
  3308. int64_t entry_pos = avio_tell(pb);
  3309. avio_wb32(pb, 0); /* size */
  3310. avio_wb32(pb, count); /* key */
  3311. mov_write_string_data_tag(pb, t->value, 0, 1);
  3312. update_size(pb, entry_pos);
  3313. count += 1;
  3314. }
  3315. return update_size(pb, pos);
  3316. }
  3317. /* meta data tags */
  3318. static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
  3319. AVFormatContext *s)
  3320. {
  3321. int size = 0;
  3322. int64_t pos = avio_tell(pb);
  3323. avio_wb32(pb, 0); /* size */
  3324. ffio_wfourcc(pb, "meta");
  3325. avio_wb32(pb, 0);
  3326. if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
  3327. mov_write_mdta_hdlr_tag(pb, mov, s);
  3328. mov_write_mdta_keys_tag(pb, mov, s);
  3329. mov_write_mdta_ilst_tag(pb, mov, s);
  3330. }
  3331. else {
  3332. /* iTunes metadata tag */
  3333. mov_write_itunes_hdlr_tag(pb, mov, s);
  3334. mov_write_ilst_tag(pb, mov, s);
  3335. }
  3336. size = update_size(pb, pos);
  3337. return size;
  3338. }
  3339. static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
  3340. const char *name, const char *key)
  3341. {
  3342. int len;
  3343. AVDictionaryEntry *t;
  3344. if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
  3345. return 0;
  3346. len = strlen(t->value);
  3347. if (len > 0) {
  3348. int size = len + 8;
  3349. avio_wb32(pb, size);
  3350. ffio_wfourcc(pb, name);
  3351. avio_write(pb, t->value, len);
  3352. return size;
  3353. }
  3354. return 0;
  3355. }
  3356. static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
  3357. {
  3358. int val;
  3359. while (*b) {
  3360. GET_UTF8(val, *b++, return -1;)
  3361. avio_wb16(pb, val);
  3362. }
  3363. avio_wb16(pb, 0x00);
  3364. return 0;
  3365. }
  3366. static uint16_t language_code(const char *str)
  3367. {
  3368. return (((str[0] - 0x60) & 0x1F) << 10) +
  3369. (((str[1] - 0x60) & 0x1F) << 5) +
  3370. (( str[2] - 0x60) & 0x1F);
  3371. }
  3372. static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
  3373. const char *tag, const char *str)
  3374. {
  3375. int64_t pos = avio_tell(pb);
  3376. AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
  3377. if (!t || !utf8len(t->value))
  3378. return 0;
  3379. avio_wb32(pb, 0); /* size */
  3380. ffio_wfourcc(pb, tag); /* type */
  3381. avio_wb32(pb, 0); /* version + flags */
  3382. if (!strcmp(tag, "yrrc"))
  3383. avio_wb16(pb, atoi(t->value));
  3384. else {
  3385. avio_wb16(pb, language_code("eng")); /* language */
  3386. avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
  3387. if (!strcmp(tag, "albm") &&
  3388. (t = av_dict_get(s->metadata, "track", NULL, 0)))
  3389. avio_w8(pb, atoi(t->value));
  3390. }
  3391. return update_size(pb, pos);
  3392. }
  3393. static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
  3394. {
  3395. int64_t pos = avio_tell(pb);
  3396. int i, nb_chapters = FFMIN(s->nb_chapters, 255);
  3397. avio_wb32(pb, 0); // size
  3398. ffio_wfourcc(pb, "chpl");
  3399. avio_wb32(pb, 0x01000000); // version + flags
  3400. avio_wb32(pb, 0); // unknown
  3401. avio_w8(pb, nb_chapters);
  3402. for (i = 0; i < nb_chapters; i++) {
  3403. AVChapter *c = s->chapters[i];
  3404. AVDictionaryEntry *t;
  3405. avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
  3406. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  3407. int len = FFMIN(strlen(t->value), 255);
  3408. avio_w8(pb, len);
  3409. avio_write(pb, t->value, len);
  3410. } else
  3411. avio_w8(pb, 0);
  3412. }
  3413. return update_size(pb, pos);
  3414. }
  3415. static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
  3416. AVFormatContext *s)
  3417. {
  3418. AVIOContext *pb_buf;
  3419. int ret, size;
  3420. uint8_t *buf;
  3421. ret = avio_open_dyn_buf(&pb_buf);
  3422. if (ret < 0)
  3423. return ret;
  3424. if (mov->mode & MODE_3GP) {
  3425. mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
  3426. mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
  3427. mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
  3428. mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
  3429. mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
  3430. mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
  3431. mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
  3432. mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
  3433. mov_write_loci_tag(s, pb_buf);
  3434. } 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
  3435. mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
  3436. mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
  3437. mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
  3438. mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
  3439. mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
  3440. mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
  3441. // currently ignored by mov.c
  3442. mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
  3443. // add support for libquicktime, this atom is also actually read by mov.c
  3444. mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
  3445. mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
  3446. mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
  3447. mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
  3448. mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
  3449. mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
  3450. mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
  3451. mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
  3452. } else {
  3453. /* iTunes meta data */
  3454. mov_write_meta_tag(pb_buf, mov, s);
  3455. mov_write_loci_tag(s, pb_buf);
  3456. }
  3457. if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
  3458. mov_write_chpl_tag(pb_buf, s);
  3459. if ((size = avio_get_dyn_buf(pb_buf, &buf)) > 0) {
  3460. avio_wb32(pb, size + 8);
  3461. ffio_wfourcc(pb, "udta");
  3462. avio_write(pb, buf, size);
  3463. }
  3464. ffio_free_dyn_buf(&pb_buf);
  3465. return 0;
  3466. }
  3467. static void mov_write_psp_udta_tag(AVIOContext *pb,
  3468. const char *str, const char *lang, int type)
  3469. {
  3470. int len = utf8len(str) + 1;
  3471. if (len <= 0)
  3472. return;
  3473. avio_wb16(pb, len * 2 + 10); /* size */
  3474. avio_wb32(pb, type); /* type */
  3475. avio_wb16(pb, language_code(lang)); /* language */
  3476. avio_wb16(pb, 0x01); /* ? */
  3477. ascii_to_wc(pb, str);
  3478. }
  3479. static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
  3480. {
  3481. AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
  3482. int64_t pos, pos2;
  3483. if (title) {
  3484. pos = avio_tell(pb);
  3485. avio_wb32(pb, 0); /* size placeholder*/
  3486. ffio_wfourcc(pb, "uuid");
  3487. ffio_wfourcc(pb, "USMT");
  3488. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  3489. avio_wb32(pb, 0xbb88695c);
  3490. avio_wb32(pb, 0xfac9c740);
  3491. pos2 = avio_tell(pb);
  3492. avio_wb32(pb, 0); /* size placeholder*/
  3493. ffio_wfourcc(pb, "MTDT");
  3494. avio_wb16(pb, 4);
  3495. // ?
  3496. avio_wb16(pb, 0x0C); /* size */
  3497. avio_wb32(pb, 0x0B); /* type */
  3498. avio_wb16(pb, language_code("und")); /* language */
  3499. avio_wb16(pb, 0x0); /* ? */
  3500. avio_wb16(pb, 0x021C); /* data */
  3501. if (!(s->flags & AVFMT_FLAG_BITEXACT))
  3502. mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
  3503. mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
  3504. mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
  3505. update_size(pb, pos2);
  3506. return update_size(pb, pos);
  3507. }
  3508. return 0;
  3509. }
  3510. static void build_chunks(MOVTrack *trk)
  3511. {
  3512. int i;
  3513. MOVIentry *chunk = &trk->cluster[0];
  3514. uint64_t chunkSize = chunk->size;
  3515. chunk->chunkNum = 1;
  3516. if (trk->chunkCount)
  3517. return;
  3518. trk->chunkCount = 1;
  3519. for (i = 1; i<trk->entry; i++){
  3520. if (chunk->pos + chunkSize == trk->cluster[i].pos &&
  3521. chunkSize + trk->cluster[i].size < (1<<20)){
  3522. chunkSize += trk->cluster[i].size;
  3523. chunk->samples_in_chunk += trk->cluster[i].entries;
  3524. } else {
  3525. trk->cluster[i].chunkNum = chunk->chunkNum+1;
  3526. chunk=&trk->cluster[i];
  3527. chunkSize = chunk->size;
  3528. trk->chunkCount++;
  3529. }
  3530. }
  3531. }
  3532. /**
  3533. * Assign track ids. If option "use_stream_ids_as_track_ids" is set,
  3534. * the stream ids are used as track ids.
  3535. *
  3536. * This assumes mov->tracks and s->streams are in the same order and
  3537. * there are no gaps in either of them (so mov->tracks[n] refers to
  3538. * s->streams[n]).
  3539. *
  3540. * As an exception, there can be more entries in
  3541. * s->streams than in mov->tracks, in which case new track ids are
  3542. * generated (starting after the largest found stream id).
  3543. */
  3544. static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
  3545. {
  3546. int i;
  3547. if (mov->track_ids_ok)
  3548. return 0;
  3549. if (mov->use_stream_ids_as_track_ids) {
  3550. int next_generated_track_id = 0;
  3551. for (i = 0; i < s->nb_streams; i++) {
  3552. if (s->streams[i]->id > next_generated_track_id)
  3553. next_generated_track_id = s->streams[i]->id;
  3554. }
  3555. for (i = 0; i < mov->nb_streams; i++) {
  3556. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3557. continue;
  3558. mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
  3559. }
  3560. } else {
  3561. for (i = 0; i < mov->nb_streams; i++) {
  3562. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3563. continue;
  3564. mov->tracks[i].track_id = i + 1;
  3565. }
  3566. }
  3567. mov->track_ids_ok = 1;
  3568. return 0;
  3569. }
  3570. static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
  3571. AVFormatContext *s)
  3572. {
  3573. int i;
  3574. int64_t pos = avio_tell(pb);
  3575. avio_wb32(pb, 0); /* size placeholder*/
  3576. ffio_wfourcc(pb, "moov");
  3577. mov_setup_track_ids(mov, s);
  3578. for (i = 0; i < mov->nb_streams; i++) {
  3579. if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
  3580. continue;
  3581. mov->tracks[i].time = mov->time;
  3582. if (mov->tracks[i].entry)
  3583. build_chunks(&mov->tracks[i]);
  3584. }
  3585. if (mov->chapter_track)
  3586. for (i = 0; i < s->nb_streams; i++) {
  3587. mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
  3588. mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
  3589. }
  3590. for (i = 0; i < mov->nb_streams; i++) {
  3591. MOVTrack *track = &mov->tracks[i];
  3592. if (track->tag == MKTAG('r','t','p',' ')) {
  3593. track->tref_tag = MKTAG('h','i','n','t');
  3594. track->tref_id = mov->tracks[track->src_track].track_id;
  3595. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  3596. int * fallback, size;
  3597. fallback = (int*)av_stream_get_side_data(track->st,
  3598. AV_PKT_DATA_FALLBACK_TRACK,
  3599. &size);
  3600. if (fallback != NULL && size == sizeof(int)) {
  3601. if (*fallback >= 0 && *fallback < mov->nb_streams) {
  3602. track->tref_tag = MKTAG('f','a','l','l');
  3603. track->tref_id = mov->tracks[*fallback].track_id;
  3604. }
  3605. }
  3606. }
  3607. }
  3608. for (i = 0; i < mov->nb_streams; i++) {
  3609. if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
  3610. int src_trk = mov->tracks[i].src_track;
  3611. mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
  3612. mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
  3613. //src_trk may have a different timescale than the tmcd track
  3614. mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
  3615. mov->tracks[i].timescale,
  3616. mov->tracks[src_trk].timescale);
  3617. }
  3618. }
  3619. mov_write_mvhd_tag(pb, mov);
  3620. if (mov->mode != MODE_MOV && !mov->iods_skip)
  3621. mov_write_iods_tag(pb, mov);
  3622. for (i = 0; i < mov->nb_streams; i++) {
  3623. if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
  3624. int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
  3625. if (ret < 0)
  3626. return ret;
  3627. }
  3628. }
  3629. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  3630. mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
  3631. if (mov->mode == MODE_PSP)
  3632. mov_write_uuidusmt_tag(pb, s);
  3633. else
  3634. mov_write_udta_tag(pb, mov, s);
  3635. return update_size(pb, pos);
  3636. }
  3637. static void param_write_int(AVIOContext *pb, const char *name, int value)
  3638. {
  3639. avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
  3640. }
  3641. static void param_write_string(AVIOContext *pb, const char *name, const char *value)
  3642. {
  3643. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
  3644. }
  3645. static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
  3646. {
  3647. char buf[150];
  3648. len = FFMIN(sizeof(buf) / 2 - 1, len);
  3649. ff_data_to_hex(buf, value, len, 0);
  3650. buf[2 * len] = '\0';
  3651. avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
  3652. }
  3653. static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
  3654. {
  3655. int64_t pos = avio_tell(pb);
  3656. int i;
  3657. int64_t manifest_bit_rate = 0;
  3658. AVCPBProperties *props = NULL;
  3659. static const uint8_t uuid[] = {
  3660. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  3661. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  3662. };
  3663. avio_wb32(pb, 0);
  3664. ffio_wfourcc(pb, "uuid");
  3665. avio_write(pb, uuid, sizeof(uuid));
  3666. avio_wb32(pb, 0);
  3667. avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
  3668. avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
  3669. avio_printf(pb, "<head>\n");
  3670. if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
  3671. avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
  3672. LIBAVFORMAT_IDENT);
  3673. avio_printf(pb, "</head>\n");
  3674. avio_printf(pb, "<body>\n");
  3675. avio_printf(pb, "<switch>\n");
  3676. mov_setup_track_ids(mov, s);
  3677. for (i = 0; i < mov->nb_streams; i++) {
  3678. MOVTrack *track = &mov->tracks[i];
  3679. const char *type;
  3680. int track_id = track->track_id;
  3681. char track_name_buf[32] = { 0 };
  3682. AVStream *st = track->st;
  3683. AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
  3684. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
  3685. type = "video";
  3686. } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
  3687. type = "audio";
  3688. } else {
  3689. continue;
  3690. }
  3691. props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
  3692. if (track->par->bit_rate) {
  3693. manifest_bit_rate = track->par->bit_rate;
  3694. } else if (props) {
  3695. manifest_bit_rate = props->max_bitrate;
  3696. }
  3697. avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
  3698. manifest_bit_rate);
  3699. param_write_int(pb, "systemBitrate", manifest_bit_rate);
  3700. param_write_int(pb, "trackID", track_id);
  3701. param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
  3702. /* Build track name piece by piece: */
  3703. /* 1. track type */
  3704. av_strlcat(track_name_buf, type, sizeof(track_name_buf));
  3705. /* 2. track language, if available */
  3706. if (lang)
  3707. av_strlcatf(track_name_buf, sizeof(track_name_buf),
  3708. "_%s", lang->value);
  3709. /* 3. special type suffix */
  3710. /* "_cc" = closed captions, "_ad" = audio_description */
  3711. if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
  3712. av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
  3713. else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
  3714. av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
  3715. param_write_string(pb, "trackName", track_name_buf);
  3716. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  3717. if (track->par->codec_id == AV_CODEC_ID_H264) {
  3718. uint8_t *ptr;
  3719. int size = track->par->extradata_size;
  3720. if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
  3721. &size)) {
  3722. param_write_hex(pb, "CodecPrivateData",
  3723. ptr ? ptr : track->par->extradata,
  3724. size);
  3725. av_free(ptr);
  3726. }
  3727. param_write_string(pb, "FourCC", "H264");
  3728. } else if (track->par->codec_id == AV_CODEC_ID_VC1) {
  3729. param_write_string(pb, "FourCC", "WVC1");
  3730. param_write_hex(pb, "CodecPrivateData", track->par->extradata,
  3731. track->par->extradata_size);
  3732. }
  3733. param_write_int(pb, "MaxWidth", track->par->width);
  3734. param_write_int(pb, "MaxHeight", track->par->height);
  3735. param_write_int(pb, "DisplayWidth", track->par->width);
  3736. param_write_int(pb, "DisplayHeight", track->par->height);
  3737. } else {
  3738. if (track->par->codec_id == AV_CODEC_ID_AAC) {
  3739. switch (track->par->profile)
  3740. {
  3741. case FF_PROFILE_AAC_HE_V2:
  3742. param_write_string(pb, "FourCC", "AACP");
  3743. break;
  3744. case FF_PROFILE_AAC_HE:
  3745. param_write_string(pb, "FourCC", "AACH");
  3746. break;
  3747. default:
  3748. param_write_string(pb, "FourCC", "AACL");
  3749. }
  3750. } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
  3751. param_write_string(pb, "FourCC", "WMAP");
  3752. }
  3753. param_write_hex(pb, "CodecPrivateData", track->par->extradata,
  3754. track->par->extradata_size);
  3755. param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
  3756. track->par->codec_id));
  3757. param_write_int(pb, "Channels", track->par->channels);
  3758. param_write_int(pb, "SamplingRate", track->par->sample_rate);
  3759. param_write_int(pb, "BitsPerSample", 16);
  3760. param_write_int(pb, "PacketSize", track->par->block_align ?
  3761. track->par->block_align : 4);
  3762. }
  3763. avio_printf(pb, "</%s>\n", type);
  3764. }
  3765. avio_printf(pb, "</switch>\n");
  3766. avio_printf(pb, "</body>\n");
  3767. avio_printf(pb, "</smil>\n");
  3768. return update_size(pb, pos);
  3769. }
  3770. static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
  3771. {
  3772. avio_wb32(pb, 16);
  3773. ffio_wfourcc(pb, "mfhd");
  3774. avio_wb32(pb, 0);
  3775. avio_wb32(pb, mov->fragments);
  3776. return 0;
  3777. }
  3778. static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
  3779. {
  3780. return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
  3781. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
  3782. }
  3783. static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
  3784. MOVTrack *track, int64_t moof_offset)
  3785. {
  3786. int64_t pos = avio_tell(pb);
  3787. uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  3788. MOV_TFHD_BASE_DATA_OFFSET;
  3789. if (!track->entry) {
  3790. flags |= MOV_TFHD_DURATION_IS_EMPTY;
  3791. } else {
  3792. flags |= MOV_TFHD_DEFAULT_FLAGS;
  3793. }
  3794. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
  3795. flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
  3796. if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
  3797. flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
  3798. flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
  3799. }
  3800. /* CMAF requires all values to be explicit in tfhd atoms */
  3801. if (mov->flags & FF_MOV_FLAG_CMAF)
  3802. flags |= MOV_TFHD_STSD_ID;
  3803. /* Don't set a default sample size, the silverlight player refuses
  3804. * to play files with that set. Don't set a default sample duration,
  3805. * WMP freaks out if it is set. Don't set a base data offset, PIFF
  3806. * file format says it MUST NOT be set. */
  3807. if (track->mode == MODE_ISM)
  3808. flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
  3809. MOV_TFHD_BASE_DATA_OFFSET | MOV_TFHD_STSD_ID);
  3810. avio_wb32(pb, 0); /* size placeholder */
  3811. ffio_wfourcc(pb, "tfhd");
  3812. avio_w8(pb, 0); /* version */
  3813. avio_wb24(pb, flags);
  3814. avio_wb32(pb, track->track_id); /* track-id */
  3815. if (flags & MOV_TFHD_BASE_DATA_OFFSET)
  3816. avio_wb64(pb, moof_offset);
  3817. if (flags & MOV_TFHD_STSD_ID) {
  3818. avio_wb32(pb, 1);
  3819. }
  3820. if (flags & MOV_TFHD_DEFAULT_DURATION) {
  3821. track->default_duration = get_cluster_duration(track, 0);
  3822. avio_wb32(pb, track->default_duration);
  3823. }
  3824. if (flags & MOV_TFHD_DEFAULT_SIZE) {
  3825. track->default_size = track->entry ? track->cluster[0].size : 1;
  3826. avio_wb32(pb, track->default_size);
  3827. } else
  3828. track->default_size = -1;
  3829. if (flags & MOV_TFHD_DEFAULT_FLAGS) {
  3830. /* Set the default flags based on the second sample, if available.
  3831. * If the first sample is different, that can be signaled via a separate field. */
  3832. if (track->entry > 1)
  3833. track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
  3834. else
  3835. track->default_sample_flags =
  3836. track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
  3837. (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
  3838. MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
  3839. avio_wb32(pb, track->default_sample_flags);
  3840. }
  3841. return update_size(pb, pos);
  3842. }
  3843. static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
  3844. MOVTrack *track, int moof_size,
  3845. int first, int end)
  3846. {
  3847. int64_t pos = avio_tell(pb);
  3848. uint32_t flags = MOV_TRUN_DATA_OFFSET;
  3849. int i;
  3850. for (i = first; i < end; i++) {
  3851. if (get_cluster_duration(track, i) != track->default_duration)
  3852. flags |= MOV_TRUN_SAMPLE_DURATION;
  3853. if (track->cluster[i].size != track->default_size)
  3854. flags |= MOV_TRUN_SAMPLE_SIZE;
  3855. if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
  3856. flags |= MOV_TRUN_SAMPLE_FLAGS;
  3857. }
  3858. if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
  3859. get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
  3860. flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
  3861. if (track->flags & MOV_TRACK_CTTS)
  3862. flags |= MOV_TRUN_SAMPLE_CTS;
  3863. avio_wb32(pb, 0); /* size placeholder */
  3864. ffio_wfourcc(pb, "trun");
  3865. if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
  3866. avio_w8(pb, 1); /* version */
  3867. else
  3868. avio_w8(pb, 0); /* version */
  3869. avio_wb24(pb, flags);
  3870. avio_wb32(pb, end - first); /* sample count */
  3871. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
  3872. !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
  3873. !mov->first_trun)
  3874. avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
  3875. else
  3876. avio_wb32(pb, moof_size + 8 + track->data_offset +
  3877. track->cluster[first].pos); /* data offset */
  3878. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
  3879. avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
  3880. for (i = first; i < end; i++) {
  3881. if (flags & MOV_TRUN_SAMPLE_DURATION)
  3882. avio_wb32(pb, get_cluster_duration(track, i));
  3883. if (flags & MOV_TRUN_SAMPLE_SIZE)
  3884. avio_wb32(pb, track->cluster[i].size);
  3885. if (flags & MOV_TRUN_SAMPLE_FLAGS)
  3886. avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
  3887. if (flags & MOV_TRUN_SAMPLE_CTS)
  3888. avio_wb32(pb, track->cluster[i].cts);
  3889. }
  3890. mov->first_trun = 0;
  3891. return update_size(pb, pos);
  3892. }
  3893. static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
  3894. {
  3895. int64_t pos = avio_tell(pb);
  3896. static const uint8_t uuid[] = {
  3897. 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
  3898. 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
  3899. };
  3900. avio_wb32(pb, 0); /* size placeholder */
  3901. ffio_wfourcc(pb, "uuid");
  3902. avio_write(pb, uuid, sizeof(uuid));
  3903. avio_w8(pb, 1);
  3904. avio_wb24(pb, 0);
  3905. avio_wb64(pb, track->start_dts + track->frag_start +
  3906. track->cluster[0].cts);
  3907. avio_wb64(pb, track->end_pts -
  3908. (track->cluster[0].dts + track->cluster[0].cts));
  3909. return update_size(pb, pos);
  3910. }
  3911. static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
  3912. MOVTrack *track, int entry)
  3913. {
  3914. int n = track->nb_frag_info - 1 - entry, i;
  3915. int size = 8 + 16 + 4 + 1 + 16*n;
  3916. static const uint8_t uuid[] = {
  3917. 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
  3918. 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
  3919. };
  3920. if (entry < 0)
  3921. return 0;
  3922. avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
  3923. avio_wb32(pb, size);
  3924. ffio_wfourcc(pb, "uuid");
  3925. avio_write(pb, uuid, sizeof(uuid));
  3926. avio_w8(pb, 1);
  3927. avio_wb24(pb, 0);
  3928. avio_w8(pb, n);
  3929. for (i = 0; i < n; i++) {
  3930. int index = entry + 1 + i;
  3931. avio_wb64(pb, track->frag_info[index].time);
  3932. avio_wb64(pb, track->frag_info[index].duration);
  3933. }
  3934. if (n < mov->ism_lookahead) {
  3935. int free_size = 16 * (mov->ism_lookahead - n);
  3936. avio_wb32(pb, free_size);
  3937. ffio_wfourcc(pb, "free");
  3938. ffio_fill(pb, 0, free_size - 8);
  3939. }
  3940. return 0;
  3941. }
  3942. static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
  3943. MOVTrack *track)
  3944. {
  3945. int64_t pos = avio_tell(pb);
  3946. int i;
  3947. for (i = 0; i < mov->ism_lookahead; i++) {
  3948. /* Update the tfrf tag for the last ism_lookahead fragments,
  3949. * nb_frag_info - 1 is the next fragment to be written. */
  3950. mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
  3951. }
  3952. avio_seek(pb, pos, SEEK_SET);
  3953. return 0;
  3954. }
  3955. static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
  3956. int size)
  3957. {
  3958. int i;
  3959. for (i = 0; i < mov->nb_streams; i++) {
  3960. MOVTrack *track = &mov->tracks[i];
  3961. MOVFragmentInfo *info;
  3962. if ((tracks >= 0 && i != tracks) || !track->entry)
  3963. continue;
  3964. track->nb_frag_info++;
  3965. if (track->nb_frag_info >= track->frag_info_capacity) {
  3966. unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
  3967. if (av_reallocp_array(&track->frag_info,
  3968. new_capacity,
  3969. sizeof(*track->frag_info)))
  3970. return AVERROR(ENOMEM);
  3971. track->frag_info_capacity = new_capacity;
  3972. }
  3973. info = &track->frag_info[track->nb_frag_info - 1];
  3974. info->offset = avio_tell(pb);
  3975. info->size = size;
  3976. // Try to recreate the original pts for the first packet
  3977. // from the fields we have stored
  3978. info->time = track->start_dts + track->frag_start +
  3979. track->cluster[0].cts;
  3980. info->duration = track->end_pts -
  3981. (track->cluster[0].dts + track->cluster[0].cts);
  3982. // If the pts is less than zero, we will have trimmed
  3983. // away parts of the media track using an edit list,
  3984. // and the corresponding start presentation time is zero.
  3985. if (info->time < 0) {
  3986. info->duration += info->time;
  3987. info->time = 0;
  3988. }
  3989. info->tfrf_offset = 0;
  3990. mov_write_tfrf_tags(pb, mov, track);
  3991. }
  3992. return 0;
  3993. }
  3994. static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
  3995. {
  3996. int i;
  3997. for (i = 0; i < mov->nb_streams; i++) {
  3998. MOVTrack *track = &mov->tracks[i];
  3999. if ((tracks >= 0 && i != tracks) || !track->entry)
  4000. continue;
  4001. if (track->nb_frag_info > max) {
  4002. memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
  4003. track->nb_frag_info = max;
  4004. }
  4005. }
  4006. }
  4007. static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
  4008. {
  4009. int64_t pos = avio_tell(pb);
  4010. avio_wb32(pb, 0); /* size */
  4011. ffio_wfourcc(pb, "tfdt");
  4012. avio_w8(pb, 1); /* version */
  4013. avio_wb24(pb, 0);
  4014. avio_wb64(pb, track->frag_start);
  4015. return update_size(pb, pos);
  4016. }
  4017. static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
  4018. MOVTrack *track, int64_t moof_offset,
  4019. int moof_size)
  4020. {
  4021. int64_t pos = avio_tell(pb);
  4022. int i, start = 0;
  4023. avio_wb32(pb, 0); /* size placeholder */
  4024. ffio_wfourcc(pb, "traf");
  4025. mov_write_tfhd_tag(pb, mov, track, moof_offset);
  4026. if (mov->mode != MODE_ISM)
  4027. mov_write_tfdt_tag(pb, track);
  4028. for (i = 1; i < track->entry; i++) {
  4029. if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
  4030. mov_write_trun_tag(pb, mov, track, moof_size, start, i);
  4031. start = i;
  4032. }
  4033. }
  4034. mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
  4035. if (mov->mode == MODE_ISM) {
  4036. mov_write_tfxd_tag(pb, track);
  4037. if (mov->ism_lookahead) {
  4038. int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
  4039. if (track->nb_frag_info > 0) {
  4040. MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
  4041. if (!info->tfrf_offset)
  4042. info->tfrf_offset = avio_tell(pb);
  4043. }
  4044. avio_wb32(pb, 8 + size);
  4045. ffio_wfourcc(pb, "free");
  4046. for (i = 0; i < size; i++)
  4047. avio_w8(pb, 0);
  4048. }
  4049. }
  4050. return update_size(pb, pos);
  4051. }
  4052. static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
  4053. int tracks, int moof_size)
  4054. {
  4055. int64_t pos = avio_tell(pb);
  4056. int i;
  4057. avio_wb32(pb, 0); /* size placeholder */
  4058. ffio_wfourcc(pb, "moof");
  4059. mov->first_trun = 1;
  4060. mov_write_mfhd_tag(pb, mov);
  4061. for (i = 0; i < mov->nb_streams; i++) {
  4062. MOVTrack *track = &mov->tracks[i];
  4063. if (tracks >= 0 && i != tracks)
  4064. continue;
  4065. if (!track->entry)
  4066. continue;
  4067. mov_write_traf_tag(pb, mov, track, pos, moof_size);
  4068. }
  4069. return update_size(pb, pos);
  4070. }
  4071. static int mov_write_sidx_tag(AVIOContext *pb,
  4072. MOVTrack *track, int ref_size, int total_sidx_size)
  4073. {
  4074. int64_t pos = avio_tell(pb), offset_pos, end_pos;
  4075. int64_t presentation_time, duration, offset;
  4076. unsigned starts_with_SAP;
  4077. int i, entries;
  4078. if (track->entry) {
  4079. entries = 1;
  4080. presentation_time = track->start_dts + track->frag_start +
  4081. track->cluster[0].cts;
  4082. duration = track->end_pts -
  4083. (track->cluster[0].dts + track->cluster[0].cts);
  4084. starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
  4085. // pts<0 should be cut away using edts
  4086. if (presentation_time < 0) {
  4087. duration += presentation_time;
  4088. presentation_time = 0;
  4089. }
  4090. } else {
  4091. entries = track->nb_frag_info;
  4092. if (entries <= 0)
  4093. return 0;
  4094. presentation_time = track->frag_info[0].time;
  4095. }
  4096. avio_wb32(pb, 0); /* size */
  4097. ffio_wfourcc(pb, "sidx");
  4098. avio_w8(pb, 1); /* version */
  4099. avio_wb24(pb, 0);
  4100. avio_wb32(pb, track->track_id); /* reference_ID */
  4101. avio_wb32(pb, track->timescale); /* timescale */
  4102. avio_wb64(pb, presentation_time); /* earliest_presentation_time */
  4103. offset_pos = avio_tell(pb);
  4104. avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
  4105. avio_wb16(pb, 0); /* reserved */
  4106. avio_wb16(pb, entries); /* reference_count */
  4107. for (i = 0; i < entries; i++) {
  4108. if (!track->entry) {
  4109. if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
  4110. av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
  4111. }
  4112. duration = track->frag_info[i].duration;
  4113. ref_size = track->frag_info[i].size;
  4114. starts_with_SAP = 1;
  4115. }
  4116. avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
  4117. avio_wb32(pb, duration); /* subsegment_duration */
  4118. avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
  4119. }
  4120. end_pos = avio_tell(pb);
  4121. offset = pos + total_sidx_size - end_pos;
  4122. avio_seek(pb, offset_pos, SEEK_SET);
  4123. avio_wb64(pb, offset);
  4124. avio_seek(pb, end_pos, SEEK_SET);
  4125. return update_size(pb, pos);
  4126. }
  4127. static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
  4128. int tracks, int ref_size)
  4129. {
  4130. int i, round, ret;
  4131. AVIOContext *avio_buf;
  4132. int total_size = 0;
  4133. for (round = 0; round < 2; round++) {
  4134. // First run one round to calculate the total size of all
  4135. // sidx atoms.
  4136. // This would be much simpler if we'd only write one sidx
  4137. // atom, for the first track in the moof.
  4138. if (round == 0) {
  4139. if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
  4140. return ret;
  4141. } else {
  4142. avio_buf = pb;
  4143. }
  4144. for (i = 0; i < mov->nb_streams; i++) {
  4145. MOVTrack *track = &mov->tracks[i];
  4146. if (tracks >= 0 && i != tracks)
  4147. continue;
  4148. // When writing a sidx for the full file, entry is 0, but
  4149. // we want to include all tracks. ref_size is 0 in this case,
  4150. // since we read it from frag_info instead.
  4151. if (!track->entry && ref_size > 0)
  4152. continue;
  4153. total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
  4154. total_size);
  4155. }
  4156. if (round == 0)
  4157. total_size = ffio_close_null_buf(avio_buf);
  4158. }
  4159. return 0;
  4160. }
  4161. static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
  4162. {
  4163. int64_t pos = avio_tell(pb), pts_us, ntp_ts;
  4164. MOVTrack *first_track;
  4165. int flags = 24;
  4166. /* PRFT should be associated with at most one track. So, choosing only the
  4167. * first track. */
  4168. if (tracks > 0)
  4169. return 0;
  4170. first_track = &(mov->tracks[0]);
  4171. if (!first_track->entry) {
  4172. av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
  4173. return 0;
  4174. }
  4175. if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
  4176. av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
  4177. return 0;
  4178. }
  4179. if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
  4180. if (first_track->cluster[0].prft.wallclock) {
  4181. /* Round the NTP time to whole milliseconds. */
  4182. ntp_ts = ff_get_formatted_ntp_time((first_track->cluster[0].prft.wallclock / 1000) * 1000 +
  4183. NTP_OFFSET_US);
  4184. flags = first_track->cluster[0].prft.flags;
  4185. } else
  4186. ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
  4187. } else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
  4188. pts_us = av_rescale_q(first_track->cluster[0].pts,
  4189. first_track->st->time_base, AV_TIME_BASE_Q);
  4190. ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
  4191. } else {
  4192. av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
  4193. mov->write_prft);
  4194. return 0;
  4195. }
  4196. avio_wb32(pb, 0); // Size place holder
  4197. ffio_wfourcc(pb, "prft"); // Type
  4198. avio_w8(pb, 1); // Version
  4199. avio_wb24(pb, flags); // Flags
  4200. avio_wb32(pb, first_track->track_id); // reference track ID
  4201. avio_wb64(pb, ntp_ts); // NTP time stamp
  4202. avio_wb64(pb, first_track->cluster[0].pts); //media time
  4203. return update_size(pb, pos);
  4204. }
  4205. static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
  4206. int64_t mdat_size)
  4207. {
  4208. AVIOContext *avio_buf;
  4209. int ret, moof_size;
  4210. if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
  4211. return ret;
  4212. mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
  4213. moof_size = ffio_close_null_buf(avio_buf);
  4214. if (mov->flags & FF_MOV_FLAG_DASH &&
  4215. !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX)))
  4216. mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
  4217. if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
  4218. mov_write_prft_tag(pb, mov, tracks);
  4219. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
  4220. !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
  4221. mov->ism_lookahead) {
  4222. if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
  4223. return ret;
  4224. if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
  4225. mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
  4226. mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
  4227. }
  4228. }
  4229. return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
  4230. }
  4231. static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
  4232. {
  4233. int64_t pos = avio_tell(pb);
  4234. int i;
  4235. avio_wb32(pb, 0); /* size placeholder */
  4236. ffio_wfourcc(pb, "tfra");
  4237. avio_w8(pb, 1); /* version */
  4238. avio_wb24(pb, 0);
  4239. avio_wb32(pb, track->track_id);
  4240. avio_wb32(pb, 0); /* length of traf/trun/sample num */
  4241. avio_wb32(pb, track->nb_frag_info);
  4242. for (i = 0; i < track->nb_frag_info; i++) {
  4243. avio_wb64(pb, track->frag_info[i].time);
  4244. avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
  4245. avio_w8(pb, 1); /* traf number */
  4246. avio_w8(pb, 1); /* trun number */
  4247. avio_w8(pb, 1); /* sample number */
  4248. }
  4249. return update_size(pb, pos);
  4250. }
  4251. static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
  4252. {
  4253. int64_t pos = avio_tell(pb);
  4254. int i;
  4255. avio_wb32(pb, 0); /* size placeholder */
  4256. ffio_wfourcc(pb, "mfra");
  4257. /* An empty mfra atom is enough to indicate to the publishing point that
  4258. * the stream has ended. */
  4259. if (mov->flags & FF_MOV_FLAG_ISML)
  4260. return update_size(pb, pos);
  4261. for (i = 0; i < mov->nb_streams; i++) {
  4262. MOVTrack *track = &mov->tracks[i];
  4263. if (track->nb_frag_info)
  4264. mov_write_tfra_tag(pb, track);
  4265. }
  4266. avio_wb32(pb, 16);
  4267. ffio_wfourcc(pb, "mfro");
  4268. avio_wb32(pb, 0); /* version + flags */
  4269. avio_wb32(pb, avio_tell(pb) + 4 - pos);
  4270. return update_size(pb, pos);
  4271. }
  4272. static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
  4273. {
  4274. avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
  4275. ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
  4276. mov->mdat_pos = avio_tell(pb);
  4277. avio_wb32(pb, 0); /* size placeholder*/
  4278. ffio_wfourcc(pb, "mdat");
  4279. return 0;
  4280. }
  4281. static void mov_write_ftyp_tag_internal(AVIOContext *pb, AVFormatContext *s,
  4282. int has_h264, int has_video, int write_minor)
  4283. {
  4284. MOVMuxContext *mov = s->priv_data;
  4285. int minor = 0x200;
  4286. if (mov->major_brand && strlen(mov->major_brand) >= 4)
  4287. ffio_wfourcc(pb, mov->major_brand);
  4288. else if (mov->mode == MODE_3GP) {
  4289. ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
  4290. minor = has_h264 ? 0x100 : 0x200;
  4291. } else if (mov->mode & MODE_3G2) {
  4292. ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
  4293. minor = has_h264 ? 0x20000 : 0x10000;
  4294. } else if (mov->mode == MODE_PSP)
  4295. ffio_wfourcc(pb, "MSNV");
  4296. else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_FRAGMENT &&
  4297. mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
  4298. ffio_wfourcc(pb, "iso6"); // Required when using signed CTS offsets in trun boxes
  4299. else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
  4300. ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
  4301. else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
  4302. ffio_wfourcc(pb, "iso4");
  4303. else if (mov->mode == MODE_MP4)
  4304. ffio_wfourcc(pb, "isom");
  4305. else if (mov->mode == MODE_IPOD)
  4306. ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
  4307. else if (mov->mode == MODE_ISM)
  4308. ffio_wfourcc(pb, "isml");
  4309. else if (mov->mode == MODE_F4V)
  4310. ffio_wfourcc(pb, "f4v ");
  4311. else
  4312. ffio_wfourcc(pb, "qt ");
  4313. if (write_minor)
  4314. avio_wb32(pb, minor);
  4315. }
  4316. static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
  4317. {
  4318. MOVMuxContext *mov = s->priv_data;
  4319. int64_t pos = avio_tell(pb);
  4320. int has_h264 = 0, has_video = 0;
  4321. int i;
  4322. for (i = 0; i < s->nb_streams; i++) {
  4323. AVStream *st = s->streams[i];
  4324. if (is_cover_image(st))
  4325. continue;
  4326. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  4327. has_video = 1;
  4328. if (st->codecpar->codec_id == AV_CODEC_ID_H264)
  4329. has_h264 = 1;
  4330. }
  4331. avio_wb32(pb, 0); /* size */
  4332. ffio_wfourcc(pb, "ftyp");
  4333. // Write major brand
  4334. mov_write_ftyp_tag_internal(pb, s, has_h264, has_video, 1);
  4335. // Write the major brand as the first compatible brand as well
  4336. mov_write_ftyp_tag_internal(pb, s, has_h264, has_video, 0);
  4337. // Write compatible brands, ensuring that we don't write the major brand as a
  4338. // compatible brand a second time.
  4339. if (mov->mode == MODE_ISM) {
  4340. ffio_wfourcc(pb, "piff");
  4341. } else if (mov->mode != MODE_MOV) {
  4342. // We add tfdt atoms when fragmenting, signal this with the iso6 compatible
  4343. // brand, if not already the major brand. This is compatible with users that
  4344. // don't understand tfdt.
  4345. if (mov->mode == MODE_MP4) {
  4346. if (mov->flags & FF_MOV_FLAG_CMAF)
  4347. ffio_wfourcc(pb, "cmfc");
  4348. if (mov->flags & FF_MOV_FLAG_FRAGMENT && !(mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS))
  4349. ffio_wfourcc(pb, "iso6");
  4350. } else {
  4351. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  4352. ffio_wfourcc(pb, "iso6");
  4353. if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
  4354. ffio_wfourcc(pb, "iso5");
  4355. else if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
  4356. ffio_wfourcc(pb, "iso4");
  4357. }
  4358. // Brands prior to iso5 can't be signaled when using default-base-is-moof
  4359. if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
  4360. // write isom for mp4 only if it it's not the major brand already.
  4361. if (mov->mode != MODE_MP4 || mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
  4362. ffio_wfourcc(pb, "isom");
  4363. ffio_wfourcc(pb, "iso2");
  4364. if (has_h264)
  4365. ffio_wfourcc(pb, "avc1");
  4366. }
  4367. }
  4368. if (mov->mode == MODE_MP4)
  4369. ffio_wfourcc(pb, "mp41");
  4370. if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  4371. ffio_wfourcc(pb, "dash");
  4372. return update_size(pb, pos);
  4373. }
  4374. static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
  4375. {
  4376. AVStream *video_st = s->streams[0];
  4377. AVCodecParameters *video_par = s->streams[0]->codecpar;
  4378. AVCodecParameters *audio_par = s->streams[1]->codecpar;
  4379. int audio_rate = audio_par->sample_rate;
  4380. int64_t frame_rate = video_st->avg_frame_rate.den ?
  4381. (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
  4382. 0;
  4383. int audio_kbitrate = audio_par->bit_rate / 1000;
  4384. int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
  4385. if (frame_rate < 0 || frame_rate > INT32_MAX) {
  4386. av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
  4387. return AVERROR(EINVAL);
  4388. }
  4389. avio_wb32(pb, 0x94); /* size */
  4390. ffio_wfourcc(pb, "uuid");
  4391. ffio_wfourcc(pb, "PROF");
  4392. avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
  4393. avio_wb32(pb, 0xbb88695c);
  4394. avio_wb32(pb, 0xfac9c740);
  4395. avio_wb32(pb, 0x0); /* ? */
  4396. avio_wb32(pb, 0x3); /* 3 sections ? */
  4397. avio_wb32(pb, 0x14); /* size */
  4398. ffio_wfourcc(pb, "FPRF");
  4399. avio_wb32(pb, 0x0); /* ? */
  4400. avio_wb32(pb, 0x0); /* ? */
  4401. avio_wb32(pb, 0x0); /* ? */
  4402. avio_wb32(pb, 0x2c); /* size */
  4403. ffio_wfourcc(pb, "APRF"); /* audio */
  4404. avio_wb32(pb, 0x0);
  4405. avio_wb32(pb, 0x2); /* TrackID */
  4406. ffio_wfourcc(pb, "mp4a");
  4407. avio_wb32(pb, 0x20f);
  4408. avio_wb32(pb, 0x0);
  4409. avio_wb32(pb, audio_kbitrate);
  4410. avio_wb32(pb, audio_kbitrate);
  4411. avio_wb32(pb, audio_rate);
  4412. avio_wb32(pb, audio_par->channels);
  4413. avio_wb32(pb, 0x34); /* size */
  4414. ffio_wfourcc(pb, "VPRF"); /* video */
  4415. avio_wb32(pb, 0x0);
  4416. avio_wb32(pb, 0x1); /* TrackID */
  4417. if (video_par->codec_id == AV_CODEC_ID_H264) {
  4418. ffio_wfourcc(pb, "avc1");
  4419. avio_wb16(pb, 0x014D);
  4420. avio_wb16(pb, 0x0015);
  4421. } else {
  4422. ffio_wfourcc(pb, "mp4v");
  4423. avio_wb16(pb, 0x0000);
  4424. avio_wb16(pb, 0x0103);
  4425. }
  4426. avio_wb32(pb, 0x0);
  4427. avio_wb32(pb, video_kbitrate);
  4428. avio_wb32(pb, video_kbitrate);
  4429. avio_wb32(pb, frame_rate);
  4430. avio_wb32(pb, frame_rate);
  4431. avio_wb16(pb, video_par->width);
  4432. avio_wb16(pb, video_par->height);
  4433. avio_wb32(pb, 0x010001); /* ? */
  4434. return 0;
  4435. }
  4436. static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
  4437. {
  4438. MOVMuxContext *mov = s->priv_data;
  4439. int i;
  4440. mov_write_ftyp_tag(pb,s);
  4441. if (mov->mode == MODE_PSP) {
  4442. int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
  4443. for (i = 0; i < s->nb_streams; i++) {
  4444. AVStream *st = s->streams[i];
  4445. if (is_cover_image(st))
  4446. continue;
  4447. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  4448. video_streams_nb++;
  4449. else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  4450. audio_streams_nb++;
  4451. else
  4452. other_streams_nb++;
  4453. }
  4454. if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
  4455. av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
  4456. return AVERROR(EINVAL);
  4457. }
  4458. return mov_write_uuidprof_tag(pb, s);
  4459. }
  4460. return 0;
  4461. }
  4462. static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
  4463. {
  4464. uint32_t c = -1;
  4465. int i, closed_gop = 0;
  4466. for (i = 0; i < pkt->size - 4; i++) {
  4467. c = (c << 8) + pkt->data[i];
  4468. if (c == 0x1b8) { // gop
  4469. closed_gop = pkt->data[i + 4] >> 6 & 0x01;
  4470. } else if (c == 0x100) { // pic
  4471. int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
  4472. if (!temp_ref || closed_gop) // I picture is not reordered
  4473. *flags = MOV_SYNC_SAMPLE;
  4474. else
  4475. *flags = MOV_PARTIAL_SYNC_SAMPLE;
  4476. break;
  4477. }
  4478. }
  4479. return 0;
  4480. }
  4481. static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
  4482. {
  4483. const uint8_t *start, *next, *end = pkt->data + pkt->size;
  4484. int seq = 0, entry = 0;
  4485. int key = pkt->flags & AV_PKT_FLAG_KEY;
  4486. start = find_next_marker(pkt->data, end);
  4487. for (next = start; next < end; start = next) {
  4488. next = find_next_marker(start + 4, end);
  4489. switch (AV_RB32(start)) {
  4490. case VC1_CODE_SEQHDR:
  4491. seq = 1;
  4492. break;
  4493. case VC1_CODE_ENTRYPOINT:
  4494. entry = 1;
  4495. break;
  4496. case VC1_CODE_SLICE:
  4497. trk->vc1_info.slices = 1;
  4498. break;
  4499. }
  4500. }
  4501. if (!trk->entry && trk->vc1_info.first_packet_seen)
  4502. trk->vc1_info.first_frag_written = 1;
  4503. if (!trk->entry && !trk->vc1_info.first_frag_written) {
  4504. /* First packet in first fragment */
  4505. trk->vc1_info.first_packet_seq = seq;
  4506. trk->vc1_info.first_packet_entry = entry;
  4507. trk->vc1_info.first_packet_seen = 1;
  4508. } else if ((seq && !trk->vc1_info.packet_seq) ||
  4509. (entry && !trk->vc1_info.packet_entry)) {
  4510. int i;
  4511. for (i = 0; i < trk->entry; i++)
  4512. trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
  4513. trk->has_keyframes = 0;
  4514. if (seq)
  4515. trk->vc1_info.packet_seq = 1;
  4516. if (entry)
  4517. trk->vc1_info.packet_entry = 1;
  4518. if (!trk->vc1_info.first_frag_written) {
  4519. /* First fragment */
  4520. if ((!seq || trk->vc1_info.first_packet_seq) &&
  4521. (!entry || trk->vc1_info.first_packet_entry)) {
  4522. /* First packet had the same headers as this one, readd the
  4523. * sync sample flag. */
  4524. trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
  4525. trk->has_keyframes = 1;
  4526. }
  4527. }
  4528. }
  4529. if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
  4530. key = seq && entry;
  4531. else if (trk->vc1_info.packet_seq)
  4532. key = seq;
  4533. else if (trk->vc1_info.packet_entry)
  4534. key = entry;
  4535. if (key) {
  4536. trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
  4537. trk->has_keyframes++;
  4538. }
  4539. }
  4540. static void mov_parse_truehd_frame(AVPacket *pkt, MOVTrack *trk)
  4541. {
  4542. int length;
  4543. if (pkt->size < 8)
  4544. return;
  4545. length = (AV_RB16(pkt->data) & 0xFFF) * 2;
  4546. if (length < 8 || length > pkt->size)
  4547. return;
  4548. if (AV_RB32(pkt->data + 4) == 0xF8726FBA) {
  4549. trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
  4550. trk->has_keyframes++;
  4551. }
  4552. return;
  4553. }
  4554. static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
  4555. {
  4556. MOVMuxContext *mov = s->priv_data;
  4557. int ret, buf_size;
  4558. uint8_t *buf;
  4559. int i, offset;
  4560. if (!track->mdat_buf)
  4561. return 0;
  4562. if (!mov->mdat_buf) {
  4563. if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
  4564. return ret;
  4565. }
  4566. buf_size = avio_get_dyn_buf(track->mdat_buf, &buf);
  4567. offset = avio_tell(mov->mdat_buf);
  4568. avio_write(mov->mdat_buf, buf, buf_size);
  4569. ffio_free_dyn_buf(&track->mdat_buf);
  4570. for (i = track->entries_flushed; i < track->entry; i++)
  4571. track->cluster[i].pos += offset;
  4572. track->entries_flushed = track->entry;
  4573. return 0;
  4574. }
  4575. static int mov_flush_fragment(AVFormatContext *s, int force)
  4576. {
  4577. MOVMuxContext *mov = s->priv_data;
  4578. int i, first_track = -1;
  4579. int64_t mdat_size = 0;
  4580. int ret;
  4581. int has_video = 0, starts_with_key = 0, first_video_track = 1;
  4582. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
  4583. return 0;
  4584. // Try to fill in the duration of the last packet in each stream
  4585. // from queued packets in the interleave queues. If the flushing
  4586. // of fragments was triggered automatically by an AVPacket, we
  4587. // already have reliable info for the end of that track, but other
  4588. // tracks may need to be filled in.
  4589. for (i = 0; i < s->nb_streams; i++) {
  4590. MOVTrack *track = &mov->tracks[i];
  4591. if (!track->end_reliable) {
  4592. AVPacket pkt;
  4593. if (!ff_interleaved_peek(s, i, &pkt, 1)) {
  4594. if (track->dts_shift != AV_NOPTS_VALUE)
  4595. pkt.dts += track->dts_shift;
  4596. track->track_duration = pkt.dts - track->start_dts;
  4597. if (pkt.pts != AV_NOPTS_VALUE)
  4598. track->end_pts = pkt.pts;
  4599. else
  4600. track->end_pts = pkt.dts;
  4601. }
  4602. }
  4603. }
  4604. for (i = 0; i < mov->nb_streams; i++) {
  4605. MOVTrack *track = &mov->tracks[i];
  4606. if (track->entry <= 1)
  4607. continue;
  4608. // Sample durations are calculated as the diff of dts values,
  4609. // but for the last sample in a fragment, we don't know the dts
  4610. // of the first sample in the next fragment, so we have to rely
  4611. // on what was set as duration in the AVPacket. Not all callers
  4612. // set this though, so we might want to replace it with an
  4613. // estimate if it currently is zero.
  4614. if (get_cluster_duration(track, track->entry - 1) != 0)
  4615. continue;
  4616. // Use the duration (i.e. dts diff) of the second last sample for
  4617. // the last one. This is a wild guess (and fatal if it turns out
  4618. // to be too long), but probably the best we can do - having a zero
  4619. // duration is bad as well.
  4620. track->track_duration += get_cluster_duration(track, track->entry - 2);
  4621. track->end_pts += get_cluster_duration(track, track->entry - 2);
  4622. if (!mov->missing_duration_warned) {
  4623. av_log(s, AV_LOG_WARNING,
  4624. "Estimating the duration of the last packet in a "
  4625. "fragment, consider setting the duration field in "
  4626. "AVPacket instead.\n");
  4627. mov->missing_duration_warned = 1;
  4628. }
  4629. }
  4630. if (!mov->moov_written) {
  4631. int64_t pos = avio_tell(s->pb);
  4632. uint8_t *buf;
  4633. int buf_size, moov_size;
  4634. for (i = 0; i < mov->nb_streams; i++)
  4635. if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
  4636. break;
  4637. /* Don't write the initial moov unless all tracks have data */
  4638. if (i < mov->nb_streams && !force)
  4639. return 0;
  4640. moov_size = get_moov_size(s);
  4641. for (i = 0; i < mov->nb_streams; i++)
  4642. mov->tracks[i].data_offset = pos + moov_size + 8;
  4643. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
  4644. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  4645. mov_write_identification(s->pb, s);
  4646. if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
  4647. return ret;
  4648. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
  4649. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  4650. mov->reserved_header_pos = avio_tell(s->pb);
  4651. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
  4652. mov->moov_written = 1;
  4653. return 0;
  4654. }
  4655. buf_size = avio_get_dyn_buf(mov->mdat_buf, &buf);
  4656. avio_wb32(s->pb, buf_size + 8);
  4657. ffio_wfourcc(s->pb, "mdat");
  4658. avio_write(s->pb, buf, buf_size);
  4659. ffio_free_dyn_buf(&mov->mdat_buf);
  4660. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  4661. mov->reserved_header_pos = avio_tell(s->pb);
  4662. mov->moov_written = 1;
  4663. mov->mdat_size = 0;
  4664. for (i = 0; i < mov->nb_streams; i++) {
  4665. if (mov->tracks[i].entry)
  4666. mov->tracks[i].frag_start += mov->tracks[i].start_dts +
  4667. mov->tracks[i].track_duration -
  4668. mov->tracks[i].cluster[0].dts;
  4669. mov->tracks[i].entry = 0;
  4670. mov->tracks[i].end_reliable = 0;
  4671. }
  4672. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
  4673. return 0;
  4674. }
  4675. if (mov->frag_interleave) {
  4676. for (i = 0; i < mov->nb_streams; i++) {
  4677. MOVTrack *track = &mov->tracks[i];
  4678. int ret;
  4679. if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
  4680. return ret;
  4681. }
  4682. if (!mov->mdat_buf)
  4683. return 0;
  4684. mdat_size = avio_tell(mov->mdat_buf);
  4685. }
  4686. for (i = 0; i < mov->nb_streams; i++) {
  4687. MOVTrack *track = &mov->tracks[i];
  4688. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
  4689. track->data_offset = 0;
  4690. else
  4691. track->data_offset = mdat_size;
  4692. if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  4693. has_video = 1;
  4694. if (first_video_track) {
  4695. if (track->entry)
  4696. starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
  4697. first_video_track = 0;
  4698. }
  4699. }
  4700. if (!track->entry)
  4701. continue;
  4702. if (track->mdat_buf)
  4703. mdat_size += avio_tell(track->mdat_buf);
  4704. if (first_track < 0)
  4705. first_track = i;
  4706. }
  4707. if (!mdat_size)
  4708. return 0;
  4709. avio_write_marker(s->pb,
  4710. av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
  4711. (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);
  4712. for (i = 0; i < mov->nb_streams; i++) {
  4713. MOVTrack *track = &mov->tracks[i];
  4714. int buf_size, write_moof = 1, moof_tracks = -1;
  4715. uint8_t *buf;
  4716. int64_t duration = 0;
  4717. if (track->entry)
  4718. duration = track->start_dts + track->track_duration -
  4719. track->cluster[0].dts;
  4720. if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
  4721. if (!track->mdat_buf)
  4722. continue;
  4723. mdat_size = avio_tell(track->mdat_buf);
  4724. moof_tracks = i;
  4725. } else {
  4726. write_moof = i == first_track;
  4727. }
  4728. if (write_moof) {
  4729. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
  4730. mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
  4731. mov->fragments++;
  4732. avio_wb32(s->pb, mdat_size + 8);
  4733. ffio_wfourcc(s->pb, "mdat");
  4734. }
  4735. if (track->entry)
  4736. track->frag_start += duration;
  4737. track->entry = 0;
  4738. track->entries_flushed = 0;
  4739. track->end_reliable = 0;
  4740. if (!mov->frag_interleave) {
  4741. if (!track->mdat_buf)
  4742. continue;
  4743. buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
  4744. track->mdat_buf = NULL;
  4745. } else {
  4746. if (!mov->mdat_buf)
  4747. continue;
  4748. buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
  4749. mov->mdat_buf = NULL;
  4750. }
  4751. avio_write(s->pb, buf, buf_size);
  4752. av_free(buf);
  4753. }
  4754. mov->mdat_size = 0;
  4755. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
  4756. return 0;
  4757. }
  4758. static int mov_auto_flush_fragment(AVFormatContext *s, int force)
  4759. {
  4760. MOVMuxContext *mov = s->priv_data;
  4761. int had_moov = mov->moov_written;
  4762. int ret = mov_flush_fragment(s, force);
  4763. if (ret < 0)
  4764. return ret;
  4765. // If using delay_moov, the first flush only wrote the moov,
  4766. // not the actual moof+mdat pair, thus flush once again.
  4767. if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  4768. ret = mov_flush_fragment(s, force);
  4769. return ret;
  4770. }
  4771. static int check_pkt(AVFormatContext *s, AVPacket *pkt)
  4772. {
  4773. MOVMuxContext *mov = s->priv_data;
  4774. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4775. int64_t ref;
  4776. uint64_t duration;
  4777. if (trk->entry) {
  4778. ref = trk->cluster[trk->entry - 1].dts;
  4779. } else if ( trk->start_dts != AV_NOPTS_VALUE
  4780. && !trk->frag_discont) {
  4781. ref = trk->start_dts + trk->track_duration;
  4782. } else
  4783. ref = pkt->dts; // Skip tests for the first packet
  4784. if (trk->dts_shift != AV_NOPTS_VALUE) {
  4785. /* With negative CTS offsets we have set an offset to the DTS,
  4786. * reverse this for the check. */
  4787. ref -= trk->dts_shift;
  4788. }
  4789. duration = pkt->dts - ref;
  4790. if (pkt->dts < ref || duration >= INT_MAX) {
  4791. av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
  4792. duration, pkt->dts
  4793. );
  4794. pkt->dts = ref + 1;
  4795. pkt->pts = AV_NOPTS_VALUE;
  4796. }
  4797. if (pkt->duration < 0 || pkt->duration > INT_MAX) {
  4798. av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
  4799. return AVERROR(EINVAL);
  4800. }
  4801. return 0;
  4802. }
  4803. int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  4804. {
  4805. MOVMuxContext *mov = s->priv_data;
  4806. AVIOContext *pb = s->pb;
  4807. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  4808. AVCodecParameters *par = trk->par;
  4809. AVProducerReferenceTime *prft;
  4810. unsigned int samples_in_chunk = 0;
  4811. int size = pkt->size, ret = 0, offset = 0;
  4812. int prft_size;
  4813. uint8_t *reformatted_data = NULL;
  4814. ret = check_pkt(s, pkt);
  4815. if (ret < 0)
  4816. return ret;
  4817. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  4818. int ret;
  4819. if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
  4820. if (mov->frag_interleave && mov->fragments > 0) {
  4821. if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
  4822. if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
  4823. return ret;
  4824. }
  4825. }
  4826. if (!trk->mdat_buf) {
  4827. if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
  4828. return ret;
  4829. }
  4830. pb = trk->mdat_buf;
  4831. } else {
  4832. if (!mov->mdat_buf) {
  4833. if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
  4834. return ret;
  4835. }
  4836. pb = mov->mdat_buf;
  4837. }
  4838. }
  4839. if (par->codec_id == AV_CODEC_ID_AMR_NB) {
  4840. /* We must find out how many AMR blocks there are in one packet */
  4841. static const uint16_t packed_size[16] =
  4842. {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
  4843. int len = 0;
  4844. while (len < size && samples_in_chunk < 100) {
  4845. len += packed_size[(pkt->data[len] >> 3) & 0x0F];
  4846. samples_in_chunk++;
  4847. }
  4848. if (samples_in_chunk > 1) {
  4849. av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
  4850. return -1;
  4851. }
  4852. } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
  4853. par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
  4854. samples_in_chunk = trk->par->frame_size;
  4855. } else if (trk->sample_size)
  4856. samples_in_chunk = size / trk->sample_size;
  4857. else
  4858. samples_in_chunk = 1;
  4859. if (samples_in_chunk < 1) {
  4860. av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n");
  4861. return AVERROR_PATCHWELCOME;
  4862. }
  4863. /* copy extradata if it exists */
  4864. if (trk->vos_len == 0 && par->extradata_size > 0 &&
  4865. !TAG_IS_AVCI(trk->tag) &&
  4866. (par->codec_id != AV_CODEC_ID_DNXHD)) {
  4867. trk->vos_len = par->extradata_size;
  4868. trk->vos_data = av_malloc(trk->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
  4869. if (!trk->vos_data) {
  4870. ret = AVERROR(ENOMEM);
  4871. goto err;
  4872. }
  4873. memcpy(trk->vos_data, par->extradata, trk->vos_len);
  4874. memset(trk->vos_data + trk->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  4875. }
  4876. if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
  4877. (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
  4878. if (!s->streams[pkt->stream_index]->nb_frames) {
  4879. av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
  4880. "use the audio bitstream filter 'aac_adtstoasc' to fix it "
  4881. "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
  4882. return -1;
  4883. }
  4884. av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
  4885. }
  4886. if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
  4887. /* from x264 or from bytestream H.264 */
  4888. /* NAL reformatting needed */
  4889. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  4890. ret = ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
  4891. &size);
  4892. if (ret < 0)
  4893. return ret;
  4894. avio_write(pb, reformatted_data, size);
  4895. } else {
  4896. if (trk->cenc.aes_ctr) {
  4897. size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
  4898. if (size < 0) {
  4899. ret = size;
  4900. goto err;
  4901. }
  4902. } else {
  4903. size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
  4904. }
  4905. }
  4906. } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
  4907. (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
  4908. /* extradata is Annex B, assume the bitstream is too and convert it */
  4909. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  4910. ret = ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data,
  4911. &size, 0, NULL);
  4912. if (ret < 0)
  4913. return ret;
  4914. avio_write(pb, reformatted_data, size);
  4915. } else {
  4916. size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
  4917. }
  4918. } else if (par->codec_id == AV_CODEC_ID_AV1) {
  4919. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
  4920. ret = ff_av1_filter_obus_buf(pkt->data, &reformatted_data,
  4921. &size, &offset);
  4922. if (ret < 0)
  4923. return ret;
  4924. avio_write(pb, reformatted_data, size);
  4925. } else {
  4926. size = ff_av1_filter_obus(pb, pkt->data, pkt->size);
  4927. }
  4928. #if CONFIG_AC3_PARSER
  4929. } else if (par->codec_id == AV_CODEC_ID_EAC3) {
  4930. size = handle_eac3(mov, pkt, trk);
  4931. if (size < 0)
  4932. return size;
  4933. else if (!size)
  4934. goto end;
  4935. avio_write(pb, pkt->data, size);
  4936. #endif
  4937. } else {
  4938. if (trk->cenc.aes_ctr) {
  4939. if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
  4940. int nal_size_length = (par->extradata[4] & 0x3) + 1;
  4941. ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
  4942. } else {
  4943. ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
  4944. }
  4945. if (ret) {
  4946. goto err;
  4947. }
  4948. } else {
  4949. avio_write(pb, pkt->data, size);
  4950. }
  4951. }
  4952. if ((par->codec_id == AV_CODEC_ID_DNXHD ||
  4953. par->codec_id == AV_CODEC_ID_TRUEHD ||
  4954. par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
  4955. /* copy frame to create needed atoms */
  4956. trk->vos_len = size;
  4957. trk->vos_data = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
  4958. if (!trk->vos_data) {
  4959. ret = AVERROR(ENOMEM);
  4960. goto err;
  4961. }
  4962. memcpy(trk->vos_data, pkt->data, size);
  4963. memset(trk->vos_data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  4964. }
  4965. if (trk->entry >= trk->cluster_capacity) {
  4966. unsigned new_capacity = trk->entry + MOV_INDEX_CLUSTER_SIZE;
  4967. if (av_reallocp_array(&trk->cluster, new_capacity,
  4968. sizeof(*trk->cluster))) {
  4969. ret = AVERROR(ENOMEM);
  4970. goto err;
  4971. }
  4972. trk->cluster_capacity = new_capacity;
  4973. }
  4974. trk->cluster[trk->entry].pos = avio_tell(pb) - size;
  4975. trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
  4976. trk->cluster[trk->entry].chunkNum = 0;
  4977. trk->cluster[trk->entry].size = size;
  4978. trk->cluster[trk->entry].entries = samples_in_chunk;
  4979. trk->cluster[trk->entry].dts = pkt->dts;
  4980. trk->cluster[trk->entry].pts = pkt->pts;
  4981. if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
  4982. if (!trk->frag_discont) {
  4983. /* First packet of a new fragment. We already wrote the duration
  4984. * of the last packet of the previous fragment based on track_duration,
  4985. * which might not exactly match our dts. Therefore adjust the dts
  4986. * of this packet to be what the previous packets duration implies. */
  4987. trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
  4988. /* We also may have written the pts and the corresponding duration
  4989. * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
  4990. * the next fragment. This means the cts of the first sample must
  4991. * be the same in all fragments, unless end_pts was updated by
  4992. * the packet causing the fragment to be written. */
  4993. if ((mov->flags & FF_MOV_FLAG_DASH &&
  4994. !(mov->flags & (FF_MOV_FLAG_GLOBAL_SIDX | FF_MOV_FLAG_SKIP_SIDX))) ||
  4995. mov->mode == MODE_ISM)
  4996. pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
  4997. } else {
  4998. /* New fragment, but discontinuous from previous fragments.
  4999. * Pretend the duration sum of the earlier fragments is
  5000. * pkt->dts - trk->start_dts. */
  5001. trk->frag_start = pkt->dts - trk->start_dts;
  5002. trk->end_pts = AV_NOPTS_VALUE;
  5003. trk->frag_discont = 0;
  5004. }
  5005. }
  5006. if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
  5007. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
  5008. /* Not using edit lists and shifting the first track to start from zero.
  5009. * If the other streams start from a later timestamp, we won't be able
  5010. * to signal the difference in starting time without an edit list.
  5011. * Thus move the timestamp for this first sample to 0, increasing
  5012. * its duration instead. */
  5013. trk->cluster[trk->entry].dts = trk->start_dts = 0;
  5014. }
  5015. if (trk->start_dts == AV_NOPTS_VALUE) {
  5016. trk->start_dts = pkt->dts;
  5017. if (trk->frag_discont) {
  5018. if (mov->use_editlist) {
  5019. /* Pretend the whole stream started at pts=0, with earlier fragments
  5020. * already written. If the stream started at pts=0, the duration sum
  5021. * of earlier fragments would have been pkt->pts. */
  5022. trk->frag_start = pkt->pts;
  5023. trk->start_dts = pkt->dts - pkt->pts;
  5024. } else {
  5025. /* Pretend the whole stream started at dts=0, with earlier fragments
  5026. * already written, with a duration summing up to pkt->dts. */
  5027. trk->frag_start = pkt->dts;
  5028. trk->start_dts = 0;
  5029. }
  5030. trk->frag_discont = 0;
  5031. } else if (pkt->dts && mov->moov_written)
  5032. av_log(s, AV_LOG_WARNING,
  5033. "Track %d starts with a nonzero dts %"PRId64", while the moov "
  5034. "already has been written. Set the delay_moov flag to handle "
  5035. "this case.\n",
  5036. pkt->stream_index, pkt->dts);
  5037. }
  5038. trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
  5039. trk->last_sample_is_subtitle_end = 0;
  5040. if (pkt->pts == AV_NOPTS_VALUE) {
  5041. av_log(s, AV_LOG_WARNING, "pts has no value\n");
  5042. pkt->pts = pkt->dts;
  5043. }
  5044. if (pkt->dts != pkt->pts)
  5045. trk->flags |= MOV_TRACK_CTTS;
  5046. trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
  5047. trk->cluster[trk->entry].flags = 0;
  5048. if (trk->start_cts == AV_NOPTS_VALUE)
  5049. trk->start_cts = pkt->pts - pkt->dts;
  5050. if (trk->end_pts == AV_NOPTS_VALUE)
  5051. trk->end_pts = trk->cluster[trk->entry].dts +
  5052. trk->cluster[trk->entry].cts + pkt->duration;
  5053. else
  5054. trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
  5055. trk->cluster[trk->entry].cts +
  5056. pkt->duration);
  5057. if (par->codec_id == AV_CODEC_ID_VC1) {
  5058. mov_parse_vc1_frame(pkt, trk);
  5059. } else if (par->codec_id == AV_CODEC_ID_TRUEHD) {
  5060. mov_parse_truehd_frame(pkt, trk);
  5061. } else if (pkt->flags & AV_PKT_FLAG_KEY) {
  5062. if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
  5063. trk->entry > 0) { // force sync sample for the first key frame
  5064. mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
  5065. if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
  5066. trk->flags |= MOV_TRACK_STPS;
  5067. } else {
  5068. trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
  5069. }
  5070. if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
  5071. trk->has_keyframes++;
  5072. }
  5073. if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
  5074. trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
  5075. trk->has_disposable++;
  5076. }
  5077. prft = (AVProducerReferenceTime *)av_packet_get_side_data(pkt, AV_PKT_DATA_PRFT, &prft_size);
  5078. if (prft && prft_size == sizeof(AVProducerReferenceTime))
  5079. memcpy(&trk->cluster[trk->entry].prft, prft, prft_size);
  5080. else
  5081. memset(&trk->cluster[trk->entry].prft, 0, sizeof(AVProducerReferenceTime));
  5082. trk->entry++;
  5083. trk->sample_count += samples_in_chunk;
  5084. mov->mdat_size += size;
  5085. if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
  5086. ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
  5087. reformatted_data ? reformatted_data + offset
  5088. : NULL, size);
  5089. end:
  5090. err:
  5091. if (pkt->data != reformatted_data)
  5092. av_free(reformatted_data);
  5093. return ret;
  5094. }
  5095. static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
  5096. {
  5097. MOVMuxContext *mov = s->priv_data;
  5098. MOVTrack *trk = &mov->tracks[pkt->stream_index];
  5099. AVCodecParameters *par = trk->par;
  5100. int64_t frag_duration = 0;
  5101. int size = pkt->size;
  5102. int ret = check_pkt(s, pkt);
  5103. if (ret < 0)
  5104. return ret;
  5105. if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
  5106. int i;
  5107. for (i = 0; i < s->nb_streams; i++)
  5108. mov->tracks[i].frag_discont = 1;
  5109. mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
  5110. }
  5111. if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
  5112. if (trk->dts_shift == AV_NOPTS_VALUE)
  5113. trk->dts_shift = pkt->pts - pkt->dts;
  5114. pkt->dts += trk->dts_shift;
  5115. }
  5116. if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
  5117. trk->par->codec_id == AV_CODEC_ID_AAC ||
  5118. trk->par->codec_id == AV_CODEC_ID_AV1 ||
  5119. trk->par->codec_id == AV_CODEC_ID_FLAC) {
  5120. int side_size = 0;
  5121. uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
  5122. if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
  5123. void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
  5124. if (!newextra)
  5125. return AVERROR(ENOMEM);
  5126. av_free(par->extradata);
  5127. par->extradata = newextra;
  5128. memcpy(par->extradata, side, side_size);
  5129. par->extradata_size = side_size;
  5130. if (!pkt->size) // Flush packet
  5131. mov->need_rewrite_extradata = 1;
  5132. }
  5133. }
  5134. if (!pkt->size) {
  5135. if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
  5136. trk->start_dts = pkt->dts;
  5137. if (pkt->pts != AV_NOPTS_VALUE)
  5138. trk->start_cts = pkt->pts - pkt->dts;
  5139. else
  5140. trk->start_cts = 0;
  5141. }
  5142. return 0; /* Discard 0 sized packets */
  5143. }
  5144. if (trk->entry && pkt->stream_index < s->nb_streams)
  5145. frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
  5146. s->streams[pkt->stream_index]->time_base,
  5147. AV_TIME_BASE_Q);
  5148. if ((mov->max_fragment_duration &&
  5149. frag_duration >= mov->max_fragment_duration) ||
  5150. (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
  5151. (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
  5152. par->codec_type == AVMEDIA_TYPE_VIDEO &&
  5153. trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
  5154. (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
  5155. if (frag_duration >= mov->min_fragment_duration) {
  5156. // Set the duration of this track to line up with the next
  5157. // sample in this track. This avoids relying on AVPacket
  5158. // duration, but only helps for this particular track, not
  5159. // for the other ones that are flushed at the same time.
  5160. trk->track_duration = pkt->dts - trk->start_dts;
  5161. if (pkt->pts != AV_NOPTS_VALUE)
  5162. trk->end_pts = pkt->pts;
  5163. else
  5164. trk->end_pts = pkt->dts;
  5165. trk->end_reliable = 1;
  5166. mov_auto_flush_fragment(s, 0);
  5167. }
  5168. }
  5169. return ff_mov_write_packet(s, pkt);
  5170. }
  5171. static int mov_write_subtitle_end_packet(AVFormatContext *s,
  5172. int stream_index,
  5173. int64_t dts) {
  5174. AVPacket end;
  5175. uint8_t data[2] = {0};
  5176. int ret;
  5177. av_init_packet(&end);
  5178. end.size = sizeof(data);
  5179. end.data = data;
  5180. end.pts = dts;
  5181. end.dts = dts;
  5182. end.duration = 0;
  5183. end.stream_index = stream_index;
  5184. ret = mov_write_single_packet(s, &end);
  5185. av_packet_unref(&end);
  5186. return ret;
  5187. }
  5188. static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
  5189. {
  5190. MOVMuxContext *mov = s->priv_data;
  5191. MOVTrack *trk;
  5192. if (!pkt) {
  5193. mov_flush_fragment(s, 1);
  5194. return 1;
  5195. }
  5196. trk = &mov->tracks[pkt->stream_index];
  5197. if (is_cover_image(trk->st)) {
  5198. int ret;
  5199. if (trk->st->nb_frames >= 1) {
  5200. if (trk->st->nb_frames == 1)
  5201. av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
  5202. " ignoring.\n", pkt->stream_index);
  5203. return 0;
  5204. }
  5205. if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
  5206. return ret;
  5207. return 0;
  5208. } else {
  5209. int i;
  5210. if (!pkt->size)
  5211. return mov_write_single_packet(s, pkt); /* Passthrough. */
  5212. /*
  5213. * Subtitles require special handling.
  5214. *
  5215. * 1) For full complaince, every track must have a sample at
  5216. * dts == 0, which is rarely true for subtitles. So, as soon
  5217. * as we see any packet with dts > 0, write an empty subtitle
  5218. * at dts == 0 for any subtitle track with no samples in it.
  5219. *
  5220. * 2) For each subtitle track, check if the current packet's
  5221. * dts is past the duration of the last subtitle sample. If
  5222. * so, we now need to write an end sample for that subtitle.
  5223. *
  5224. * This must be done conditionally to allow for subtitles that
  5225. * immediately replace each other, in which case an end sample
  5226. * is not needed, and is, in fact, actively harmful.
  5227. *
  5228. * 3) See mov_write_trailer for how the final end sample is
  5229. * handled.
  5230. */
  5231. for (i = 0; i < mov->nb_streams; i++) {
  5232. MOVTrack *trk = &mov->tracks[i];
  5233. int ret;
  5234. if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
  5235. trk->track_duration < pkt->dts &&
  5236. (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
  5237. ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
  5238. if (ret < 0) return ret;
  5239. trk->last_sample_is_subtitle_end = 1;
  5240. }
  5241. }
  5242. if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  5243. AVPacket *opkt = pkt;
  5244. int reshuffle_ret, ret;
  5245. if (trk->is_unaligned_qt_rgb) {
  5246. int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
  5247. int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
  5248. reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
  5249. if (reshuffle_ret < 0)
  5250. return reshuffle_ret;
  5251. } else
  5252. reshuffle_ret = 0;
  5253. if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
  5254. ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
  5255. if (ret < 0)
  5256. goto fail;
  5257. if (ret)
  5258. trk->pal_done++;
  5259. } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
  5260. (trk->par->format == AV_PIX_FMT_GRAY8 ||
  5261. trk->par->format == AV_PIX_FMT_MONOBLACK)) {
  5262. for (i = 0; i < pkt->size; i++)
  5263. pkt->data[i] = ~pkt->data[i];
  5264. }
  5265. if (reshuffle_ret) {
  5266. ret = mov_write_single_packet(s, pkt);
  5267. fail:
  5268. if (reshuffle_ret)
  5269. av_packet_free(&pkt);
  5270. return ret;
  5271. }
  5272. }
  5273. return mov_write_single_packet(s, pkt);
  5274. }
  5275. }
  5276. // QuickTime chapters involve an additional text track with the chapter names
  5277. // as samples, and a tref pointing from the other tracks to the chapter one.
  5278. static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
  5279. {
  5280. AVIOContext *pb;
  5281. MOVMuxContext *mov = s->priv_data;
  5282. MOVTrack *track = &mov->tracks[tracknum];
  5283. AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
  5284. int i, len;
  5285. track->mode = mov->mode;
  5286. track->tag = MKTAG('t','e','x','t');
  5287. track->timescale = MOV_TIMESCALE;
  5288. track->par = avcodec_parameters_alloc();
  5289. if (!track->par)
  5290. return AVERROR(ENOMEM);
  5291. track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
  5292. #if 0
  5293. // These properties are required to make QT recognize the chapter track
  5294. uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
  5295. if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
  5296. return AVERROR(ENOMEM);
  5297. memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
  5298. #else
  5299. if (avio_open_dyn_buf(&pb) >= 0) {
  5300. int size;
  5301. uint8_t *buf;
  5302. /* Stub header (usually for Quicktime chapter track) */
  5303. // TextSampleEntry
  5304. avio_wb32(pb, 0x01); // displayFlags
  5305. avio_w8(pb, 0x00); // horizontal justification
  5306. avio_w8(pb, 0x00); // vertical justification
  5307. avio_w8(pb, 0x00); // bgColourRed
  5308. avio_w8(pb, 0x00); // bgColourGreen
  5309. avio_w8(pb, 0x00); // bgColourBlue
  5310. avio_w8(pb, 0x00); // bgColourAlpha
  5311. // BoxRecord
  5312. avio_wb16(pb, 0x00); // defTextBoxTop
  5313. avio_wb16(pb, 0x00); // defTextBoxLeft
  5314. avio_wb16(pb, 0x00); // defTextBoxBottom
  5315. avio_wb16(pb, 0x00); // defTextBoxRight
  5316. // StyleRecord
  5317. avio_wb16(pb, 0x00); // startChar
  5318. avio_wb16(pb, 0x00); // endChar
  5319. avio_wb16(pb, 0x01); // fontID
  5320. avio_w8(pb, 0x00); // fontStyleFlags
  5321. avio_w8(pb, 0x00); // fontSize
  5322. avio_w8(pb, 0x00); // fgColourRed
  5323. avio_w8(pb, 0x00); // fgColourGreen
  5324. avio_w8(pb, 0x00); // fgColourBlue
  5325. avio_w8(pb, 0x00); // fgColourAlpha
  5326. // FontTableBox
  5327. avio_wb32(pb, 0x0D); // box size
  5328. ffio_wfourcc(pb, "ftab"); // box atom name
  5329. avio_wb16(pb, 0x01); // entry count
  5330. // FontRecord
  5331. avio_wb16(pb, 0x01); // font ID
  5332. avio_w8(pb, 0x00); // font name length
  5333. if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
  5334. track->par->extradata = buf;
  5335. track->par->extradata_size = size;
  5336. } else {
  5337. av_freep(&buf);
  5338. }
  5339. }
  5340. #endif
  5341. for (i = 0; i < s->nb_chapters; i++) {
  5342. AVChapter *c = s->chapters[i];
  5343. AVDictionaryEntry *t;
  5344. int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
  5345. pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
  5346. pkt.duration = end - pkt.dts;
  5347. if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
  5348. static const char encd[12] = {
  5349. 0x00, 0x00, 0x00, 0x0C,
  5350. 'e', 'n', 'c', 'd',
  5351. 0x00, 0x00, 0x01, 0x00 };
  5352. len = strlen(t->value);
  5353. pkt.size = len + 2 + 12;
  5354. pkt.data = av_malloc(pkt.size);
  5355. if (!pkt.data)
  5356. return AVERROR(ENOMEM);
  5357. AV_WB16(pkt.data, len);
  5358. memcpy(pkt.data + 2, t->value, len);
  5359. memcpy(pkt.data + len + 2, encd, sizeof(encd));
  5360. ff_mov_write_packet(s, &pkt);
  5361. av_freep(&pkt.data);
  5362. }
  5363. }
  5364. return 0;
  5365. }
  5366. static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
  5367. {
  5368. int ret;
  5369. /* compute the frame number */
  5370. ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
  5371. return ret;
  5372. }
  5373. static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
  5374. {
  5375. int ret;
  5376. MOVMuxContext *mov = s->priv_data;
  5377. MOVTrack *track = &mov->tracks[index];
  5378. AVStream *src_st = s->streams[src_index];
  5379. AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
  5380. AVRational rate = find_fps(s, src_st);
  5381. /* tmcd track based on video stream */
  5382. track->mode = mov->mode;
  5383. track->tag = MKTAG('t','m','c','d');
  5384. track->src_track = src_index;
  5385. track->timescale = mov->tracks[src_index].timescale;
  5386. if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
  5387. track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
  5388. /* set st to src_st for metadata access*/
  5389. track->st = src_st;
  5390. /* encode context: tmcd data stream */
  5391. track->par = avcodec_parameters_alloc();
  5392. if (!track->par)
  5393. return AVERROR(ENOMEM);
  5394. track->par->codec_type = AVMEDIA_TYPE_DATA;
  5395. track->par->codec_tag = track->tag;
  5396. track->st->avg_frame_rate = av_inv_q(rate);
  5397. /* the tmcd track just contains one packet with the frame number */
  5398. pkt.data = av_malloc(pkt.size);
  5399. if (!pkt.data)
  5400. return AVERROR(ENOMEM);
  5401. AV_WB32(pkt.data, tc.start);
  5402. ret = ff_mov_write_packet(s, &pkt);
  5403. av_free(pkt.data);
  5404. return ret;
  5405. }
  5406. /*
  5407. * st->disposition controls the "enabled" flag in the tkhd tag.
  5408. * QuickTime will not play a track if it is not enabled. So make sure
  5409. * that one track of each type (audio, video, subtitle) is enabled.
  5410. *
  5411. * Subtitles are special. For audio and video, setting "enabled" also
  5412. * makes the track "default" (i.e. it is rendered when played). For
  5413. * subtitles, an "enabled" subtitle is not rendered by default, but
  5414. * if no subtitle is enabled, the subtitle menu in QuickTime will be
  5415. * empty!
  5416. */
  5417. static void enable_tracks(AVFormatContext *s)
  5418. {
  5419. MOVMuxContext *mov = s->priv_data;
  5420. int i;
  5421. int enabled[AVMEDIA_TYPE_NB];
  5422. int first[AVMEDIA_TYPE_NB];
  5423. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  5424. enabled[i] = 0;
  5425. first[i] = -1;
  5426. }
  5427. for (i = 0; i < s->nb_streams; i++) {
  5428. AVStream *st = s->streams[i];
  5429. if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
  5430. st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
  5431. is_cover_image(st))
  5432. continue;
  5433. if (first[st->codecpar->codec_type] < 0)
  5434. first[st->codecpar->codec_type] = i;
  5435. if (st->disposition & AV_DISPOSITION_DEFAULT) {
  5436. mov->tracks[i].flags |= MOV_TRACK_ENABLED;
  5437. enabled[st->codecpar->codec_type]++;
  5438. }
  5439. }
  5440. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  5441. switch (i) {
  5442. case AVMEDIA_TYPE_VIDEO:
  5443. case AVMEDIA_TYPE_AUDIO:
  5444. case AVMEDIA_TYPE_SUBTITLE:
  5445. if (enabled[i] > 1)
  5446. mov->per_stream_grouping = 1;
  5447. if (!enabled[i] && first[i] >= 0)
  5448. mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
  5449. break;
  5450. }
  5451. }
  5452. }
  5453. static void mov_free(AVFormatContext *s)
  5454. {
  5455. MOVMuxContext *mov = s->priv_data;
  5456. int i;
  5457. if (mov->chapter_track) {
  5458. if (mov->tracks[mov->chapter_track].par)
  5459. av_freep(&mov->tracks[mov->chapter_track].par->extradata);
  5460. av_freep(&mov->tracks[mov->chapter_track].par);
  5461. }
  5462. for (i = 0; i < mov->nb_streams; i++) {
  5463. if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
  5464. ff_mov_close_hinting(&mov->tracks[i]);
  5465. else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
  5466. av_freep(&mov->tracks[i].par);
  5467. av_freep(&mov->tracks[i].cluster);
  5468. av_freep(&mov->tracks[i].frag_info);
  5469. av_packet_unref(&mov->tracks[i].cover_image);
  5470. if (mov->tracks[i].eac3_priv) {
  5471. struct eac3_info *info = mov->tracks[i].eac3_priv;
  5472. av_packet_unref(&info->pkt);
  5473. av_freep(&mov->tracks[i].eac3_priv);
  5474. }
  5475. if (mov->tracks[i].vos_len)
  5476. av_freep(&mov->tracks[i].vos_data);
  5477. ff_mov_cenc_free(&mov->tracks[i].cenc);
  5478. }
  5479. av_freep(&mov->tracks);
  5480. }
  5481. static uint32_t rgb_to_yuv(uint32_t rgb)
  5482. {
  5483. uint8_t r, g, b;
  5484. int y, cb, cr;
  5485. r = (rgb >> 16) & 0xFF;
  5486. g = (rgb >> 8) & 0xFF;
  5487. b = (rgb ) & 0xFF;
  5488. y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
  5489. cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
  5490. cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
  5491. return (y << 16) | (cr << 8) | cb;
  5492. }
  5493. static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
  5494. AVStream *st)
  5495. {
  5496. int i, width = 720, height = 480;
  5497. int have_palette = 0, have_size = 0;
  5498. uint32_t palette[16];
  5499. char *cur = st->codecpar->extradata;
  5500. while (cur && *cur) {
  5501. if (strncmp("palette:", cur, 8) == 0) {
  5502. int i, count;
  5503. count = sscanf(cur + 8,
  5504. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  5505. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  5506. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
  5507. "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
  5508. &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
  5509. &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
  5510. &palette[ 8], &palette[ 9], &palette[10], &palette[11],
  5511. &palette[12], &palette[13], &palette[14], &palette[15]);
  5512. for (i = 0; i < count; i++) {
  5513. palette[i] = rgb_to_yuv(palette[i]);
  5514. }
  5515. have_palette = 1;
  5516. } else if (!strncmp("size:", cur, 5)) {
  5517. sscanf(cur + 5, "%dx%d", &width, &height);
  5518. have_size = 1;
  5519. }
  5520. if (have_palette && have_size)
  5521. break;
  5522. cur += strcspn(cur, "\n\r");
  5523. cur += strspn(cur, "\n\r");
  5524. }
  5525. if (have_palette) {
  5526. track->vos_data = av_malloc(16*4 + AV_INPUT_BUFFER_PADDING_SIZE);
  5527. if (!track->vos_data)
  5528. return AVERROR(ENOMEM);
  5529. for (i = 0; i < 16; i++) {
  5530. AV_WB32(track->vos_data + i * 4, palette[i]);
  5531. }
  5532. memset(track->vos_data + 16*4, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  5533. track->vos_len = 16 * 4;
  5534. }
  5535. st->codecpar->width = width;
  5536. st->codecpar->height = track->height = height;
  5537. return 0;
  5538. }
  5539. static int mov_init(AVFormatContext *s)
  5540. {
  5541. MOVMuxContext *mov = s->priv_data;
  5542. AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  5543. int i, ret;
  5544. mov->fc = s;
  5545. /* Default mode == MP4 */
  5546. mov->mode = MODE_MP4;
  5547. if (s->oformat) {
  5548. if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
  5549. else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
  5550. else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
  5551. else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
  5552. else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
  5553. else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
  5554. else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
  5555. }
  5556. if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
  5557. mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
  5558. /* Set the FRAGMENT flag if any of the fragmentation methods are
  5559. * enabled. */
  5560. if (mov->max_fragment_duration || mov->max_fragment_size ||
  5561. mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
  5562. FF_MOV_FLAG_FRAG_KEYFRAME |
  5563. FF_MOV_FLAG_FRAG_CUSTOM |
  5564. FF_MOV_FLAG_FRAG_EVERY_FRAME))
  5565. mov->flags |= FF_MOV_FLAG_FRAGMENT;
  5566. /* Set other implicit flags immediately */
  5567. if (mov->mode == MODE_ISM)
  5568. mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
  5569. FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
  5570. if (mov->flags & FF_MOV_FLAG_DASH)
  5571. mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
  5572. FF_MOV_FLAG_DEFAULT_BASE_MOOF;
  5573. if (mov->flags & FF_MOV_FLAG_CMAF)
  5574. mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
  5575. FF_MOV_FLAG_DEFAULT_BASE_MOOF | FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
  5576. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
  5577. av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
  5578. s->flags &= ~AVFMT_FLAG_AUTO_BSF;
  5579. }
  5580. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX && mov->flags & FF_MOV_FLAG_SKIP_SIDX) {
  5581. av_log(s, AV_LOG_WARNING, "Global SIDX enabled; Ignoring skip_sidx option\n");
  5582. mov->flags &= ~FF_MOV_FLAG_SKIP_SIDX;
  5583. }
  5584. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  5585. mov->reserved_moov_size = -1;
  5586. }
  5587. if (mov->use_editlist < 0) {
  5588. mov->use_editlist = 1;
  5589. if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
  5590. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  5591. // If we can avoid needing an edit list by shifting the
  5592. // tracks, prefer that over (trying to) write edit lists
  5593. // in fragmented output.
  5594. if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
  5595. s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
  5596. mov->use_editlist = 0;
  5597. }
  5598. if (mov->flags & FF_MOV_FLAG_CMAF) {
  5599. // CMAF Track requires negative cts offsets without edit lists
  5600. mov->use_editlist = 0;
  5601. }
  5602. }
  5603. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
  5604. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
  5605. av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
  5606. if (mov->flags & FF_MOV_FLAG_CMAF && mov->use_editlist) {
  5607. av_log(s, AV_LOG_WARNING, "Edit list enabled; Assuming writing CMAF Track File\n");
  5608. mov->flags &= ~FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS;
  5609. }
  5610. if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO &&
  5611. !(mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS))
  5612. s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
  5613. /* Clear the omit_tfhd_offset flag if default_base_moof is set;
  5614. * if the latter is set that's enough and omit_tfhd_offset doesn't
  5615. * add anything extra on top of that. */
  5616. if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
  5617. mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
  5618. mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
  5619. if (mov->frag_interleave &&
  5620. mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
  5621. av_log(s, AV_LOG_ERROR,
  5622. "Sample interleaving in fragments is mutually exclusive with "
  5623. "omit_tfhd_offset and separate_moof\n");
  5624. return AVERROR(EINVAL);
  5625. }
  5626. /* Non-seekable output is ok if using fragmentation. If ism_lookahead
  5627. * is enabled, we don't support non-seekable output at all. */
  5628. if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
  5629. (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
  5630. av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
  5631. return AVERROR(EINVAL);
  5632. }
  5633. mov->nb_streams = s->nb_streams;
  5634. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
  5635. mov->chapter_track = mov->nb_streams++;
  5636. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  5637. for (i = 0; i < s->nb_streams; i++)
  5638. if (rtp_hinting_needed(s->streams[i]))
  5639. mov->nb_streams++;
  5640. }
  5641. if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
  5642. || mov->write_tmcd == 1) {
  5643. /* +1 tmcd track for each video stream with a timecode */
  5644. for (i = 0; i < s->nb_streams; i++) {
  5645. AVStream *st = s->streams[i];
  5646. AVDictionaryEntry *t = global_tcr;
  5647. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  5648. (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
  5649. AVTimecode tc;
  5650. ret = mov_check_timecode_track(s, &tc, i, t->value);
  5651. if (ret >= 0)
  5652. mov->nb_meta_tmcd++;
  5653. }
  5654. }
  5655. /* check if there is already a tmcd track to remux */
  5656. if (mov->nb_meta_tmcd) {
  5657. for (i = 0; i < s->nb_streams; i++) {
  5658. AVStream *st = s->streams[i];
  5659. if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
  5660. av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
  5661. "so timecode metadata are now ignored\n");
  5662. mov->nb_meta_tmcd = 0;
  5663. }
  5664. }
  5665. }
  5666. mov->nb_streams += mov->nb_meta_tmcd;
  5667. }
  5668. // Reserve an extra stream for chapters for the case where chapters
  5669. // are written in the trailer
  5670. mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
  5671. if (!mov->tracks)
  5672. return AVERROR(ENOMEM);
  5673. if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
  5674. if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
  5675. mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
  5676. if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
  5677. av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
  5678. mov->encryption_key_len, AES_CTR_KEY_SIZE);
  5679. return AVERROR(EINVAL);
  5680. }
  5681. if (mov->encryption_kid_len != CENC_KID_SIZE) {
  5682. av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
  5683. mov->encryption_kid_len, CENC_KID_SIZE);
  5684. return AVERROR(EINVAL);
  5685. }
  5686. } else {
  5687. av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
  5688. mov->encryption_scheme_str);
  5689. return AVERROR(EINVAL);
  5690. }
  5691. }
  5692. for (i = 0; i < s->nb_streams; i++) {
  5693. AVStream *st= s->streams[i];
  5694. MOVTrack *track= &mov->tracks[i];
  5695. AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
  5696. track->st = st;
  5697. track->par = st->codecpar;
  5698. track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
  5699. if (track->language < 0)
  5700. track->language = 32767; // Unspecified Macintosh language code
  5701. track->mode = mov->mode;
  5702. track->tag = mov_find_codec_tag(s, track);
  5703. if (!track->tag) {
  5704. av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
  5705. "codec not currently supported in container\n",
  5706. avcodec_get_name(st->codecpar->codec_id), i);
  5707. return AVERROR(EINVAL);
  5708. }
  5709. /* If hinting of this track is enabled by a later hint track,
  5710. * this is updated. */
  5711. track->hint_track = -1;
  5712. track->start_dts = AV_NOPTS_VALUE;
  5713. track->start_cts = AV_NOPTS_VALUE;
  5714. track->end_pts = AV_NOPTS_VALUE;
  5715. track->dts_shift = AV_NOPTS_VALUE;
  5716. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  5717. if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
  5718. track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
  5719. track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
  5720. if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
  5721. av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
  5722. return AVERROR(EINVAL);
  5723. }
  5724. track->height = track->tag >> 24 == 'n' ? 486 : 576;
  5725. }
  5726. if (mov->video_track_timescale) {
  5727. track->timescale = mov->video_track_timescale;
  5728. if (mov->mode == MODE_ISM && mov->video_track_timescale != 10000000)
  5729. av_log(s, AV_LOG_WARNING, "Warning: some tools, like mp4split, assume a timescale of 10000000 for ISMV.\n");
  5730. } else {
  5731. track->timescale = st->time_base.den;
  5732. while(track->timescale < 10000)
  5733. track->timescale *= 2;
  5734. }
  5735. if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
  5736. av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
  5737. return AVERROR(EINVAL);
  5738. }
  5739. if (track->mode == MODE_MOV && track->timescale > 100000)
  5740. av_log(s, AV_LOG_WARNING,
  5741. "WARNING codec timebase is very high. If duration is too long,\n"
  5742. "file may not be playable by quicktime. Specify a shorter timebase\n"
  5743. "or choose different container.\n");
  5744. if (track->mode == MODE_MOV &&
  5745. track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
  5746. track->tag == MKTAG('r','a','w',' ')) {
  5747. enum AVPixelFormat pix_fmt = track->par->format;
  5748. if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
  5749. pix_fmt = AV_PIX_FMT_MONOWHITE;
  5750. track->is_unaligned_qt_rgb =
  5751. pix_fmt == AV_PIX_FMT_RGB24 ||
  5752. pix_fmt == AV_PIX_FMT_BGR24 ||
  5753. pix_fmt == AV_PIX_FMT_PAL8 ||
  5754. pix_fmt == AV_PIX_FMT_GRAY8 ||
  5755. pix_fmt == AV_PIX_FMT_MONOWHITE ||
  5756. pix_fmt == AV_PIX_FMT_MONOBLACK;
  5757. }
  5758. if (track->par->codec_id == AV_CODEC_ID_VP9 ||
  5759. track->par->codec_id == AV_CODEC_ID_AV1) {
  5760. if (track->mode != MODE_MP4) {
  5761. av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
  5762. return AVERROR(EINVAL);
  5763. }
  5764. } else if (track->par->codec_id == AV_CODEC_ID_VP8) {
  5765. /* altref frames handling is not defined in the spec as of version v1.0,
  5766. * so just forbid muxing VP8 streams altogether until a new version does */
  5767. av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
  5768. return AVERROR_PATCHWELCOME;
  5769. }
  5770. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  5771. track->timescale = st->codecpar->sample_rate;
  5772. if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
  5773. av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
  5774. track->audio_vbr = 1;
  5775. }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
  5776. st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
  5777. st->codecpar->codec_id == AV_CODEC_ID_ILBC){
  5778. if (!st->codecpar->block_align) {
  5779. av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
  5780. return AVERROR(EINVAL);
  5781. }
  5782. track->sample_size = st->codecpar->block_align;
  5783. }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
  5784. track->audio_vbr = 1;
  5785. }else{
  5786. track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
  5787. }
  5788. if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
  5789. st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
  5790. track->audio_vbr = 1;
  5791. }
  5792. if (track->mode != MODE_MOV &&
  5793. track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
  5794. if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
  5795. av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
  5796. i, track->par->sample_rate);
  5797. return AVERROR(EINVAL);
  5798. } else {
  5799. av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
  5800. i, track->par->sample_rate);
  5801. }
  5802. }
  5803. if (track->par->codec_id == AV_CODEC_ID_FLAC ||
  5804. track->par->codec_id == AV_CODEC_ID_TRUEHD ||
  5805. track->par->codec_id == AV_CODEC_ID_OPUS) {
  5806. if (track->mode != MODE_MP4) {
  5807. av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
  5808. return AVERROR(EINVAL);
  5809. }
  5810. if (track->par->codec_id != AV_CODEC_ID_OPUS &&
  5811. s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  5812. av_log(s, AV_LOG_ERROR,
  5813. "%s in MP4 support is experimental, add "
  5814. "'-strict %d' if you want to use it.\n",
  5815. avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
  5816. return AVERROR_EXPERIMENTAL;
  5817. }
  5818. }
  5819. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  5820. track->timescale = st->time_base.den;
  5821. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
  5822. track->timescale = st->time_base.den;
  5823. } else {
  5824. track->timescale = MOV_TIMESCALE;
  5825. }
  5826. if (!track->height)
  5827. track->height = st->codecpar->height;
  5828. /* The Protected Interoperable File Format (PIFF) standard, used by ISMV recommends but
  5829. doesn't mandate a track timescale of 10,000,000. The muxer allows a custom timescale
  5830. for video tracks, so if user-set, it isn't overwritten */
  5831. if (mov->mode == MODE_ISM &&
  5832. (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ||
  5833. (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !mov->video_track_timescale))) {
  5834. track->timescale = 10000000;
  5835. }
  5836. avpriv_set_pts_info(st, 64, 1, track->timescale);
  5837. if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
  5838. ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
  5839. track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
  5840. if (ret)
  5841. return ret;
  5842. }
  5843. }
  5844. enable_tracks(s);
  5845. return 0;
  5846. }
  5847. static int mov_write_header(AVFormatContext *s)
  5848. {
  5849. AVIOContext *pb = s->pb;
  5850. MOVMuxContext *mov = s->priv_data;
  5851. AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
  5852. int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
  5853. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
  5854. nb_tracks++;
  5855. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  5856. hint_track = nb_tracks;
  5857. for (i = 0; i < s->nb_streams; i++)
  5858. if (rtp_hinting_needed(s->streams[i]))
  5859. nb_tracks++;
  5860. }
  5861. if (mov->nb_meta_tmcd)
  5862. tmcd_track = nb_tracks;
  5863. for (i = 0; i < s->nb_streams; i++) {
  5864. int j;
  5865. AVStream *st= s->streams[i];
  5866. MOVTrack *track= &mov->tracks[i];
  5867. /* copy extradata if it exists */
  5868. if (st->codecpar->extradata_size) {
  5869. if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
  5870. mov_create_dvd_sub_decoder_specific_info(track, st);
  5871. else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
  5872. track->vos_len = st->codecpar->extradata_size;
  5873. track->vos_data = av_malloc(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
  5874. if (!track->vos_data) {
  5875. return AVERROR(ENOMEM);
  5876. }
  5877. memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
  5878. memset(track->vos_data + track->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  5879. }
  5880. }
  5881. if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
  5882. track->par->channel_layout != AV_CH_LAYOUT_MONO)
  5883. continue;
  5884. for (j = 0; j < s->nb_streams; j++) {
  5885. AVStream *stj= s->streams[j];
  5886. MOVTrack *trackj= &mov->tracks[j];
  5887. if (j == i)
  5888. continue;
  5889. if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
  5890. trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
  5891. trackj->language != track->language ||
  5892. trackj->tag != track->tag
  5893. )
  5894. continue;
  5895. track->multichannel_as_mono++;
  5896. }
  5897. }
  5898. if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  5899. if ((ret = mov_write_identification(pb, s)) < 0)
  5900. return ret;
  5901. }
  5902. if (mov->reserved_moov_size){
  5903. mov->reserved_header_pos = avio_tell(pb);
  5904. if (mov->reserved_moov_size > 0)
  5905. avio_skip(pb, mov->reserved_moov_size);
  5906. }
  5907. if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
  5908. /* If no fragmentation options have been set, set a default. */
  5909. if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
  5910. FF_MOV_FLAG_FRAG_CUSTOM |
  5911. FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
  5912. !mov->max_fragment_duration && !mov->max_fragment_size)
  5913. mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
  5914. } else {
  5915. if (mov->flags & FF_MOV_FLAG_FASTSTART)
  5916. mov->reserved_header_pos = avio_tell(pb);
  5917. mov_write_mdat_tag(pb, mov);
  5918. }
  5919. ff_parse_creation_time_metadata(s, &mov->time, 1);
  5920. if (mov->time)
  5921. mov->time += 0x7C25B080; // 1970 based -> 1904 based
  5922. if (mov->chapter_track)
  5923. if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  5924. return ret;
  5925. if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
  5926. for (i = 0; i < s->nb_streams; i++) {
  5927. if (rtp_hinting_needed(s->streams[i])) {
  5928. if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
  5929. return ret;
  5930. hint_track++;
  5931. }
  5932. }
  5933. }
  5934. if (mov->nb_meta_tmcd) {
  5935. /* Initialize the tmcd tracks */
  5936. for (i = 0; i < s->nb_streams; i++) {
  5937. AVStream *st = s->streams[i];
  5938. t = global_tcr;
  5939. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  5940. AVTimecode tc;
  5941. if (!t)
  5942. t = av_dict_get(st->metadata, "timecode", NULL, 0);
  5943. if (!t)
  5944. continue;
  5945. if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
  5946. continue;
  5947. if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
  5948. return ret;
  5949. tmcd_track++;
  5950. }
  5951. }
  5952. }
  5953. avio_flush(pb);
  5954. if (mov->flags & FF_MOV_FLAG_ISML)
  5955. mov_write_isml_manifest(pb, mov, s);
  5956. if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
  5957. !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
  5958. if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
  5959. return ret;
  5960. mov->moov_written = 1;
  5961. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
  5962. mov->reserved_header_pos = avio_tell(pb);
  5963. }
  5964. return 0;
  5965. }
  5966. static int get_moov_size(AVFormatContext *s)
  5967. {
  5968. int ret;
  5969. AVIOContext *moov_buf;
  5970. MOVMuxContext *mov = s->priv_data;
  5971. if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
  5972. return ret;
  5973. if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
  5974. return ret;
  5975. return ffio_close_null_buf(moov_buf);
  5976. }
  5977. static int get_sidx_size(AVFormatContext *s)
  5978. {
  5979. int ret;
  5980. AVIOContext *buf;
  5981. MOVMuxContext *mov = s->priv_data;
  5982. if ((ret = ffio_open_null_buf(&buf)) < 0)
  5983. return ret;
  5984. mov_write_sidx_tags(buf, mov, -1, 0);
  5985. return ffio_close_null_buf(buf);
  5986. }
  5987. /*
  5988. * This function gets the moov size if moved to the top of the file: the chunk
  5989. * offset table can switch between stco (32-bit entries) to co64 (64-bit
  5990. * entries) when the moov is moved to the beginning, so the size of the moov
  5991. * would change. It also updates the chunk offset tables.
  5992. */
  5993. static int compute_moov_size(AVFormatContext *s)
  5994. {
  5995. int i, moov_size, moov_size2;
  5996. MOVMuxContext *mov = s->priv_data;
  5997. moov_size = get_moov_size(s);
  5998. if (moov_size < 0)
  5999. return moov_size;
  6000. for (i = 0; i < mov->nb_streams; i++)
  6001. mov->tracks[i].data_offset += moov_size;
  6002. moov_size2 = get_moov_size(s);
  6003. if (moov_size2 < 0)
  6004. return moov_size2;
  6005. /* if the size changed, we just switched from stco to co64 and need to
  6006. * update the offsets */
  6007. if (moov_size2 != moov_size)
  6008. for (i = 0; i < mov->nb_streams; i++)
  6009. mov->tracks[i].data_offset += moov_size2 - moov_size;
  6010. return moov_size2;
  6011. }
  6012. static int compute_sidx_size(AVFormatContext *s)
  6013. {
  6014. int i, sidx_size;
  6015. MOVMuxContext *mov = s->priv_data;
  6016. sidx_size = get_sidx_size(s);
  6017. if (sidx_size < 0)
  6018. return sidx_size;
  6019. for (i = 0; i < mov->nb_streams; i++)
  6020. mov->tracks[i].data_offset += sidx_size;
  6021. return sidx_size;
  6022. }
  6023. static int shift_data(AVFormatContext *s)
  6024. {
  6025. int ret = 0, moov_size;
  6026. MOVMuxContext *mov = s->priv_data;
  6027. int64_t pos, pos_end;
  6028. uint8_t *buf, *read_buf[2];
  6029. int read_buf_id = 0;
  6030. int read_size[2];
  6031. AVIOContext *read_pb;
  6032. if (mov->flags & FF_MOV_FLAG_FRAGMENT)
  6033. moov_size = compute_sidx_size(s);
  6034. else
  6035. moov_size = compute_moov_size(s);
  6036. if (moov_size < 0)
  6037. return moov_size;
  6038. buf = av_malloc(moov_size * 2);
  6039. if (!buf)
  6040. return AVERROR(ENOMEM);
  6041. read_buf[0] = buf;
  6042. read_buf[1] = buf + moov_size;
  6043. /* Shift the data: the AVIO context of the output can only be used for
  6044. * writing, so we re-open the same output, but for reading. It also avoids
  6045. * a read/seek/write/seek back and forth. */
  6046. avio_flush(s->pb);
  6047. ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
  6048. if (ret < 0) {
  6049. av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
  6050. "the second pass (faststart)\n", s->url);
  6051. goto end;
  6052. }
  6053. /* mark the end of the shift to up to the last data we wrote, and get ready
  6054. * for writing */
  6055. pos_end = avio_tell(s->pb);
  6056. avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
  6057. /* start reading at where the new moov will be placed */
  6058. avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
  6059. pos = avio_tell(read_pb);
  6060. #define READ_BLOCK do { \
  6061. read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
  6062. read_buf_id ^= 1; \
  6063. } while (0)
  6064. /* shift data by chunk of at most moov_size */
  6065. READ_BLOCK;
  6066. do {
  6067. int n;
  6068. READ_BLOCK;
  6069. n = read_size[read_buf_id];
  6070. if (n <= 0)
  6071. break;
  6072. avio_write(s->pb, read_buf[read_buf_id], n);
  6073. pos += n;
  6074. } while (pos < pos_end);
  6075. ff_format_io_close(s, &read_pb);
  6076. end:
  6077. av_free(buf);
  6078. return ret;
  6079. }
  6080. static int mov_write_trailer(AVFormatContext *s)
  6081. {
  6082. MOVMuxContext *mov = s->priv_data;
  6083. AVIOContext *pb = s->pb;
  6084. int res = 0;
  6085. int i;
  6086. int64_t moov_pos;
  6087. if (mov->need_rewrite_extradata) {
  6088. for (i = 0; i < s->nb_streams; i++) {
  6089. MOVTrack *track = &mov->tracks[i];
  6090. AVCodecParameters *par = track->par;
  6091. track->vos_len = par->extradata_size;
  6092. track->vos_data = av_malloc(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
  6093. if (!track->vos_data)
  6094. return AVERROR(ENOMEM);
  6095. memcpy(track->vos_data, par->extradata, track->vos_len);
  6096. memset(track->vos_data + track->vos_len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  6097. }
  6098. mov->need_rewrite_extradata = 0;
  6099. }
  6100. /*
  6101. * Before actually writing the trailer, make sure that there are no
  6102. * dangling subtitles, that need a terminating sample.
  6103. */
  6104. for (i = 0; i < mov->nb_streams; i++) {
  6105. MOVTrack *trk = &mov->tracks[i];
  6106. if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
  6107. !trk->last_sample_is_subtitle_end) {
  6108. mov_write_subtitle_end_packet(s, i, trk->track_duration);
  6109. trk->last_sample_is_subtitle_end = 1;
  6110. }
  6111. }
  6112. // If there were no chapters when the header was written, but there
  6113. // are chapters now, write them in the trailer. This only works
  6114. // when we are not doing fragments.
  6115. if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  6116. if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
  6117. mov->chapter_track = mov->nb_streams++;
  6118. if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
  6119. return res;
  6120. }
  6121. }
  6122. if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
  6123. moov_pos = avio_tell(pb);
  6124. /* Write size of mdat tag */
  6125. if (mov->mdat_size + 8 <= UINT32_MAX) {
  6126. avio_seek(pb, mov->mdat_pos, SEEK_SET);
  6127. avio_wb32(pb, mov->mdat_size + 8);
  6128. } else {
  6129. /* overwrite 'wide' placeholder atom */
  6130. avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
  6131. /* special value: real atom size will be 64 bit value after
  6132. * tag field */
  6133. avio_wb32(pb, 1);
  6134. ffio_wfourcc(pb, "mdat");
  6135. avio_wb64(pb, mov->mdat_size + 16);
  6136. }
  6137. avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
  6138. if (mov->flags & FF_MOV_FLAG_FASTSTART) {
  6139. av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
  6140. res = shift_data(s);
  6141. if (res < 0)
  6142. return res;
  6143. avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
  6144. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  6145. return res;
  6146. } else if (mov->reserved_moov_size > 0) {
  6147. int64_t size;
  6148. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  6149. return res;
  6150. size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
  6151. if (size < 8){
  6152. av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
  6153. return AVERROR(EINVAL);
  6154. }
  6155. avio_wb32(pb, size);
  6156. ffio_wfourcc(pb, "free");
  6157. ffio_fill(pb, 0, size - 8);
  6158. avio_seek(pb, moov_pos, SEEK_SET);
  6159. } else {
  6160. if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
  6161. return res;
  6162. }
  6163. res = 0;
  6164. } else {
  6165. mov_auto_flush_fragment(s, 1);
  6166. for (i = 0; i < mov->nb_streams; i++)
  6167. mov->tracks[i].data_offset = 0;
  6168. if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
  6169. int64_t end;
  6170. av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
  6171. res = shift_data(s);
  6172. if (res < 0)
  6173. return res;
  6174. end = avio_tell(pb);
  6175. avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
  6176. mov_write_sidx_tags(pb, mov, -1, 0);
  6177. avio_seek(pb, end, SEEK_SET);
  6178. }
  6179. if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
  6180. avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
  6181. mov_write_mfra_tag(pb, mov);
  6182. }
  6183. }
  6184. return res;
  6185. }
  6186. static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
  6187. {
  6188. int ret = 1;
  6189. AVStream *st = s->streams[pkt->stream_index];
  6190. if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
  6191. if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
  6192. ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
  6193. } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
  6194. ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
  6195. }
  6196. return ret;
  6197. }
  6198. static const AVCodecTag codec_3gp_tags[] = {
  6199. { AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
  6200. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  6201. { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
  6202. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  6203. { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
  6204. { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
  6205. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
  6206. { AV_CODEC_ID_NONE, 0 },
  6207. };
  6208. const AVCodecTag codec_mp4_tags[] = {
  6209. { AV_CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
  6210. { AV_CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') },
  6211. { AV_CODEC_ID_H264, MKTAG('a', 'v', 'c', '3') },
  6212. { AV_CODEC_ID_HEVC, MKTAG('h', 'e', 'v', '1') },
  6213. { AV_CODEC_ID_HEVC, MKTAG('h', 'v', 'c', '1') },
  6214. { AV_CODEC_ID_MPEG2VIDEO, MKTAG('m', 'p', '4', 'v') },
  6215. { AV_CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', '4', 'v') },
  6216. { AV_CODEC_ID_MJPEG, MKTAG('m', 'p', '4', 'v') },
  6217. { AV_CODEC_ID_PNG, MKTAG('m', 'p', '4', 'v') },
  6218. { AV_CODEC_ID_JPEG2000, MKTAG('m', 'p', '4', 'v') },
  6219. { AV_CODEC_ID_VC1, MKTAG('v', 'c', '-', '1') },
  6220. { AV_CODEC_ID_DIRAC, MKTAG('d', 'r', 'a', 'c') },
  6221. { AV_CODEC_ID_TSCC2, MKTAG('m', 'p', '4', 'v') },
  6222. { AV_CODEC_ID_VP9, MKTAG('v', 'p', '0', '9') },
  6223. { AV_CODEC_ID_AV1, MKTAG('a', 'v', '0', '1') },
  6224. { AV_CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') },
  6225. { AV_CODEC_ID_MP4ALS, MKTAG('m', 'p', '4', 'a') },
  6226. { AV_CODEC_ID_MP3, MKTAG('m', 'p', '4', 'a') },
  6227. { AV_CODEC_ID_MP2, MKTAG('m', 'p', '4', 'a') },
  6228. { AV_CODEC_ID_AC3, MKTAG('a', 'c', '-', '3') },
  6229. { AV_CODEC_ID_EAC3, MKTAG('e', 'c', '-', '3') },
  6230. { AV_CODEC_ID_DTS, MKTAG('m', 'p', '4', 'a') },
  6231. { AV_CODEC_ID_TRUEHD, MKTAG('m', 'l', 'p', 'a') },
  6232. { AV_CODEC_ID_FLAC, MKTAG('f', 'L', 'a', 'C') },
  6233. { AV_CODEC_ID_OPUS, MKTAG('O', 'p', 'u', 's') },
  6234. { AV_CODEC_ID_VORBIS, MKTAG('m', 'p', '4', 'a') },
  6235. { AV_CODEC_ID_QCELP, MKTAG('m', 'p', '4', 'a') },
  6236. { AV_CODEC_ID_EVRC, MKTAG('m', 'p', '4', 'a') },
  6237. { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
  6238. { AV_CODEC_ID_MOV_TEXT, MKTAG('t', 'x', '3', 'g') },
  6239. { AV_CODEC_ID_BIN_DATA, MKTAG('g', 'p', 'm', 'd') },
  6240. { AV_CODEC_ID_MPEGH_3D_AUDIO, MKTAG('m', 'h', 'm', '1') },
  6241. { AV_CODEC_ID_NONE, 0 },
  6242. };
  6243. const AVCodecTag codec_ism_tags[] = {
  6244. { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
  6245. { AV_CODEC_ID_NONE , 0 },
  6246. };
  6247. static const AVCodecTag codec_ipod_tags[] = {
  6248. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  6249. { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
  6250. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  6251. { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
  6252. { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
  6253. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
  6254. { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
  6255. { AV_CODEC_ID_NONE, 0 },
  6256. };
  6257. static const AVCodecTag codec_f4v_tags[] = {
  6258. { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
  6259. { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
  6260. { AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
  6261. { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
  6262. { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
  6263. { AV_CODEC_ID_NONE, 0 },
  6264. };
  6265. #if CONFIG_MOV_MUXER
  6266. MOV_CLASS(mov)
  6267. AVOutputFormat ff_mov_muxer = {
  6268. .name = "mov",
  6269. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  6270. .extensions = "mov",
  6271. .priv_data_size = sizeof(MOVMuxContext),
  6272. .audio_codec = AV_CODEC_ID_AAC,
  6273. .video_codec = CONFIG_LIBX264_ENCODER ?
  6274. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  6275. .init = mov_init,
  6276. .write_header = mov_write_header,
  6277. .write_packet = mov_write_packet,
  6278. .write_trailer = mov_write_trailer,
  6279. .deinit = mov_free,
  6280. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6281. .codec_tag = (const AVCodecTag* const []){
  6282. ff_codec_movvideo_tags, ff_codec_movaudio_tags, ff_codec_movsubtitle_tags, 0
  6283. },
  6284. .check_bitstream = mov_check_bitstream,
  6285. .priv_class = &mov_muxer_class,
  6286. };
  6287. #endif
  6288. #if CONFIG_TGP_MUXER
  6289. MOV_CLASS(tgp)
  6290. AVOutputFormat ff_tgp_muxer = {
  6291. .name = "3gp",
  6292. .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
  6293. .extensions = "3gp",
  6294. .priv_data_size = sizeof(MOVMuxContext),
  6295. .audio_codec = AV_CODEC_ID_AMR_NB,
  6296. .video_codec = AV_CODEC_ID_H263,
  6297. .init = mov_init,
  6298. .write_header = mov_write_header,
  6299. .write_packet = mov_write_packet,
  6300. .write_trailer = mov_write_trailer,
  6301. .deinit = mov_free,
  6302. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6303. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  6304. .check_bitstream = mov_check_bitstream,
  6305. .priv_class = &tgp_muxer_class,
  6306. };
  6307. #endif
  6308. #if CONFIG_MP4_MUXER
  6309. MOV_CLASS(mp4)
  6310. AVOutputFormat ff_mp4_muxer = {
  6311. .name = "mp4",
  6312. .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
  6313. .mime_type = "video/mp4",
  6314. .extensions = "mp4",
  6315. .priv_data_size = sizeof(MOVMuxContext),
  6316. .audio_codec = AV_CODEC_ID_AAC,
  6317. .video_codec = CONFIG_LIBX264_ENCODER ?
  6318. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  6319. .init = mov_init,
  6320. .write_header = mov_write_header,
  6321. .write_packet = mov_write_packet,
  6322. .write_trailer = mov_write_trailer,
  6323. .deinit = mov_free,
  6324. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6325. .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
  6326. .check_bitstream = mov_check_bitstream,
  6327. .priv_class = &mp4_muxer_class,
  6328. };
  6329. #endif
  6330. #if CONFIG_PSP_MUXER
  6331. MOV_CLASS(psp)
  6332. AVOutputFormat ff_psp_muxer = {
  6333. .name = "psp",
  6334. .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
  6335. .extensions = "mp4,psp",
  6336. .priv_data_size = sizeof(MOVMuxContext),
  6337. .audio_codec = AV_CODEC_ID_AAC,
  6338. .video_codec = CONFIG_LIBX264_ENCODER ?
  6339. AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
  6340. .init = mov_init,
  6341. .write_header = mov_write_header,
  6342. .write_packet = mov_write_packet,
  6343. .write_trailer = mov_write_trailer,
  6344. .deinit = mov_free,
  6345. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6346. .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
  6347. .check_bitstream = mov_check_bitstream,
  6348. .priv_class = &psp_muxer_class,
  6349. };
  6350. #endif
  6351. #if CONFIG_TG2_MUXER
  6352. MOV_CLASS(tg2)
  6353. AVOutputFormat ff_tg2_muxer = {
  6354. .name = "3g2",
  6355. .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
  6356. .extensions = "3g2",
  6357. .priv_data_size = sizeof(MOVMuxContext),
  6358. .audio_codec = AV_CODEC_ID_AMR_NB,
  6359. .video_codec = AV_CODEC_ID_H263,
  6360. .init = mov_init,
  6361. .write_header = mov_write_header,
  6362. .write_packet = mov_write_packet,
  6363. .write_trailer = mov_write_trailer,
  6364. .deinit = mov_free,
  6365. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6366. .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
  6367. .check_bitstream = mov_check_bitstream,
  6368. .priv_class = &tg2_muxer_class,
  6369. };
  6370. #endif
  6371. #if CONFIG_IPOD_MUXER
  6372. MOV_CLASS(ipod)
  6373. AVOutputFormat ff_ipod_muxer = {
  6374. .name = "ipod",
  6375. .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
  6376. .mime_type = "video/mp4",
  6377. .extensions = "m4v,m4a,m4b",
  6378. .priv_data_size = sizeof(MOVMuxContext),
  6379. .audio_codec = AV_CODEC_ID_AAC,
  6380. .video_codec = AV_CODEC_ID_H264,
  6381. .init = mov_init,
  6382. .write_header = mov_write_header,
  6383. .write_packet = mov_write_packet,
  6384. .write_trailer = mov_write_trailer,
  6385. .deinit = mov_free,
  6386. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6387. .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
  6388. .check_bitstream = mov_check_bitstream,
  6389. .priv_class = &ipod_muxer_class,
  6390. };
  6391. #endif
  6392. #if CONFIG_ISMV_MUXER
  6393. MOV_CLASS(ismv)
  6394. AVOutputFormat ff_ismv_muxer = {
  6395. .name = "ismv",
  6396. .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
  6397. .mime_type = "video/mp4",
  6398. .extensions = "ismv,isma",
  6399. .priv_data_size = sizeof(MOVMuxContext),
  6400. .audio_codec = AV_CODEC_ID_AAC,
  6401. .video_codec = AV_CODEC_ID_H264,
  6402. .init = mov_init,
  6403. .write_header = mov_write_header,
  6404. .write_packet = mov_write_packet,
  6405. .write_trailer = mov_write_trailer,
  6406. .deinit = mov_free,
  6407. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
  6408. .codec_tag = (const AVCodecTag* const []){
  6409. codec_mp4_tags, codec_ism_tags, 0 },
  6410. .check_bitstream = mov_check_bitstream,
  6411. .priv_class = &ismv_muxer_class,
  6412. };
  6413. #endif
  6414. #if CONFIG_F4V_MUXER
  6415. MOV_CLASS(f4v)
  6416. AVOutputFormat ff_f4v_muxer = {
  6417. .name = "f4v",
  6418. .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
  6419. .mime_type = "application/f4v",
  6420. .extensions = "f4v",
  6421. .priv_data_size = sizeof(MOVMuxContext),
  6422. .audio_codec = AV_CODEC_ID_AAC,
  6423. .video_codec = AV_CODEC_ID_H264,
  6424. .init = mov_init,
  6425. .write_header = mov_write_header,
  6426. .write_packet = mov_write_packet,
  6427. .write_trailer = mov_write_trailer,
  6428. .deinit = mov_free,
  6429. .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
  6430. .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
  6431. .check_bitstream = mov_check_bitstream,
  6432. .priv_class = &f4v_muxer_class,
  6433. };
  6434. #endif