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.

6983 lines
253KB

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