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.

7017 lines
255KB

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