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.

7120 lines
260KB

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