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.

7978 lines
274KB

  1. /*
  2. * MOV demuxer
  3. * Copyright (c) 2001 Fabrice Bellard
  4. * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  5. *
  6. * first version by Francois Revol <revol@free.fr>
  7. * seek function by Gael Chardon <gael.dev@4now.net>
  8. *
  9. * This file is part of FFmpeg.
  10. *
  11. * FFmpeg is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU Lesser General Public
  13. * License as published by the Free Software Foundation; either
  14. * version 2.1 of the License, or (at your option) any later version.
  15. *
  16. * FFmpeg is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  19. * Lesser General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Lesser General Public
  22. * License along with FFmpeg; if not, write to the Free Software
  23. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24. */
  25. #include <inttypes.h>
  26. #include <limits.h>
  27. #include <stdint.h>
  28. #include "libavutil/attributes.h"
  29. #include "libavutil/channel_layout.h"
  30. #include "libavutil/internal.h"
  31. #include "libavutil/intreadwrite.h"
  32. #include "libavutil/intfloat.h"
  33. #include "libavutil/mathematics.h"
  34. #include "libavutil/time_internal.h"
  35. #include "libavutil/avassert.h"
  36. #include "libavutil/avstring.h"
  37. #include "libavutil/dict.h"
  38. #include "libavutil/display.h"
  39. #include "libavutil/opt.h"
  40. #include "libavutil/aes.h"
  41. #include "libavutil/aes_ctr.h"
  42. #include "libavutil/pixdesc.h"
  43. #include "libavutil/sha.h"
  44. #include "libavutil/spherical.h"
  45. #include "libavutil/stereo3d.h"
  46. #include "libavutil/timecode.h"
  47. #include "libavcodec/ac3tab.h"
  48. #include "libavcodec/flac.h"
  49. #include "libavcodec/mpegaudiodecheader.h"
  50. #include "avformat.h"
  51. #include "internal.h"
  52. #include "avio_internal.h"
  53. #include "riff.h"
  54. #include "isom.h"
  55. #include "libavcodec/get_bits.h"
  56. #include "id3v1.h"
  57. #include "mov_chan.h"
  58. #include "replaygain.h"
  59. #if CONFIG_ZLIB
  60. #include <zlib.h>
  61. #endif
  62. #include "qtpalette.h"
  63. /* those functions parse an atom */
  64. /* links atom IDs to parse functions */
  65. typedef struct MOVParseTableEntry {
  66. uint32_t type;
  67. int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
  68. } MOVParseTableEntry;
  69. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
  70. static int mov_read_mfra(MOVContext *c, AVIOContext *f);
  71. static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
  72. int count, int duration);
  73. static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
  74. unsigned len, const char *key)
  75. {
  76. char buf[16];
  77. short current, total = 0;
  78. avio_rb16(pb); // unknown
  79. current = avio_rb16(pb);
  80. if (len >= 6)
  81. total = avio_rb16(pb);
  82. if (!total)
  83. snprintf(buf, sizeof(buf), "%d", current);
  84. else
  85. snprintf(buf, sizeof(buf), "%d/%d", current, total);
  86. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  87. av_dict_set(&c->fc->metadata, key, buf, 0);
  88. return 0;
  89. }
  90. static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
  91. unsigned len, const char *key)
  92. {
  93. /* bypass padding bytes */
  94. avio_r8(pb);
  95. avio_r8(pb);
  96. avio_r8(pb);
  97. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  98. av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  99. return 0;
  100. }
  101. static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
  102. unsigned len, const char *key)
  103. {
  104. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  105. av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  106. return 0;
  107. }
  108. static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
  109. unsigned len, const char *key)
  110. {
  111. short genre;
  112. avio_r8(pb); // unknown
  113. genre = avio_r8(pb);
  114. if (genre < 1 || genre > ID3v1_GENRE_MAX)
  115. return 0;
  116. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  117. av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
  118. return 0;
  119. }
  120. static const uint32_t mac_to_unicode[128] = {
  121. 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
  122. 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
  123. 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
  124. 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
  125. 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
  126. 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
  127. 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
  128. 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
  129. 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
  130. 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
  131. 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
  132. 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
  133. 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
  134. 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
  135. 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
  136. 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
  137. };
  138. static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
  139. char *dst, int dstlen)
  140. {
  141. char *p = dst;
  142. char *end = dst+dstlen-1;
  143. int i;
  144. for (i = 0; i < len; i++) {
  145. uint8_t t, c = avio_r8(pb);
  146. if (p >= end)
  147. continue;
  148. if (c < 0x80)
  149. *p++ = c;
  150. else if (p < end)
  151. PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
  152. }
  153. *p = 0;
  154. return p - dst;
  155. }
  156. static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
  157. {
  158. AVPacket pkt;
  159. AVStream *st;
  160. MOVStreamContext *sc;
  161. enum AVCodecID id;
  162. int ret;
  163. switch (type) {
  164. case 0xd: id = AV_CODEC_ID_MJPEG; break;
  165. case 0xe: id = AV_CODEC_ID_PNG; break;
  166. case 0x1b: id = AV_CODEC_ID_BMP; break;
  167. default:
  168. av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
  169. avio_skip(pb, len);
  170. return 0;
  171. }
  172. st = avformat_new_stream(c->fc, NULL);
  173. if (!st)
  174. return AVERROR(ENOMEM);
  175. sc = av_mallocz(sizeof(*sc));
  176. if (!sc)
  177. return AVERROR(ENOMEM);
  178. st->priv_data = sc;
  179. ret = av_get_packet(pb, &pkt, len);
  180. if (ret < 0)
  181. return ret;
  182. if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
  183. if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
  184. id = AV_CODEC_ID_PNG;
  185. } else {
  186. id = AV_CODEC_ID_MJPEG;
  187. }
  188. }
  189. st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
  190. st->attached_pic = pkt;
  191. st->attached_pic.stream_index = st->index;
  192. st->attached_pic.flags |= AV_PKT_FLAG_KEY;
  193. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  194. st->codecpar->codec_id = id;
  195. return 0;
  196. }
  197. // 3GPP TS 26.244
  198. static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
  199. {
  200. char language[4] = { 0 };
  201. char buf[200], place[100];
  202. uint16_t langcode = 0;
  203. double longitude, latitude, altitude;
  204. const char *key = "location";
  205. if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
  206. av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
  207. return AVERROR_INVALIDDATA;
  208. }
  209. avio_skip(pb, 4); // version+flags
  210. langcode = avio_rb16(pb);
  211. ff_mov_lang_to_iso639(langcode, language);
  212. len -= 6;
  213. len -= avio_get_str(pb, len, place, sizeof(place));
  214. if (len < 1) {
  215. av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
  216. return AVERROR_INVALIDDATA;
  217. }
  218. avio_skip(pb, 1); // role
  219. len -= 1;
  220. if (len < 12) {
  221. av_log(c->fc, AV_LOG_ERROR,
  222. "loci too short (%u bytes left, need at least %d)\n", len, 12);
  223. return AVERROR_INVALIDDATA;
  224. }
  225. longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  226. latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  227. altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  228. // Try to output in the same format as the ?xyz field
  229. snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
  230. if (altitude)
  231. av_strlcatf(buf, sizeof(buf), "%+f", altitude);
  232. av_strlcatf(buf, sizeof(buf), "/%s", place);
  233. if (*language && strcmp(language, "und")) {
  234. char key2[16];
  235. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  236. av_dict_set(&c->fc->metadata, key2, buf, 0);
  237. }
  238. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  239. return av_dict_set(&c->fc->metadata, key, buf, 0);
  240. }
  241. static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len)
  242. {
  243. int i, n_hmmt;
  244. if (len < 2)
  245. return 0;
  246. if (c->ignore_chapters)
  247. return 0;
  248. n_hmmt = avio_rb32(pb);
  249. for (i = 0; i < n_hmmt && !pb->eof_reached; i++) {
  250. int moment_time = avio_rb32(pb);
  251. avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL);
  252. }
  253. return 0;
  254. }
  255. static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  256. {
  257. char tmp_key[5];
  258. char key2[32], language[4] = {0};
  259. char *str = NULL;
  260. const char *key = NULL;
  261. uint16_t langcode = 0;
  262. uint32_t data_type = 0, str_size, str_size_alloc;
  263. int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
  264. int raw = 0;
  265. int num = 0;
  266. switch (atom.type) {
  267. case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
  268. case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
  269. case MKTAG( 'X','M','P','_'):
  270. if (c->export_xmp) { key = "xmp"; raw = 1; } break;
  271. case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
  272. case MKTAG( 'a','k','I','D'): key = "account_type";
  273. parse = mov_metadata_int8_no_padding; break;
  274. case MKTAG( 'a','p','I','D'): key = "account_id"; break;
  275. case MKTAG( 'c','a','t','g'): key = "category"; break;
  276. case MKTAG( 'c','p','i','l'): key = "compilation";
  277. parse = mov_metadata_int8_no_padding; break;
  278. case MKTAG( 'c','p','r','t'): key = "copyright"; break;
  279. case MKTAG( 'd','e','s','c'): key = "description"; break;
  280. case MKTAG( 'd','i','s','k'): key = "disc";
  281. parse = mov_metadata_track_or_disc_number; break;
  282. case MKTAG( 'e','g','i','d'): key = "episode_uid";
  283. parse = mov_metadata_int8_no_padding; break;
  284. case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break;
  285. case MKTAG( 'g','n','r','e'): key = "genre";
  286. parse = mov_metadata_gnre; break;
  287. case MKTAG( 'h','d','v','d'): key = "hd_video";
  288. parse = mov_metadata_int8_no_padding; break;
  289. case MKTAG( 'H','M','M','T'):
  290. return mov_metadata_hmmt(c, pb, atom.size);
  291. case MKTAG( 'k','e','y','w'): key = "keywords"; break;
  292. case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
  293. case MKTAG( 'l','o','c','i'):
  294. return mov_metadata_loci(c, pb, atom.size);
  295. case MKTAG( 'm','a','n','u'): key = "make"; break;
  296. case MKTAG( 'm','o','d','l'): key = "model"; break;
  297. case MKTAG( 'p','c','s','t'): key = "podcast";
  298. parse = mov_metadata_int8_no_padding; break;
  299. case MKTAG( 'p','g','a','p'): key = "gapless_playback";
  300. parse = mov_metadata_int8_no_padding; break;
  301. case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
  302. case MKTAG( 'r','t','n','g'): key = "rating";
  303. parse = mov_metadata_int8_no_padding; break;
  304. case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
  305. case MKTAG( 's','o','a','l'): key = "sort_album"; break;
  306. case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
  307. case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
  308. case MKTAG( 's','o','n','m'): key = "sort_name"; break;
  309. case MKTAG( 's','o','s','n'): key = "sort_show"; break;
  310. case MKTAG( 's','t','i','k'): key = "media_type";
  311. parse = mov_metadata_int8_no_padding; break;
  312. case MKTAG( 't','r','k','n'): key = "track";
  313. parse = mov_metadata_track_or_disc_number; break;
  314. case MKTAG( 't','v','e','n'): key = "episode_id"; break;
  315. case MKTAG( 't','v','e','s'): key = "episode_sort";
  316. parse = mov_metadata_int8_bypass_padding; break;
  317. case MKTAG( 't','v','n','n'): key = "network"; break;
  318. case MKTAG( 't','v','s','h'): key = "show"; break;
  319. case MKTAG( 't','v','s','n'): key = "season_number";
  320. parse = mov_metadata_int8_bypass_padding; break;
  321. case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
  322. case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
  323. case MKTAG(0xa9,'a','l','b'): key = "album"; break;
  324. case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
  325. case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
  326. case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
  327. case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
  328. case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
  329. case MKTAG(0xa9,'d','a','y'): key = "date"; break;
  330. case MKTAG(0xa9,'d','i','r'): key = "director"; break;
  331. case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
  332. case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
  333. case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
  334. case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
  335. case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
  336. case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
  337. case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
  338. case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
  339. case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
  340. case MKTAG(0xa9,'m','a','k'): key = "make"; break;
  341. case MKTAG(0xa9,'m','o','d'): key = "model"; break;
  342. case MKTAG(0xa9,'n','a','m'): key = "title"; break;
  343. case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
  344. case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
  345. case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
  346. case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
  347. case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
  348. case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
  349. case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
  350. case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
  351. case MKTAG(0xa9,'t','r','k'): key = "track"; break;
  352. case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
  353. case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
  354. case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
  355. case MKTAG(0xa9,'x','y','z'): key = "location"; break;
  356. }
  357. retry:
  358. if (c->itunes_metadata && atom.size > 8) {
  359. int data_size = avio_rb32(pb);
  360. int tag = avio_rl32(pb);
  361. if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
  362. data_type = avio_rb32(pb); // type
  363. avio_rb32(pb); // unknown
  364. str_size = data_size - 16;
  365. atom.size -= 16;
  366. if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
  367. int ret = mov_read_covr(c, pb, data_type, str_size);
  368. if (ret < 0) {
  369. av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
  370. return ret;
  371. }
  372. atom.size -= str_size;
  373. if (atom.size > 8)
  374. goto retry;
  375. return ret;
  376. } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
  377. uint32_t index = AV_RB32(&atom.type);
  378. if (index < c->meta_keys_count && index > 0) {
  379. key = c->meta_keys[index];
  380. } else {
  381. av_log(c->fc, AV_LOG_WARNING,
  382. "The index of 'data' is out of range: %"PRId32" < 1 or >= %d.\n",
  383. index, c->meta_keys_count);
  384. }
  385. }
  386. } else return 0;
  387. } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
  388. str_size = avio_rb16(pb); // string length
  389. if (str_size > atom.size) {
  390. raw = 1;
  391. avio_seek(pb, -2, SEEK_CUR);
  392. av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
  393. goto retry;
  394. }
  395. langcode = avio_rb16(pb);
  396. ff_mov_lang_to_iso639(langcode, language);
  397. atom.size -= 4;
  398. } else
  399. str_size = atom.size;
  400. if (c->export_all && !key) {
  401. snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
  402. key = tmp_key;
  403. }
  404. if (!key)
  405. return 0;
  406. if (atom.size < 0 || str_size >= INT_MAX/2)
  407. return AVERROR_INVALIDDATA;
  408. // Allocates enough space if data_type is a int32 or float32 number, otherwise
  409. // worst-case requirement for output string in case of utf8 coded input
  410. num = (data_type >= 21 && data_type <= 23);
  411. str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
  412. str = av_mallocz(str_size_alloc);
  413. if (!str)
  414. return AVERROR(ENOMEM);
  415. if (parse)
  416. parse(c, pb, str_size, key);
  417. else {
  418. if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
  419. mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
  420. } else if (data_type == 21) { // BE signed integer, variable size
  421. int val = 0;
  422. if (str_size == 1)
  423. val = (int8_t)avio_r8(pb);
  424. else if (str_size == 2)
  425. val = (int16_t)avio_rb16(pb);
  426. else if (str_size == 3)
  427. val = ((int32_t)(avio_rb24(pb)<<8))>>8;
  428. else if (str_size == 4)
  429. val = (int32_t)avio_rb32(pb);
  430. if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
  431. av_log(c->fc, AV_LOG_ERROR,
  432. "Failed to store the number (%d) in string.\n", val);
  433. av_free(str);
  434. return AVERROR_INVALIDDATA;
  435. }
  436. } else if (data_type == 22) { // BE unsigned integer, variable size
  437. unsigned int val = 0;
  438. if (str_size == 1)
  439. val = avio_r8(pb);
  440. else if (str_size == 2)
  441. val = avio_rb16(pb);
  442. else if (str_size == 3)
  443. val = avio_rb24(pb);
  444. else if (str_size == 4)
  445. val = avio_rb32(pb);
  446. if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
  447. av_log(c->fc, AV_LOG_ERROR,
  448. "Failed to store the number (%u) in string.\n", val);
  449. av_free(str);
  450. return AVERROR_INVALIDDATA;
  451. }
  452. } else if (data_type == 23 && str_size >= 4) { // BE float32
  453. float val = av_int2float(avio_rb32(pb));
  454. if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
  455. av_log(c->fc, AV_LOG_ERROR,
  456. "Failed to store the float32 number (%f) in string.\n", val);
  457. av_free(str);
  458. return AVERROR_INVALIDDATA;
  459. }
  460. } else {
  461. int ret = ffio_read_size(pb, str, str_size);
  462. if (ret < 0) {
  463. av_free(str);
  464. return ret;
  465. }
  466. str[str_size] = 0;
  467. }
  468. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  469. av_dict_set(&c->fc->metadata, key, str, 0);
  470. if (*language && strcmp(language, "und")) {
  471. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  472. av_dict_set(&c->fc->metadata, key2, str, 0);
  473. }
  474. if (!strcmp(key, "encoder")) {
  475. int major, minor, micro;
  476. if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, &micro) == 3) {
  477. c->handbrake_version = 1000000*major + 1000*minor + micro;
  478. }
  479. }
  480. }
  481. av_freep(&str);
  482. return 0;
  483. }
  484. static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  485. {
  486. int64_t start;
  487. int i, nb_chapters, str_len, version;
  488. char str[256+1];
  489. int ret;
  490. if (c->ignore_chapters)
  491. return 0;
  492. if ((atom.size -= 5) < 0)
  493. return 0;
  494. version = avio_r8(pb);
  495. avio_rb24(pb);
  496. if (version)
  497. avio_rb32(pb); // ???
  498. nb_chapters = avio_r8(pb);
  499. for (i = 0; i < nb_chapters; i++) {
  500. if (atom.size < 9)
  501. return 0;
  502. start = avio_rb64(pb);
  503. str_len = avio_r8(pb);
  504. if ((atom.size -= 9+str_len) < 0)
  505. return 0;
  506. ret = ffio_read_size(pb, str, str_len);
  507. if (ret < 0)
  508. return ret;
  509. str[str_len] = 0;
  510. avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
  511. }
  512. return 0;
  513. }
  514. #define MIN_DATA_ENTRY_BOX_SIZE 12
  515. static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  516. {
  517. AVStream *st;
  518. MOVStreamContext *sc;
  519. int entries, i, j;
  520. if (c->fc->nb_streams < 1)
  521. return 0;
  522. st = c->fc->streams[c->fc->nb_streams-1];
  523. sc = st->priv_data;
  524. avio_rb32(pb); // version + flags
  525. entries = avio_rb32(pb);
  526. if (!entries ||
  527. entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
  528. entries >= UINT_MAX / sizeof(*sc->drefs))
  529. return AVERROR_INVALIDDATA;
  530. sc->drefs_count = 0;
  531. av_free(sc->drefs);
  532. sc->drefs_count = 0;
  533. sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
  534. if (!sc->drefs)
  535. return AVERROR(ENOMEM);
  536. sc->drefs_count = entries;
  537. for (i = 0; i < entries; i++) {
  538. MOVDref *dref = &sc->drefs[i];
  539. uint32_t size = avio_rb32(pb);
  540. int64_t next = avio_tell(pb) + size - 4;
  541. if (size < 12)
  542. return AVERROR_INVALIDDATA;
  543. dref->type = avio_rl32(pb);
  544. avio_rb32(pb); // version + flags
  545. if (dref->type == MKTAG('a','l','i','s') && size > 150) {
  546. /* macintosh alias record */
  547. uint16_t volume_len, len;
  548. int16_t type;
  549. int ret;
  550. avio_skip(pb, 10);
  551. volume_len = avio_r8(pb);
  552. volume_len = FFMIN(volume_len, 27);
  553. ret = ffio_read_size(pb, dref->volume, 27);
  554. if (ret < 0)
  555. return ret;
  556. dref->volume[volume_len] = 0;
  557. av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
  558. avio_skip(pb, 12);
  559. len = avio_r8(pb);
  560. len = FFMIN(len, 63);
  561. ret = ffio_read_size(pb, dref->filename, 63);
  562. if (ret < 0)
  563. return ret;
  564. dref->filename[len] = 0;
  565. av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
  566. avio_skip(pb, 16);
  567. /* read next level up_from_alias/down_to_target */
  568. dref->nlvl_from = avio_rb16(pb);
  569. dref->nlvl_to = avio_rb16(pb);
  570. av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
  571. dref->nlvl_from, dref->nlvl_to);
  572. avio_skip(pb, 16);
  573. for (type = 0; type != -1 && avio_tell(pb) < next; ) {
  574. if(avio_feof(pb))
  575. return AVERROR_EOF;
  576. type = avio_rb16(pb);
  577. len = avio_rb16(pb);
  578. av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
  579. if (len&1)
  580. len += 1;
  581. if (type == 2) { // absolute path
  582. av_free(dref->path);
  583. dref->path = av_mallocz(len+1);
  584. if (!dref->path)
  585. return AVERROR(ENOMEM);
  586. ret = ffio_read_size(pb, dref->path, len);
  587. if (ret < 0) {
  588. av_freep(&dref->path);
  589. return ret;
  590. }
  591. if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
  592. len -= volume_len;
  593. memmove(dref->path, dref->path+volume_len, len);
  594. dref->path[len] = 0;
  595. }
  596. // trim string of any ending zeros
  597. for (j = len - 1; j >= 0; j--) {
  598. if (dref->path[j] == 0)
  599. len--;
  600. else
  601. break;
  602. }
  603. for (j = 0; j < len; j++)
  604. if (dref->path[j] == ':' || dref->path[j] == 0)
  605. dref->path[j] = '/';
  606. av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
  607. } else if (type == 0) { // directory name
  608. av_free(dref->dir);
  609. dref->dir = av_malloc(len+1);
  610. if (!dref->dir)
  611. return AVERROR(ENOMEM);
  612. ret = ffio_read_size(pb, dref->dir, len);
  613. if (ret < 0) {
  614. av_freep(&dref->dir);
  615. return ret;
  616. }
  617. dref->dir[len] = 0;
  618. for (j = 0; j < len; j++)
  619. if (dref->dir[j] == ':')
  620. dref->dir[j] = '/';
  621. av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
  622. } else
  623. avio_skip(pb, len);
  624. }
  625. } else {
  626. av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08"PRIx32" size %"PRIu32"\n",
  627. dref->type, size);
  628. entries--;
  629. i--;
  630. }
  631. avio_seek(pb, next, SEEK_SET);
  632. }
  633. return 0;
  634. }
  635. static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  636. {
  637. AVStream *st;
  638. uint32_t type;
  639. uint32_t ctype;
  640. int64_t title_size;
  641. char *title_str;
  642. int ret;
  643. avio_r8(pb); /* version */
  644. avio_rb24(pb); /* flags */
  645. /* component type */
  646. ctype = avio_rl32(pb);
  647. type = avio_rl32(pb); /* component subtype */
  648. av_log(c->fc, AV_LOG_TRACE, "ctype=%s\n", av_fourcc2str(ctype));
  649. av_log(c->fc, AV_LOG_TRACE, "stype=%s\n", av_fourcc2str(type));
  650. if (c->trak_index < 0) { // meta not inside a trak
  651. if (type == MKTAG('m','d','t','a')) {
  652. c->found_hdlr_mdta = 1;
  653. }
  654. return 0;
  655. }
  656. st = c->fc->streams[c->fc->nb_streams-1];
  657. if (type == MKTAG('v','i','d','e'))
  658. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  659. else if (type == MKTAG('s','o','u','n'))
  660. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  661. else if (type == MKTAG('m','1','a',' '))
  662. st->codecpar->codec_id = AV_CODEC_ID_MP2;
  663. else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
  664. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  665. avio_rb32(pb); /* component manufacture */
  666. avio_rb32(pb); /* component flags */
  667. avio_rb32(pb); /* component flags mask */
  668. title_size = atom.size - 24;
  669. if (title_size > 0) {
  670. if (title_size > FFMIN(INT_MAX, SIZE_MAX-1))
  671. return AVERROR_INVALIDDATA;
  672. title_str = av_malloc(title_size + 1); /* Add null terminator */
  673. if (!title_str)
  674. return AVERROR(ENOMEM);
  675. ret = ffio_read_size(pb, title_str, title_size);
  676. if (ret < 0) {
  677. av_freep(&title_str);
  678. return ret;
  679. }
  680. title_str[title_size] = 0;
  681. if (title_str[0]) {
  682. int off = (!c->isom && title_str[0] == title_size - 1);
  683. // flag added so as to not set stream handler name if already set from mdia->hdlr
  684. av_dict_set(&st->metadata, "handler_name", title_str + off, AV_DICT_DONT_OVERWRITE);
  685. }
  686. av_freep(&title_str);
  687. }
  688. return 0;
  689. }
  690. static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  691. {
  692. return ff_mov_read_esds(c->fc, pb);
  693. }
  694. static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  695. {
  696. AVStream *st;
  697. enum AVAudioServiceType *ast;
  698. int ac3info, acmod, lfeon, bsmod;
  699. if (c->fc->nb_streams < 1)
  700. return 0;
  701. st = c->fc->streams[c->fc->nb_streams-1];
  702. ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
  703. sizeof(*ast));
  704. if (!ast)
  705. return AVERROR(ENOMEM);
  706. ac3info = avio_rb24(pb);
  707. bsmod = (ac3info >> 14) & 0x7;
  708. acmod = (ac3info >> 11) & 0x7;
  709. lfeon = (ac3info >> 10) & 0x1;
  710. st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
  711. st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  712. if (lfeon)
  713. st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
  714. *ast = bsmod;
  715. if (st->codecpar->channels > 1 && bsmod == 0x7)
  716. *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  717. #if FF_API_LAVF_AVCTX
  718. FF_DISABLE_DEPRECATION_WARNINGS
  719. st->codec->audio_service_type = *ast;
  720. FF_ENABLE_DEPRECATION_WARNINGS
  721. #endif
  722. return 0;
  723. }
  724. static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  725. {
  726. AVStream *st;
  727. enum AVAudioServiceType *ast;
  728. int eac3info, acmod, lfeon, bsmod;
  729. if (c->fc->nb_streams < 1)
  730. return 0;
  731. st = c->fc->streams[c->fc->nb_streams-1];
  732. ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
  733. sizeof(*ast));
  734. if (!ast)
  735. return AVERROR(ENOMEM);
  736. /* No need to parse fields for additional independent substreams and its
  737. * associated dependent substreams since libavcodec's E-AC-3 decoder
  738. * does not support them yet. */
  739. avio_rb16(pb); /* data_rate and num_ind_sub */
  740. eac3info = avio_rb24(pb);
  741. bsmod = (eac3info >> 12) & 0x1f;
  742. acmod = (eac3info >> 9) & 0x7;
  743. lfeon = (eac3info >> 8) & 0x1;
  744. st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  745. if (lfeon)
  746. st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
  747. st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
  748. *ast = bsmod;
  749. if (st->codecpar->channels > 1 && bsmod == 0x7)
  750. *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  751. #if FF_API_LAVF_AVCTX
  752. FF_DISABLE_DEPRECATION_WARNINGS
  753. st->codec->audio_service_type = *ast;
  754. FF_ENABLE_DEPRECATION_WARNINGS
  755. #endif
  756. return 0;
  757. }
  758. static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  759. {
  760. const uint32_t ddts_size = 20;
  761. AVStream *st = NULL;
  762. uint8_t *buf = NULL;
  763. uint32_t frame_duration_code = 0;
  764. uint32_t channel_layout_code = 0;
  765. GetBitContext gb;
  766. buf = av_malloc(ddts_size + AV_INPUT_BUFFER_PADDING_SIZE);
  767. if (!buf) {
  768. return AVERROR(ENOMEM);
  769. }
  770. if (avio_read(pb, buf, ddts_size) < ddts_size) {
  771. av_free(buf);
  772. return AVERROR_INVALIDDATA;
  773. }
  774. init_get_bits(&gb, buf, 8*ddts_size);
  775. if (c->fc->nb_streams < 1) {
  776. av_free(buf);
  777. return 0;
  778. }
  779. st = c->fc->streams[c->fc->nb_streams-1];
  780. st->codecpar->sample_rate = get_bits_long(&gb, 32);
  781. if (st->codecpar->sample_rate <= 0) {
  782. av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
  783. av_free(buf);
  784. return AVERROR_INVALIDDATA;
  785. }
  786. skip_bits_long(&gb, 32); /* max bitrate */
  787. st->codecpar->bit_rate = get_bits_long(&gb, 32);
  788. st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
  789. frame_duration_code = get_bits(&gb, 2);
  790. skip_bits(&gb, 30); /* various fields */
  791. channel_layout_code = get_bits(&gb, 16);
  792. st->codecpar->frame_size =
  793. (frame_duration_code == 0) ? 512 :
  794. (frame_duration_code == 1) ? 1024 :
  795. (frame_duration_code == 2) ? 2048 :
  796. (frame_duration_code == 3) ? 4096 : 0;
  797. if (channel_layout_code > 0xff) {
  798. av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
  799. }
  800. st->codecpar->channel_layout =
  801. ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
  802. ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
  803. ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
  804. ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
  805. ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
  806. ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
  807. st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
  808. av_free(buf);
  809. return 0;
  810. }
  811. static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  812. {
  813. AVStream *st;
  814. if (c->fc->nb_streams < 1)
  815. return 0;
  816. st = c->fc->streams[c->fc->nb_streams-1];
  817. if (atom.size < 16)
  818. return 0;
  819. /* skip version and flags */
  820. avio_skip(pb, 4);
  821. ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
  822. return 0;
  823. }
  824. static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  825. {
  826. AVStream *st;
  827. int ret;
  828. if (c->fc->nb_streams < 1)
  829. return 0;
  830. st = c->fc->streams[c->fc->nb_streams-1];
  831. if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
  832. av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
  833. return ret;
  834. }
  835. static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  836. {
  837. const int num = avio_rb32(pb);
  838. const int den = avio_rb32(pb);
  839. AVStream *st;
  840. if (c->fc->nb_streams < 1)
  841. return 0;
  842. st = c->fc->streams[c->fc->nb_streams-1];
  843. if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
  844. (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
  845. av_log(c->fc, AV_LOG_WARNING,
  846. "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
  847. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  848. num, den);
  849. } else if (den != 0) {
  850. av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
  851. num, den, 32767);
  852. }
  853. return 0;
  854. }
  855. /* this atom contains actual media data */
  856. static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  857. {
  858. if (atom.size == 0) /* wrong one (MP4) */
  859. return 0;
  860. c->found_mdat=1;
  861. return 0; /* now go for moov */
  862. }
  863. #define DRM_BLOB_SIZE 56
  864. static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  865. {
  866. uint8_t intermediate_key[20];
  867. uint8_t intermediate_iv[20];
  868. uint8_t input[64];
  869. uint8_t output[64];
  870. uint8_t file_checksum[20];
  871. uint8_t calculated_checksum[20];
  872. struct AVSHA *sha;
  873. int i;
  874. int ret = 0;
  875. uint8_t *activation_bytes = c->activation_bytes;
  876. uint8_t *fixed_key = c->audible_fixed_key;
  877. c->aax_mode = 1;
  878. sha = av_sha_alloc();
  879. if (!sha)
  880. return AVERROR(ENOMEM);
  881. c->aes_decrypt = av_aes_alloc();
  882. if (!c->aes_decrypt) {
  883. ret = AVERROR(ENOMEM);
  884. goto fail;
  885. }
  886. /* drm blob processing */
  887. avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
  888. avio_read(pb, input, DRM_BLOB_SIZE);
  889. avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
  890. avio_read(pb, file_checksum, 20);
  891. av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
  892. for (i = 0; i < 20; i++)
  893. av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]);
  894. av_log(c->fc, AV_LOG_INFO, "\n");
  895. /* verify activation data */
  896. if (!activation_bytes) {
  897. av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
  898. ret = 0; /* allow ffprobe to continue working on .aax files */
  899. goto fail;
  900. }
  901. if (c->activation_bytes_size != 4) {
  902. av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
  903. ret = AVERROR(EINVAL);
  904. goto fail;
  905. }
  906. /* verify fixed key */
  907. if (c->audible_fixed_key_size != 16) {
  908. av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
  909. ret = AVERROR(EINVAL);
  910. goto fail;
  911. }
  912. /* AAX (and AAX+) key derivation */
  913. av_sha_init(sha, 160);
  914. av_sha_update(sha, fixed_key, 16);
  915. av_sha_update(sha, activation_bytes, 4);
  916. av_sha_final(sha, intermediate_key);
  917. av_sha_init(sha, 160);
  918. av_sha_update(sha, fixed_key, 16);
  919. av_sha_update(sha, intermediate_key, 20);
  920. av_sha_update(sha, activation_bytes, 4);
  921. av_sha_final(sha, intermediate_iv);
  922. av_sha_init(sha, 160);
  923. av_sha_update(sha, intermediate_key, 16);
  924. av_sha_update(sha, intermediate_iv, 16);
  925. av_sha_final(sha, calculated_checksum);
  926. if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
  927. av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
  928. ret = AVERROR_INVALIDDATA;
  929. goto fail;
  930. }
  931. av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
  932. av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
  933. for (i = 0; i < 4; i++) {
  934. // file data (in output) is stored in big-endian mode
  935. if (activation_bytes[i] != output[3 - i]) { // critical error
  936. av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
  937. ret = AVERROR_INVALIDDATA;
  938. goto fail;
  939. }
  940. }
  941. memcpy(c->file_key, output + 8, 16);
  942. memcpy(input, output + 26, 16);
  943. av_sha_init(sha, 160);
  944. av_sha_update(sha, input, 16);
  945. av_sha_update(sha, c->file_key, 16);
  946. av_sha_update(sha, fixed_key, 16);
  947. av_sha_final(sha, c->file_iv);
  948. fail:
  949. av_free(sha);
  950. return ret;
  951. }
  952. // Audible AAX (and AAX+) bytestream decryption
  953. static int aax_filter(uint8_t *input, int size, MOVContext *c)
  954. {
  955. int blocks = 0;
  956. unsigned char iv[16];
  957. memcpy(iv, c->file_iv, 16); // iv is overwritten
  958. blocks = size >> 4; // trailing bytes are not encrypted!
  959. av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
  960. av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
  961. return 0;
  962. }
  963. /* read major brand, minor version and compatible brands and store them as metadata */
  964. static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  965. {
  966. uint32_t minor_ver;
  967. int comp_brand_size;
  968. char* comp_brands_str;
  969. uint8_t type[5] = {0};
  970. int ret = ffio_read_size(pb, type, 4);
  971. if (ret < 0)
  972. return ret;
  973. if (strcmp(type, "qt "))
  974. c->isom = 1;
  975. av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
  976. av_dict_set(&c->fc->metadata, "major_brand", type, 0);
  977. minor_ver = avio_rb32(pb); /* minor version */
  978. av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
  979. comp_brand_size = atom.size - 8;
  980. if (comp_brand_size < 0)
  981. return AVERROR_INVALIDDATA;
  982. comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
  983. if (!comp_brands_str)
  984. return AVERROR(ENOMEM);
  985. ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
  986. if (ret < 0) {
  987. av_freep(&comp_brands_str);
  988. return ret;
  989. }
  990. comp_brands_str[comp_brand_size] = 0;
  991. av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
  992. av_freep(&comp_brands_str);
  993. return 0;
  994. }
  995. /* this atom should contain all header atoms */
  996. static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  997. {
  998. int ret;
  999. if (c->found_moov) {
  1000. av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
  1001. avio_skip(pb, atom.size);
  1002. return 0;
  1003. }
  1004. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1005. return ret;
  1006. /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
  1007. /* so we don't parse the whole file if over a network */
  1008. c->found_moov=1;
  1009. return 0; /* now go for mdat */
  1010. }
  1011. static MOVFragmentStreamInfo * get_frag_stream_info(
  1012. MOVFragmentIndex *frag_index,
  1013. int index,
  1014. int id)
  1015. {
  1016. int i;
  1017. MOVFragmentIndexItem * item;
  1018. if (index < 0 || index >= frag_index->nb_items)
  1019. return NULL;
  1020. item = &frag_index->item[index];
  1021. for (i = 0; i < item->nb_stream_info; i++)
  1022. if (item->stream_info[i].id == id)
  1023. return &item->stream_info[i];
  1024. // This shouldn't happen
  1025. return NULL;
  1026. }
  1027. static void set_frag_stream(MOVFragmentIndex *frag_index, int id)
  1028. {
  1029. int i;
  1030. MOVFragmentIndexItem * item;
  1031. if (frag_index->current < 0 ||
  1032. frag_index->current >= frag_index->nb_items)
  1033. return;
  1034. item = &frag_index->item[frag_index->current];
  1035. for (i = 0; i < item->nb_stream_info; i++)
  1036. if (item->stream_info[i].id == id) {
  1037. item->current = i;
  1038. return;
  1039. }
  1040. // id not found. This shouldn't happen.
  1041. item->current = -1;
  1042. }
  1043. static MOVFragmentStreamInfo * get_current_frag_stream_info(
  1044. MOVFragmentIndex *frag_index)
  1045. {
  1046. MOVFragmentIndexItem *item;
  1047. if (frag_index->current < 0 ||
  1048. frag_index->current >= frag_index->nb_items)
  1049. return NULL;
  1050. item = &frag_index->item[frag_index->current];
  1051. if (item->current >= 0 && item->current < item->nb_stream_info)
  1052. return &item->stream_info[item->current];
  1053. // This shouldn't happen
  1054. return NULL;
  1055. }
  1056. static int search_frag_moof_offset(MOVFragmentIndex *frag_index, int64_t offset)
  1057. {
  1058. int a, b, m;
  1059. int64_t moof_offset;
  1060. // Optimize for appending new entries
  1061. if (!frag_index->nb_items ||
  1062. frag_index->item[frag_index->nb_items - 1].moof_offset < offset)
  1063. return frag_index->nb_items;
  1064. a = -1;
  1065. b = frag_index->nb_items;
  1066. while (b - a > 1) {
  1067. m = (a + b) >> 1;
  1068. moof_offset = frag_index->item[m].moof_offset;
  1069. if (moof_offset >= offset)
  1070. b = m;
  1071. if (moof_offset <= offset)
  1072. a = m;
  1073. }
  1074. return b;
  1075. }
  1076. static int64_t get_stream_info_time(MOVFragmentStreamInfo * frag_stream_info)
  1077. {
  1078. if (frag_stream_info) {
  1079. if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE)
  1080. return frag_stream_info->sidx_pts;
  1081. if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE)
  1082. return frag_stream_info->first_tfra_pts;
  1083. if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE)
  1084. return frag_stream_info->tfdt_dts;
  1085. }
  1086. return AV_NOPTS_VALUE;
  1087. }
  1088. static int64_t get_frag_time(MOVFragmentIndex *frag_index,
  1089. int index, int track_id)
  1090. {
  1091. MOVFragmentStreamInfo * frag_stream_info;
  1092. int64_t timestamp;
  1093. int i;
  1094. if (track_id >= 0) {
  1095. frag_stream_info = get_frag_stream_info(frag_index, index, track_id);
  1096. return frag_stream_info->sidx_pts;
  1097. }
  1098. for (i = 0; i < frag_index->item[index].nb_stream_info; i++) {
  1099. frag_stream_info = &frag_index->item[index].stream_info[i];
  1100. timestamp = get_stream_info_time(frag_stream_info);
  1101. if (timestamp != AV_NOPTS_VALUE)
  1102. return timestamp;
  1103. }
  1104. return AV_NOPTS_VALUE;
  1105. }
  1106. static int search_frag_timestamp(MOVFragmentIndex *frag_index,
  1107. AVStream *st, int64_t timestamp)
  1108. {
  1109. int a, b, m;
  1110. int64_t frag_time;
  1111. int id = -1;
  1112. if (st) {
  1113. // If the stream is referenced by any sidx, limit the search
  1114. // to fragments that referenced this stream in the sidx
  1115. MOVStreamContext *sc = st->priv_data;
  1116. if (sc->has_sidx)
  1117. id = st->id;
  1118. }
  1119. a = -1;
  1120. b = frag_index->nb_items;
  1121. while (b - a > 1) {
  1122. m = (a + b) >> 1;
  1123. frag_time = get_frag_time(frag_index, m, id);
  1124. if (frag_time != AV_NOPTS_VALUE) {
  1125. if (frag_time >= timestamp)
  1126. b = m;
  1127. if (frag_time <= timestamp)
  1128. a = m;
  1129. }
  1130. }
  1131. return a;
  1132. }
  1133. static int update_frag_index(MOVContext *c, int64_t offset)
  1134. {
  1135. int index, i;
  1136. MOVFragmentIndexItem * item;
  1137. MOVFragmentStreamInfo * frag_stream_info;
  1138. // If moof_offset already exists in frag_index, return index to it
  1139. index = search_frag_moof_offset(&c->frag_index, offset);
  1140. if (index < c->frag_index.nb_items &&
  1141. c->frag_index.item[index].moof_offset == offset)
  1142. return index;
  1143. // offset is not yet in frag index.
  1144. // Insert new item at index (sorted by moof offset)
  1145. item = av_fast_realloc(c->frag_index.item,
  1146. &c->frag_index.allocated_size,
  1147. (c->frag_index.nb_items + 1) *
  1148. sizeof(*c->frag_index.item));
  1149. if(!item)
  1150. return -1;
  1151. c->frag_index.item = item;
  1152. frag_stream_info = av_realloc_array(NULL, c->fc->nb_streams,
  1153. sizeof(*item->stream_info));
  1154. if (!frag_stream_info)
  1155. return -1;
  1156. for (i = 0; i < c->fc->nb_streams; i++) {
  1157. frag_stream_info[i].id = c->fc->streams[i]->id;
  1158. frag_stream_info[i].sidx_pts = AV_NOPTS_VALUE;
  1159. frag_stream_info[i].tfdt_dts = AV_NOPTS_VALUE;
  1160. frag_stream_info[i].first_tfra_pts = AV_NOPTS_VALUE;
  1161. frag_stream_info[i].index_entry = -1;
  1162. frag_stream_info[i].encryption_index = NULL;
  1163. }
  1164. if (index < c->frag_index.nb_items)
  1165. memmove(c->frag_index.item + index + 1, c->frag_index.item + index,
  1166. (c->frag_index.nb_items - index) * sizeof(*c->frag_index.item));
  1167. item = &c->frag_index.item[index];
  1168. item->headers_read = 0;
  1169. item->current = 0;
  1170. item->nb_stream_info = c->fc->nb_streams;
  1171. item->moof_offset = offset;
  1172. item->stream_info = frag_stream_info;
  1173. c->frag_index.nb_items++;
  1174. return index;
  1175. }
  1176. static void fix_frag_index_entries(MOVFragmentIndex *frag_index, int index,
  1177. int id, int entries)
  1178. {
  1179. int i;
  1180. MOVFragmentStreamInfo * frag_stream_info;
  1181. if (index < 0)
  1182. return;
  1183. for (i = index; i < frag_index->nb_items; i++) {
  1184. frag_stream_info = get_frag_stream_info(frag_index, i, id);
  1185. if (frag_stream_info && frag_stream_info->index_entry >= 0)
  1186. frag_stream_info->index_entry += entries;
  1187. }
  1188. }
  1189. static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1190. {
  1191. if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
  1192. c->has_looked_for_mfra = 1;
  1193. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  1194. int ret;
  1195. av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
  1196. "for a mfra\n");
  1197. if ((ret = mov_read_mfra(c, pb)) < 0) {
  1198. av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
  1199. "read the mfra (may be a live ismv)\n");
  1200. }
  1201. } else {
  1202. av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
  1203. "seekable, can not look for mfra\n");
  1204. }
  1205. }
  1206. c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
  1207. av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
  1208. c->frag_index.current = update_frag_index(c, c->fragment.moof_offset);
  1209. return mov_read_default(c, pb, atom);
  1210. }
  1211. static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
  1212. {
  1213. if (time) {
  1214. if(time >= 2082844800)
  1215. time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
  1216. if ((int64_t)(time * 1000000ULL) / 1000000 != time) {
  1217. av_log(NULL, AV_LOG_DEBUG, "creation_time is not representable\n");
  1218. return;
  1219. }
  1220. avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000);
  1221. }
  1222. }
  1223. static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1224. {
  1225. AVStream *st;
  1226. MOVStreamContext *sc;
  1227. int version;
  1228. char language[4] = {0};
  1229. unsigned lang;
  1230. int64_t creation_time;
  1231. if (c->fc->nb_streams < 1)
  1232. return 0;
  1233. st = c->fc->streams[c->fc->nb_streams-1];
  1234. sc = st->priv_data;
  1235. if (sc->time_scale) {
  1236. av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
  1237. return AVERROR_INVALIDDATA;
  1238. }
  1239. version = avio_r8(pb);
  1240. if (version > 1) {
  1241. avpriv_request_sample(c->fc, "Version %d", version);
  1242. return AVERROR_PATCHWELCOME;
  1243. }
  1244. avio_rb24(pb); /* flags */
  1245. if (version == 1) {
  1246. creation_time = avio_rb64(pb);
  1247. avio_rb64(pb);
  1248. } else {
  1249. creation_time = avio_rb32(pb);
  1250. avio_rb32(pb); /* modification time */
  1251. }
  1252. mov_metadata_creation_time(&st->metadata, creation_time);
  1253. sc->time_scale = avio_rb32(pb);
  1254. if (sc->time_scale <= 0) {
  1255. av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d, defaulting to 1\n", sc->time_scale);
  1256. sc->time_scale = 1;
  1257. }
  1258. st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  1259. lang = avio_rb16(pb); /* language */
  1260. if (ff_mov_lang_to_iso639(lang, language))
  1261. av_dict_set(&st->metadata, "language", language, 0);
  1262. avio_rb16(pb); /* quality */
  1263. return 0;
  1264. }
  1265. static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1266. {
  1267. int i;
  1268. int64_t creation_time;
  1269. int version = avio_r8(pb); /* version */
  1270. avio_rb24(pb); /* flags */
  1271. if (version == 1) {
  1272. creation_time = avio_rb64(pb);
  1273. avio_rb64(pb);
  1274. } else {
  1275. creation_time = avio_rb32(pb);
  1276. avio_rb32(pb); /* modification time */
  1277. }
  1278. mov_metadata_creation_time(&c->fc->metadata, creation_time);
  1279. c->time_scale = avio_rb32(pb); /* time scale */
  1280. if (c->time_scale <= 0) {
  1281. av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d, defaulting to 1\n", c->time_scale);
  1282. c->time_scale = 1;
  1283. }
  1284. av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
  1285. c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  1286. // set the AVCodecContext duration because the duration of individual tracks
  1287. // may be inaccurate
  1288. if (c->time_scale > 0 && !c->trex_data)
  1289. c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
  1290. avio_rb32(pb); /* preferred scale */
  1291. avio_rb16(pb); /* preferred volume */
  1292. avio_skip(pb, 10); /* reserved */
  1293. /* movie display matrix, store it in main context and use it later on */
  1294. for (i = 0; i < 3; i++) {
  1295. c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  1296. c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  1297. c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  1298. }
  1299. avio_rb32(pb); /* preview time */
  1300. avio_rb32(pb); /* preview duration */
  1301. avio_rb32(pb); /* poster time */
  1302. avio_rb32(pb); /* selection time */
  1303. avio_rb32(pb); /* selection duration */
  1304. avio_rb32(pb); /* current time */
  1305. avio_rb32(pb); /* next track ID */
  1306. return 0;
  1307. }
  1308. static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1309. {
  1310. AVStream *st;
  1311. int little_endian;
  1312. if (c->fc->nb_streams < 1)
  1313. return 0;
  1314. st = c->fc->streams[c->fc->nb_streams-1];
  1315. little_endian = avio_rb16(pb) & 0xFF;
  1316. av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
  1317. if (little_endian == 1) {
  1318. switch (st->codecpar->codec_id) {
  1319. case AV_CODEC_ID_PCM_S24BE:
  1320. st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
  1321. break;
  1322. case AV_CODEC_ID_PCM_S32BE:
  1323. st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
  1324. break;
  1325. case AV_CODEC_ID_PCM_F32BE:
  1326. st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
  1327. break;
  1328. case AV_CODEC_ID_PCM_F64BE:
  1329. st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
  1330. break;
  1331. default:
  1332. break;
  1333. }
  1334. }
  1335. return 0;
  1336. }
  1337. static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1338. {
  1339. AVStream *st;
  1340. char color_parameter_type[5] = { 0 };
  1341. uint16_t color_primaries, color_trc, color_matrix;
  1342. int ret;
  1343. if (c->fc->nb_streams < 1)
  1344. return 0;
  1345. st = c->fc->streams[c->fc->nb_streams - 1];
  1346. ret = ffio_read_size(pb, color_parameter_type, 4);
  1347. if (ret < 0)
  1348. return ret;
  1349. if (strncmp(color_parameter_type, "nclx", 4) &&
  1350. strncmp(color_parameter_type, "nclc", 4)) {
  1351. av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
  1352. color_parameter_type);
  1353. return 0;
  1354. }
  1355. color_primaries = avio_rb16(pb);
  1356. color_trc = avio_rb16(pb);
  1357. color_matrix = avio_rb16(pb);
  1358. av_log(c->fc, AV_LOG_TRACE,
  1359. "%s: pri %d trc %d matrix %d",
  1360. color_parameter_type, color_primaries, color_trc, color_matrix);
  1361. if (!strncmp(color_parameter_type, "nclx", 4)) {
  1362. uint8_t color_range = avio_r8(pb) >> 7;
  1363. av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
  1364. if (color_range)
  1365. st->codecpar->color_range = AVCOL_RANGE_JPEG;
  1366. else
  1367. st->codecpar->color_range = AVCOL_RANGE_MPEG;
  1368. }
  1369. if (!av_color_primaries_name(color_primaries))
  1370. color_primaries = AVCOL_PRI_UNSPECIFIED;
  1371. if (!av_color_transfer_name(color_trc))
  1372. color_trc = AVCOL_TRC_UNSPECIFIED;
  1373. if (!av_color_space_name(color_matrix))
  1374. color_matrix = AVCOL_SPC_UNSPECIFIED;
  1375. st->codecpar->color_primaries = color_primaries;
  1376. st->codecpar->color_trc = color_trc;
  1377. st->codecpar->color_space = color_matrix;
  1378. av_log(c->fc, AV_LOG_TRACE, "\n");
  1379. return 0;
  1380. }
  1381. static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1382. {
  1383. AVStream *st;
  1384. unsigned mov_field_order;
  1385. enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
  1386. if (c->fc->nb_streams < 1) // will happen with jp2 files
  1387. return 0;
  1388. st = c->fc->streams[c->fc->nb_streams-1];
  1389. if (atom.size < 2)
  1390. return AVERROR_INVALIDDATA;
  1391. mov_field_order = avio_rb16(pb);
  1392. if ((mov_field_order & 0xFF00) == 0x0100)
  1393. decoded_field_order = AV_FIELD_PROGRESSIVE;
  1394. else if ((mov_field_order & 0xFF00) == 0x0200) {
  1395. switch (mov_field_order & 0xFF) {
  1396. case 0x01: decoded_field_order = AV_FIELD_TT;
  1397. break;
  1398. case 0x06: decoded_field_order = AV_FIELD_BB;
  1399. break;
  1400. case 0x09: decoded_field_order = AV_FIELD_TB;
  1401. break;
  1402. case 0x0E: decoded_field_order = AV_FIELD_BT;
  1403. break;
  1404. }
  1405. }
  1406. if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
  1407. av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
  1408. }
  1409. st->codecpar->field_order = decoded_field_order;
  1410. return 0;
  1411. }
  1412. static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
  1413. {
  1414. int err = 0;
  1415. uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
  1416. if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
  1417. return AVERROR_INVALIDDATA;
  1418. if ((err = av_reallocp(&par->extradata, size)) < 0) {
  1419. par->extradata_size = 0;
  1420. return err;
  1421. }
  1422. par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
  1423. return 0;
  1424. }
  1425. /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
  1426. static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  1427. AVCodecParameters *par, uint8_t *buf)
  1428. {
  1429. int64_t result = atom.size;
  1430. int err;
  1431. AV_WB32(buf , atom.size + 8);
  1432. AV_WL32(buf + 4, atom.type);
  1433. err = ffio_read_size(pb, buf + 8, atom.size);
  1434. if (err < 0) {
  1435. par->extradata_size -= atom.size;
  1436. return err;
  1437. } else if (err < atom.size) {
  1438. av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
  1439. par->extradata_size -= atom.size - err;
  1440. result = err;
  1441. }
  1442. memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  1443. return result;
  1444. }
  1445. /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
  1446. static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  1447. enum AVCodecID codec_id)
  1448. {
  1449. AVStream *st;
  1450. uint64_t original_size;
  1451. int err;
  1452. if (c->fc->nb_streams < 1) // will happen with jp2 files
  1453. return 0;
  1454. st = c->fc->streams[c->fc->nb_streams-1];
  1455. if (st->codecpar->codec_id != codec_id)
  1456. return 0; /* unexpected codec_id - don't mess with extradata */
  1457. original_size = st->codecpar->extradata_size;
  1458. err = mov_realloc_extradata(st->codecpar, atom);
  1459. if (err)
  1460. return err;
  1461. err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
  1462. if (err < 0)
  1463. return err;
  1464. return 0; // Note: this is the original behavior to ignore truncation.
  1465. }
  1466. /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
  1467. static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1468. {
  1469. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
  1470. }
  1471. static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1472. {
  1473. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
  1474. }
  1475. static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1476. {
  1477. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
  1478. }
  1479. static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1480. {
  1481. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
  1482. }
  1483. static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1484. {
  1485. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
  1486. if(ret == 0)
  1487. ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
  1488. return ret;
  1489. }
  1490. static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1491. {
  1492. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
  1493. if (!ret && c->fc->nb_streams >= 1) {
  1494. AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
  1495. if (par->extradata_size >= 40) {
  1496. par->height = AV_RB16(&par->extradata[36]);
  1497. par->width = AV_RB16(&par->extradata[38]);
  1498. }
  1499. }
  1500. return ret;
  1501. }
  1502. static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1503. {
  1504. if (c->fc->nb_streams >= 1) {
  1505. AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
  1506. if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
  1507. par->codec_id == AV_CODEC_ID_H264 &&
  1508. atom.size > 11) {
  1509. int cid;
  1510. avio_skip(pb, 10);
  1511. cid = avio_rb16(pb);
  1512. /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
  1513. if (cid == 0xd4d || cid == 0xd4e)
  1514. par->width = 1440;
  1515. return 0;
  1516. } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
  1517. par->codec_tag == MKTAG('A', 'V', 'j', '2') ||
  1518. par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
  1519. atom.size >= 24) {
  1520. int num, den;
  1521. avio_skip(pb, 12);
  1522. num = avio_rb32(pb);
  1523. den = avio_rb32(pb);
  1524. if (num <= 0 || den <= 0)
  1525. return 0;
  1526. switch (avio_rb32(pb)) {
  1527. case 2:
  1528. if (den >= INT_MAX / 2)
  1529. return 0;
  1530. den *= 2;
  1531. case 1:
  1532. c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
  1533. c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
  1534. default:
  1535. return 0;
  1536. }
  1537. }
  1538. }
  1539. return mov_read_avid(c, pb, atom);
  1540. }
  1541. static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1542. {
  1543. int ret = 0;
  1544. int length = 0;
  1545. uint64_t original_size;
  1546. if (c->fc->nb_streams >= 1) {
  1547. AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
  1548. if (par->codec_id == AV_CODEC_ID_H264)
  1549. return 0;
  1550. if (atom.size == 16) {
  1551. original_size = par->extradata_size;
  1552. ret = mov_realloc_extradata(par, atom);
  1553. if (!ret) {
  1554. length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
  1555. if (length == atom.size) {
  1556. const uint8_t range_value = par->extradata[original_size + 19];
  1557. switch (range_value) {
  1558. case 1:
  1559. par->color_range = AVCOL_RANGE_MPEG;
  1560. break;
  1561. case 2:
  1562. par->color_range = AVCOL_RANGE_JPEG;
  1563. break;
  1564. default:
  1565. av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
  1566. break;
  1567. }
  1568. ff_dlog(c, "color_range: %d\n", par->color_range);
  1569. } else {
  1570. /* For some reason the whole atom was not added to the extradata */
  1571. av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
  1572. }
  1573. } else {
  1574. av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
  1575. }
  1576. } else {
  1577. av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
  1578. }
  1579. }
  1580. return ret;
  1581. }
  1582. static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1583. {
  1584. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
  1585. }
  1586. static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1587. {
  1588. AVStream *st;
  1589. int ret;
  1590. if (c->fc->nb_streams < 1)
  1591. return 0;
  1592. st = c->fc->streams[c->fc->nb_streams-1];
  1593. if ((uint64_t)atom.size > (1<<30))
  1594. return AVERROR_INVALIDDATA;
  1595. if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
  1596. st->codecpar->codec_id == AV_CODEC_ID_QDMC ||
  1597. st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
  1598. // pass all frma atom to codec, needed at least for QDMC and QDM2
  1599. av_freep(&st->codecpar->extradata);
  1600. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
  1601. if (ret < 0)
  1602. return ret;
  1603. } else if (atom.size > 8) { /* to read frma, esds atoms */
  1604. if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
  1605. uint64_t buffer;
  1606. ret = ffio_ensure_seekback(pb, 8);
  1607. if (ret < 0)
  1608. return ret;
  1609. buffer = avio_rb64(pb);
  1610. atom.size -= 8;
  1611. if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
  1612. && buffer >> 32 <= atom.size
  1613. && buffer >> 32 >= 8) {
  1614. avio_skip(pb, -8);
  1615. atom.size += 8;
  1616. } else if (!st->codecpar->extradata_size) {
  1617. #define ALAC_EXTRADATA_SIZE 36
  1618. st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
  1619. if (!st->codecpar->extradata)
  1620. return AVERROR(ENOMEM);
  1621. st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE;
  1622. AV_WB32(st->codecpar->extradata , ALAC_EXTRADATA_SIZE);
  1623. AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
  1624. AV_WB64(st->codecpar->extradata + 12, buffer);
  1625. avio_read(pb, st->codecpar->extradata + 20, 16);
  1626. avio_skip(pb, atom.size - 24);
  1627. return 0;
  1628. }
  1629. }
  1630. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1631. return ret;
  1632. } else
  1633. avio_skip(pb, atom.size);
  1634. return 0;
  1635. }
  1636. /**
  1637. * This function reads atom content and puts data in extradata without tag
  1638. * nor size unlike mov_read_extradata.
  1639. */
  1640. static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1641. {
  1642. AVStream *st;
  1643. int ret;
  1644. if (c->fc->nb_streams < 1)
  1645. return 0;
  1646. st = c->fc->streams[c->fc->nb_streams-1];
  1647. if ((uint64_t)atom.size > (1<<30))
  1648. return AVERROR_INVALIDDATA;
  1649. if (atom.size >= 10) {
  1650. // Broken files created by legacy versions of libavformat will
  1651. // wrap a whole fiel atom inside of a glbl atom.
  1652. unsigned size = avio_rb32(pb);
  1653. unsigned type = avio_rl32(pb);
  1654. avio_seek(pb, -8, SEEK_CUR);
  1655. if (type == MKTAG('f','i','e','l') && size == atom.size)
  1656. return mov_read_default(c, pb, atom);
  1657. }
  1658. if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
  1659. av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
  1660. return 0;
  1661. }
  1662. av_freep(&st->codecpar->extradata);
  1663. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
  1664. if (ret < 0)
  1665. return ret;
  1666. if (atom.type == MKTAG('h','v','c','C') && st->codecpar->codec_tag == MKTAG('d','v','h','1'))
  1667. st->codecpar->codec_id = AV_CODEC_ID_HEVC;
  1668. return 0;
  1669. }
  1670. static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1671. {
  1672. AVStream *st;
  1673. uint8_t profile_level;
  1674. int ret;
  1675. if (c->fc->nb_streams < 1)
  1676. return 0;
  1677. st = c->fc->streams[c->fc->nb_streams-1];
  1678. if (atom.size >= (1<<28) || atom.size < 7)
  1679. return AVERROR_INVALIDDATA;
  1680. profile_level = avio_r8(pb);
  1681. if ((profile_level & 0xf0) != 0xc0)
  1682. return 0;
  1683. avio_seek(pb, 6, SEEK_CUR);
  1684. av_freep(&st->codecpar->extradata);
  1685. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
  1686. if (ret < 0)
  1687. return ret;
  1688. return 0;
  1689. }
  1690. /**
  1691. * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
  1692. * but can have extradata appended at the end after the 40 bytes belonging
  1693. * to the struct.
  1694. */
  1695. static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1696. {
  1697. AVStream *st;
  1698. int ret;
  1699. if (c->fc->nb_streams < 1)
  1700. return 0;
  1701. if (atom.size <= 40)
  1702. return 0;
  1703. st = c->fc->streams[c->fc->nb_streams-1];
  1704. if ((uint64_t)atom.size > (1<<30))
  1705. return AVERROR_INVALIDDATA;
  1706. avio_skip(pb, 40);
  1707. av_freep(&st->codecpar->extradata);
  1708. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
  1709. if (ret < 0)
  1710. return ret;
  1711. return 0;
  1712. }
  1713. static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1714. {
  1715. AVStream *st;
  1716. MOVStreamContext *sc;
  1717. unsigned int i, entries;
  1718. if (c->fc->nb_streams < 1)
  1719. return 0;
  1720. st = c->fc->streams[c->fc->nb_streams-1];
  1721. sc = st->priv_data;
  1722. avio_r8(pb); /* version */
  1723. avio_rb24(pb); /* flags */
  1724. entries = avio_rb32(pb);
  1725. if (!entries)
  1726. return 0;
  1727. if (sc->chunk_offsets)
  1728. av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
  1729. av_free(sc->chunk_offsets);
  1730. sc->chunk_count = 0;
  1731. sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
  1732. if (!sc->chunk_offsets)
  1733. return AVERROR(ENOMEM);
  1734. sc->chunk_count = entries;
  1735. if (atom.type == MKTAG('s','t','c','o'))
  1736. for (i = 0; i < entries && !pb->eof_reached; i++)
  1737. sc->chunk_offsets[i] = avio_rb32(pb);
  1738. else if (atom.type == MKTAG('c','o','6','4'))
  1739. for (i = 0; i < entries && !pb->eof_reached; i++)
  1740. sc->chunk_offsets[i] = avio_rb64(pb);
  1741. else
  1742. return AVERROR_INVALIDDATA;
  1743. sc->chunk_count = i;
  1744. if (pb->eof_reached) {
  1745. av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STCO atom\n");
  1746. return AVERROR_EOF;
  1747. }
  1748. return 0;
  1749. }
  1750. static int mov_codec_id(AVStream *st, uint32_t format)
  1751. {
  1752. int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
  1753. if (id <= 0 &&
  1754. ((format & 0xFFFF) == 'm' + ('s' << 8) ||
  1755. (format & 0xFFFF) == 'T' + ('S' << 8)))
  1756. id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
  1757. if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
  1758. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  1759. } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
  1760. /* skip old ASF MPEG-4 tag */
  1761. format && format != MKTAG('m','p','4','s')) {
  1762. id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1763. if (id <= 0)
  1764. id = ff_codec_get_id(ff_codec_bmp_tags, format);
  1765. if (id > 0)
  1766. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  1767. else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
  1768. (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1769. st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
  1770. id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
  1771. if (id > 0)
  1772. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1773. }
  1774. }
  1775. st->codecpar->codec_tag = format;
  1776. return id;
  1777. }
  1778. static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
  1779. AVStream *st, MOVStreamContext *sc)
  1780. {
  1781. uint8_t codec_name[32] = { 0 };
  1782. int64_t stsd_start;
  1783. unsigned int len;
  1784. /* The first 16 bytes of the video sample description are already
  1785. * read in ff_mov_read_stsd_entries() */
  1786. stsd_start = avio_tell(pb) - 16;
  1787. avio_rb16(pb); /* version */
  1788. avio_rb16(pb); /* revision level */
  1789. avio_rb32(pb); /* vendor */
  1790. avio_rb32(pb); /* temporal quality */
  1791. avio_rb32(pb); /* spatial quality */
  1792. st->codecpar->width = avio_rb16(pb); /* width */
  1793. st->codecpar->height = avio_rb16(pb); /* height */
  1794. avio_rb32(pb); /* horiz resolution */
  1795. avio_rb32(pb); /* vert resolution */
  1796. avio_rb32(pb); /* data size, always 0 */
  1797. avio_rb16(pb); /* frames per samples */
  1798. len = avio_r8(pb); /* codec name, pascal string */
  1799. if (len > 31)
  1800. len = 31;
  1801. mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
  1802. if (len < 31)
  1803. avio_skip(pb, 31 - len);
  1804. if (codec_name[0])
  1805. av_dict_set(&st->metadata, "encoder", codec_name, 0);
  1806. /* codec_tag YV12 triggers an UV swap in rawdec.c */
  1807. if (!strncmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
  1808. st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
  1809. st->codecpar->width &= ~1;
  1810. st->codecpar->height &= ~1;
  1811. }
  1812. /* Flash Media Server uses tag H.263 with Sorenson Spark */
  1813. if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
  1814. !strncmp(codec_name, "Sorenson H263", 13))
  1815. st->codecpar->codec_id = AV_CODEC_ID_FLV1;
  1816. st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
  1817. avio_seek(pb, stsd_start, SEEK_SET);
  1818. if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
  1819. st->codecpar->bits_per_coded_sample &= 0x1F;
  1820. sc->has_palette = 1;
  1821. }
  1822. }
  1823. static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
  1824. AVStream *st, MOVStreamContext *sc)
  1825. {
  1826. int bits_per_sample, flags;
  1827. uint16_t version = avio_rb16(pb);
  1828. AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
  1829. avio_rb16(pb); /* revision level */
  1830. avio_rb32(pb); /* vendor */
  1831. st->codecpar->channels = avio_rb16(pb); /* channel count */
  1832. st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  1833. av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
  1834. sc->audio_cid = avio_rb16(pb);
  1835. avio_rb16(pb); /* packet size = 0 */
  1836. st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
  1837. // Read QT version 1 fields. In version 0 these do not exist.
  1838. av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
  1839. if (!c->isom ||
  1840. (compatible_brands && strstr(compatible_brands->value, "qt "))) {
  1841. if (version == 1) {
  1842. sc->samples_per_frame = avio_rb32(pb);
  1843. avio_rb32(pb); /* bytes per packet */
  1844. sc->bytes_per_frame = avio_rb32(pb);
  1845. avio_rb32(pb); /* bytes per sample */
  1846. } else if (version == 2) {
  1847. avio_rb32(pb); /* sizeof struct only */
  1848. st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
  1849. st->codecpar->channels = avio_rb32(pb);
  1850. avio_rb32(pb); /* always 0x7F000000 */
  1851. st->codecpar->bits_per_coded_sample = avio_rb32(pb);
  1852. flags = avio_rb32(pb); /* lpcm format specific flag */
  1853. sc->bytes_per_frame = avio_rb32(pb);
  1854. sc->samples_per_frame = avio_rb32(pb);
  1855. if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
  1856. st->codecpar->codec_id =
  1857. ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
  1858. flags);
  1859. }
  1860. if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
  1861. /* can't correctly handle variable sized packet as audio unit */
  1862. switch (st->codecpar->codec_id) {
  1863. case AV_CODEC_ID_MP2:
  1864. case AV_CODEC_ID_MP3:
  1865. st->need_parsing = AVSTREAM_PARSE_FULL;
  1866. break;
  1867. }
  1868. }
  1869. }
  1870. if (sc->format == 0) {
  1871. if (st->codecpar->bits_per_coded_sample == 8)
  1872. st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
  1873. else if (st->codecpar->bits_per_coded_sample == 16)
  1874. st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
  1875. }
  1876. switch (st->codecpar->codec_id) {
  1877. case AV_CODEC_ID_PCM_S8:
  1878. case AV_CODEC_ID_PCM_U8:
  1879. if (st->codecpar->bits_per_coded_sample == 16)
  1880. st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
  1881. break;
  1882. case AV_CODEC_ID_PCM_S16LE:
  1883. case AV_CODEC_ID_PCM_S16BE:
  1884. if (st->codecpar->bits_per_coded_sample == 8)
  1885. st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
  1886. else if (st->codecpar->bits_per_coded_sample == 24)
  1887. st->codecpar->codec_id =
  1888. st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1889. AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  1890. else if (st->codecpar->bits_per_coded_sample == 32)
  1891. st->codecpar->codec_id =
  1892. st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1893. AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
  1894. break;
  1895. /* set values for old format before stsd version 1 appeared */
  1896. case AV_CODEC_ID_MACE3:
  1897. sc->samples_per_frame = 6;
  1898. sc->bytes_per_frame = 2 * st->codecpar->channels;
  1899. break;
  1900. case AV_CODEC_ID_MACE6:
  1901. sc->samples_per_frame = 6;
  1902. sc->bytes_per_frame = 1 * st->codecpar->channels;
  1903. break;
  1904. case AV_CODEC_ID_ADPCM_IMA_QT:
  1905. sc->samples_per_frame = 64;
  1906. sc->bytes_per_frame = 34 * st->codecpar->channels;
  1907. break;
  1908. case AV_CODEC_ID_GSM:
  1909. sc->samples_per_frame = 160;
  1910. sc->bytes_per_frame = 33;
  1911. break;
  1912. default:
  1913. break;
  1914. }
  1915. bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
  1916. if (bits_per_sample) {
  1917. st->codecpar->bits_per_coded_sample = bits_per_sample;
  1918. sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
  1919. }
  1920. }
  1921. static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
  1922. AVStream *st, MOVStreamContext *sc,
  1923. int64_t size)
  1924. {
  1925. // ttxt stsd contains display flags, justification, background
  1926. // color, fonts, and default styles, so fake an atom to read it
  1927. MOVAtom fake_atom = { .size = size };
  1928. // mp4s contains a regular esds atom
  1929. if (st->codecpar->codec_tag != AV_RL32("mp4s"))
  1930. mov_read_glbl(c, pb, fake_atom);
  1931. st->codecpar->width = sc->width;
  1932. st->codecpar->height = sc->height;
  1933. }
  1934. static uint32_t yuv_to_rgba(uint32_t ycbcr)
  1935. {
  1936. uint8_t r, g, b;
  1937. int y, cb, cr;
  1938. y = (ycbcr >> 16) & 0xFF;
  1939. cr = (ycbcr >> 8) & 0xFF;
  1940. cb = ycbcr & 0xFF;
  1941. b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
  1942. g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
  1943. r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
  1944. return (r << 16) | (g << 8) | b;
  1945. }
  1946. static int mov_rewrite_dvd_sub_extradata(AVStream *st)
  1947. {
  1948. char buf[256] = {0};
  1949. uint8_t *src = st->codecpar->extradata;
  1950. int i;
  1951. if (st->codecpar->extradata_size != 64)
  1952. return 0;
  1953. if (st->codecpar->width > 0 && st->codecpar->height > 0)
  1954. snprintf(buf, sizeof(buf), "size: %dx%d\n",
  1955. st->codecpar->width, st->codecpar->height);
  1956. av_strlcat(buf, "palette: ", sizeof(buf));
  1957. for (i = 0; i < 16; i++) {
  1958. uint32_t yuv = AV_RB32(src + i * 4);
  1959. uint32_t rgba = yuv_to_rgba(yuv);
  1960. av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
  1961. }
  1962. if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
  1963. return 0;
  1964. av_freep(&st->codecpar->extradata);
  1965. st->codecpar->extradata_size = 0;
  1966. st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
  1967. if (!st->codecpar->extradata)
  1968. return AVERROR(ENOMEM);
  1969. st->codecpar->extradata_size = strlen(buf);
  1970. memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
  1971. return 0;
  1972. }
  1973. static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
  1974. AVStream *st, MOVStreamContext *sc,
  1975. int64_t size)
  1976. {
  1977. int ret;
  1978. if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
  1979. if ((int)size != size)
  1980. return AVERROR(ENOMEM);
  1981. ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
  1982. if (ret < 0)
  1983. return ret;
  1984. if (size > 16) {
  1985. MOVStreamContext *tmcd_ctx = st->priv_data;
  1986. int val;
  1987. val = AV_RB32(st->codecpar->extradata + 4);
  1988. tmcd_ctx->tmcd_flags = val;
  1989. st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
  1990. st->avg_frame_rate.den = 1;
  1991. #if FF_API_LAVF_AVCTX
  1992. FF_DISABLE_DEPRECATION_WARNINGS
  1993. st->codec->time_base = av_inv_q(st->avg_frame_rate);
  1994. FF_ENABLE_DEPRECATION_WARNINGS
  1995. #endif
  1996. /* adjust for per frame dur in counter mode */
  1997. if (tmcd_ctx->tmcd_flags & 0x0008) {
  1998. int timescale = AV_RB32(st->codecpar->extradata + 8);
  1999. int framedur = AV_RB32(st->codecpar->extradata + 12);
  2000. st->avg_frame_rate.num *= timescale;
  2001. st->avg_frame_rate.den *= framedur;
  2002. #if FF_API_LAVF_AVCTX
  2003. FF_DISABLE_DEPRECATION_WARNINGS
  2004. st->codec->time_base.den *= timescale;
  2005. st->codec->time_base.num *= framedur;
  2006. FF_ENABLE_DEPRECATION_WARNINGS
  2007. #endif
  2008. }
  2009. if (size > 30) {
  2010. uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
  2011. uint32_t format = AV_RB32(st->codecpar->extradata + 22);
  2012. if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
  2013. uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
  2014. if (str_size > 0 && size >= (int)str_size + 26) {
  2015. char *reel_name = av_malloc(str_size + 1);
  2016. if (!reel_name)
  2017. return AVERROR(ENOMEM);
  2018. memcpy(reel_name, st->codecpar->extradata + 30, str_size);
  2019. reel_name[str_size] = 0; /* Add null terminator */
  2020. /* don't add reel_name if emtpy string */
  2021. if (*reel_name == 0) {
  2022. av_free(reel_name);
  2023. } else {
  2024. av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
  2025. }
  2026. }
  2027. }
  2028. }
  2029. }
  2030. } else {
  2031. /* other codec type, just skip (rtp, mp4s ...) */
  2032. avio_skip(pb, size);
  2033. }
  2034. return 0;
  2035. }
  2036. static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
  2037. AVStream *st, MOVStreamContext *sc)
  2038. {
  2039. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  2040. !st->codecpar->sample_rate && sc->time_scale > 1)
  2041. st->codecpar->sample_rate = sc->time_scale;
  2042. /* special codec parameters handling */
  2043. switch (st->codecpar->codec_id) {
  2044. #if CONFIG_DV_DEMUXER
  2045. case AV_CODEC_ID_DVAUDIO:
  2046. c->dv_fctx = avformat_alloc_context();
  2047. if (!c->dv_fctx) {
  2048. av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
  2049. return AVERROR(ENOMEM);
  2050. }
  2051. c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
  2052. if (!c->dv_demux) {
  2053. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  2054. return AVERROR(ENOMEM);
  2055. }
  2056. sc->dv_audio_container = 1;
  2057. st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
  2058. break;
  2059. #endif
  2060. /* no ifdef since parameters are always those */
  2061. case AV_CODEC_ID_QCELP:
  2062. st->codecpar->channels = 1;
  2063. // force sample rate for qcelp when not stored in mov
  2064. if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
  2065. st->codecpar->sample_rate = 8000;
  2066. // FIXME: Why is the following needed for some files?
  2067. sc->samples_per_frame = 160;
  2068. if (!sc->bytes_per_frame)
  2069. sc->bytes_per_frame = 35;
  2070. break;
  2071. case AV_CODEC_ID_AMR_NB:
  2072. st->codecpar->channels = 1;
  2073. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  2074. st->codecpar->sample_rate = 8000;
  2075. break;
  2076. case AV_CODEC_ID_AMR_WB:
  2077. st->codecpar->channels = 1;
  2078. st->codecpar->sample_rate = 16000;
  2079. break;
  2080. case AV_CODEC_ID_MP2:
  2081. case AV_CODEC_ID_MP3:
  2082. /* force type after stsd for m1a hdlr */
  2083. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  2084. break;
  2085. case AV_CODEC_ID_GSM:
  2086. case AV_CODEC_ID_ADPCM_MS:
  2087. case AV_CODEC_ID_ADPCM_IMA_WAV:
  2088. case AV_CODEC_ID_ILBC:
  2089. case AV_CODEC_ID_MACE3:
  2090. case AV_CODEC_ID_MACE6:
  2091. case AV_CODEC_ID_QDM2:
  2092. st->codecpar->block_align = sc->bytes_per_frame;
  2093. break;
  2094. case AV_CODEC_ID_ALAC:
  2095. if (st->codecpar->extradata_size == 36) {
  2096. st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
  2097. st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
  2098. }
  2099. break;
  2100. case AV_CODEC_ID_AC3:
  2101. case AV_CODEC_ID_EAC3:
  2102. case AV_CODEC_ID_MPEG1VIDEO:
  2103. case AV_CODEC_ID_VC1:
  2104. case AV_CODEC_ID_VP8:
  2105. case AV_CODEC_ID_VP9:
  2106. st->need_parsing = AVSTREAM_PARSE_FULL;
  2107. break;
  2108. default:
  2109. break;
  2110. }
  2111. return 0;
  2112. }
  2113. static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
  2114. int codec_tag, int format,
  2115. int64_t size)
  2116. {
  2117. int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  2118. if (codec_tag &&
  2119. (codec_tag != format &&
  2120. // AVID 1:1 samples with differing data format and codec tag exist
  2121. (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) &&
  2122. // prores is allowed to have differing data format and codec tag
  2123. codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
  2124. // so is dv (sigh)
  2125. codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
  2126. (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
  2127. : codec_tag != MKTAG('j','p','e','g')))) {
  2128. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  2129. * export it as a separate AVStream but this needs a few changes
  2130. * in the MOV demuxer, patch welcome. */
  2131. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  2132. avio_skip(pb, size);
  2133. return 1;
  2134. }
  2135. return 0;
  2136. }
  2137. int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
  2138. {
  2139. AVStream *st;
  2140. MOVStreamContext *sc;
  2141. int pseudo_stream_id;
  2142. av_assert0 (c->fc->nb_streams >= 1);
  2143. st = c->fc->streams[c->fc->nb_streams-1];
  2144. sc = st->priv_data;
  2145. for (pseudo_stream_id = 0;
  2146. pseudo_stream_id < entries && !pb->eof_reached;
  2147. pseudo_stream_id++) {
  2148. //Parsing Sample description table
  2149. enum AVCodecID id;
  2150. int ret, dref_id = 1;
  2151. MOVAtom a = { AV_RL32("stsd") };
  2152. int64_t start_pos = avio_tell(pb);
  2153. int64_t size = avio_rb32(pb); /* size */
  2154. uint32_t format = avio_rl32(pb); /* data format */
  2155. if (size >= 16) {
  2156. avio_rb32(pb); /* reserved */
  2157. avio_rb16(pb); /* reserved */
  2158. dref_id = avio_rb16(pb);
  2159. } else if (size <= 7) {
  2160. av_log(c->fc, AV_LOG_ERROR,
  2161. "invalid size %"PRId64" in stsd\n", size);
  2162. return AVERROR_INVALIDDATA;
  2163. }
  2164. if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
  2165. size - (avio_tell(pb) - start_pos))) {
  2166. sc->stsd_count++;
  2167. continue;
  2168. }
  2169. sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
  2170. sc->dref_id= dref_id;
  2171. sc->format = format;
  2172. id = mov_codec_id(st, format);
  2173. av_log(c->fc, AV_LOG_TRACE,
  2174. "size=%"PRId64" 4CC=%s codec_type=%d\n", size,
  2175. av_fourcc2str(format), st->codecpar->codec_type);
  2176. if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
  2177. st->codecpar->codec_id = id;
  2178. mov_parse_stsd_video(c, pb, st, sc);
  2179. } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
  2180. st->codecpar->codec_id = id;
  2181. mov_parse_stsd_audio(c, pb, st, sc);
  2182. if (st->codecpar->sample_rate < 0) {
  2183. av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
  2184. return AVERROR_INVALIDDATA;
  2185. }
  2186. } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
  2187. st->codecpar->codec_id = id;
  2188. mov_parse_stsd_subtitle(c, pb, st, sc,
  2189. size - (avio_tell(pb) - start_pos));
  2190. } else {
  2191. ret = mov_parse_stsd_data(c, pb, st, sc,
  2192. size - (avio_tell(pb) - start_pos));
  2193. if (ret < 0)
  2194. return ret;
  2195. }
  2196. /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
  2197. a.size = size - (avio_tell(pb) - start_pos);
  2198. if (a.size > 8) {
  2199. if ((ret = mov_read_default(c, pb, a)) < 0)
  2200. return ret;
  2201. } else if (a.size > 0)
  2202. avio_skip(pb, a.size);
  2203. if (sc->extradata && st->codecpar->extradata) {
  2204. int extra_size = st->codecpar->extradata_size;
  2205. /* Move the current stream extradata to the stream context one. */
  2206. sc->extradata_size[pseudo_stream_id] = extra_size;
  2207. sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
  2208. if (!sc->extradata[pseudo_stream_id])
  2209. return AVERROR(ENOMEM);
  2210. memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
  2211. av_freep(&st->codecpar->extradata);
  2212. st->codecpar->extradata_size = 0;
  2213. }
  2214. sc->stsd_count++;
  2215. }
  2216. if (pb->eof_reached) {
  2217. av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSD atom\n");
  2218. return AVERROR_EOF;
  2219. }
  2220. return 0;
  2221. }
  2222. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2223. {
  2224. AVStream *st;
  2225. MOVStreamContext *sc;
  2226. int ret, entries;
  2227. if (c->fc->nb_streams < 1)
  2228. return 0;
  2229. st = c->fc->streams[c->fc->nb_streams - 1];
  2230. sc = st->priv_data;
  2231. avio_r8(pb); /* version */
  2232. avio_rb24(pb); /* flags */
  2233. entries = avio_rb32(pb);
  2234. if (entries <= 0) {
  2235. av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
  2236. return AVERROR_INVALIDDATA;
  2237. }
  2238. if (sc->extradata) {
  2239. av_log(c->fc, AV_LOG_ERROR,
  2240. "Duplicate stsd found in this track.\n");
  2241. return AVERROR_INVALIDDATA;
  2242. }
  2243. /* Prepare space for hosting multiple extradata. */
  2244. sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
  2245. if (!sc->extradata)
  2246. return AVERROR(ENOMEM);
  2247. sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size));
  2248. if (!sc->extradata_size) {
  2249. ret = AVERROR(ENOMEM);
  2250. goto fail;
  2251. }
  2252. ret = ff_mov_read_stsd_entries(c, pb, entries);
  2253. if (ret < 0)
  2254. goto fail;
  2255. /* Restore back the primary extradata. */
  2256. av_freep(&st->codecpar->extradata);
  2257. st->codecpar->extradata_size = sc->extradata_size[0];
  2258. if (sc->extradata_size[0]) {
  2259. st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
  2260. if (!st->codecpar->extradata)
  2261. return AVERROR(ENOMEM);
  2262. memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
  2263. }
  2264. return mov_finalize_stsd_codec(c, pb, st, sc);
  2265. fail:
  2266. if (sc->extradata) {
  2267. int j;
  2268. for (j = 0; j < sc->stsd_count; j++)
  2269. av_freep(&sc->extradata[j]);
  2270. }
  2271. av_freep(&sc->extradata);
  2272. av_freep(&sc->extradata_size);
  2273. return ret;
  2274. }
  2275. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2276. {
  2277. AVStream *st;
  2278. MOVStreamContext *sc;
  2279. unsigned int i, entries;
  2280. if (c->fc->nb_streams < 1)
  2281. return 0;
  2282. st = c->fc->streams[c->fc->nb_streams-1];
  2283. sc = st->priv_data;
  2284. avio_r8(pb); /* version */
  2285. avio_rb24(pb); /* flags */
  2286. entries = avio_rb32(pb);
  2287. if ((uint64_t)entries * 12 + 4 > atom.size)
  2288. return AVERROR_INVALIDDATA;
  2289. av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
  2290. if (!entries)
  2291. return 0;
  2292. if (sc->stsc_data)
  2293. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
  2294. av_free(sc->stsc_data);
  2295. sc->stsc_count = 0;
  2296. sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
  2297. if (!sc->stsc_data)
  2298. return AVERROR(ENOMEM);
  2299. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2300. sc->stsc_data[i].first = avio_rb32(pb);
  2301. sc->stsc_data[i].count = avio_rb32(pb);
  2302. sc->stsc_data[i].id = avio_rb32(pb);
  2303. }
  2304. sc->stsc_count = i;
  2305. for (i = sc->stsc_count - 1; i < UINT_MAX; i--) {
  2306. int64_t first_min = i + 1;
  2307. if ((i+1 < sc->stsc_count && sc->stsc_data[i].first >= sc->stsc_data[i+1].first) ||
  2308. (i > 0 && sc->stsc_data[i].first <= sc->stsc_data[i-1].first) ||
  2309. sc->stsc_data[i].first < first_min ||
  2310. sc->stsc_data[i].count < 1 ||
  2311. sc->stsc_data[i].id < 1) {
  2312. av_log(c->fc, AV_LOG_WARNING, "STSC entry %d is invalid (first=%d count=%d id=%d)\n", i, sc->stsc_data[i].first, sc->stsc_data[i].count, sc->stsc_data[i].id);
  2313. if (i+1 >= sc->stsc_count) {
  2314. sc->stsc_data[i].first = FFMAX(sc->stsc_data[i].first, first_min);
  2315. if (i > 0 && sc->stsc_data[i].first <= sc->stsc_data[i-1].first)
  2316. sc->stsc_data[i].first = FFMIN(sc->stsc_data[i-1].first + 1LL, INT_MAX);
  2317. sc->stsc_data[i].count = FFMAX(sc->stsc_data[i].count, 1);
  2318. sc->stsc_data[i].id = FFMAX(sc->stsc_data[i].id, 1);
  2319. continue;
  2320. }
  2321. av_assert0(sc->stsc_data[i+1].first >= 2);
  2322. // We replace this entry by the next valid
  2323. sc->stsc_data[i].first = sc->stsc_data[i+1].first - 1;
  2324. sc->stsc_data[i].count = sc->stsc_data[i+1].count;
  2325. sc->stsc_data[i].id = sc->stsc_data[i+1].id;
  2326. }
  2327. }
  2328. if (pb->eof_reached) {
  2329. av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSC atom\n");
  2330. return AVERROR_EOF;
  2331. }
  2332. return 0;
  2333. }
  2334. static inline int mov_stsc_index_valid(unsigned int index, unsigned int count)
  2335. {
  2336. return index < count - 1;
  2337. }
  2338. /* Compute the samples value for the stsc entry at the given index. */
  2339. static inline int64_t mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
  2340. {
  2341. int chunk_count;
  2342. if (mov_stsc_index_valid(index, sc->stsc_count))
  2343. chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
  2344. else
  2345. chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
  2346. return sc->stsc_data[index].count * (int64_t)chunk_count;
  2347. }
  2348. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2349. {
  2350. AVStream *st;
  2351. MOVStreamContext *sc;
  2352. unsigned i, entries;
  2353. if (c->fc->nb_streams < 1)
  2354. return 0;
  2355. st = c->fc->streams[c->fc->nb_streams-1];
  2356. sc = st->priv_data;
  2357. avio_rb32(pb); // version + flags
  2358. entries = avio_rb32(pb);
  2359. if (sc->stps_data)
  2360. av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
  2361. av_free(sc->stps_data);
  2362. sc->stps_count = 0;
  2363. sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
  2364. if (!sc->stps_data)
  2365. return AVERROR(ENOMEM);
  2366. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2367. sc->stps_data[i] = avio_rb32(pb);
  2368. }
  2369. sc->stps_count = i;
  2370. if (pb->eof_reached) {
  2371. av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STPS atom\n");
  2372. return AVERROR_EOF;
  2373. }
  2374. return 0;
  2375. }
  2376. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2377. {
  2378. AVStream *st;
  2379. MOVStreamContext *sc;
  2380. unsigned int i, entries;
  2381. if (c->fc->nb_streams < 1)
  2382. return 0;
  2383. st = c->fc->streams[c->fc->nb_streams-1];
  2384. sc = st->priv_data;
  2385. avio_r8(pb); /* version */
  2386. avio_rb24(pb); /* flags */
  2387. entries = avio_rb32(pb);
  2388. av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
  2389. if (!entries)
  2390. {
  2391. sc->keyframe_absent = 1;
  2392. if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  2393. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  2394. return 0;
  2395. }
  2396. if (sc->keyframes)
  2397. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
  2398. if (entries >= UINT_MAX / sizeof(int))
  2399. return AVERROR_INVALIDDATA;
  2400. av_freep(&sc->keyframes);
  2401. sc->keyframe_count = 0;
  2402. sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
  2403. if (!sc->keyframes)
  2404. return AVERROR(ENOMEM);
  2405. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2406. sc->keyframes[i] = avio_rb32(pb);
  2407. }
  2408. sc->keyframe_count = i;
  2409. if (pb->eof_reached) {
  2410. av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSS atom\n");
  2411. return AVERROR_EOF;
  2412. }
  2413. return 0;
  2414. }
  2415. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2416. {
  2417. AVStream *st;
  2418. MOVStreamContext *sc;
  2419. unsigned int i, entries, sample_size, field_size, num_bytes;
  2420. GetBitContext gb;
  2421. unsigned char* buf;
  2422. int ret;
  2423. if (c->fc->nb_streams < 1)
  2424. return 0;
  2425. st = c->fc->streams[c->fc->nb_streams-1];
  2426. sc = st->priv_data;
  2427. avio_r8(pb); /* version */
  2428. avio_rb24(pb); /* flags */
  2429. if (atom.type == MKTAG('s','t','s','z')) {
  2430. sample_size = avio_rb32(pb);
  2431. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  2432. sc->sample_size = sample_size;
  2433. sc->stsz_sample_size = sample_size;
  2434. field_size = 32;
  2435. } else {
  2436. sample_size = 0;
  2437. avio_rb24(pb); /* reserved */
  2438. field_size = avio_r8(pb);
  2439. }
  2440. entries = avio_rb32(pb);
  2441. av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
  2442. sc->sample_count = entries;
  2443. if (sample_size)
  2444. return 0;
  2445. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  2446. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
  2447. return AVERROR_INVALIDDATA;
  2448. }
  2449. if (!entries)
  2450. return 0;
  2451. if (entries >= (UINT_MAX - 4) / field_size)
  2452. return AVERROR_INVALIDDATA;
  2453. if (sc->sample_sizes)
  2454. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
  2455. av_free(sc->sample_sizes);
  2456. sc->sample_count = 0;
  2457. sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
  2458. if (!sc->sample_sizes)
  2459. return AVERROR(ENOMEM);
  2460. num_bytes = (entries*field_size+4)>>3;
  2461. buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
  2462. if (!buf) {
  2463. av_freep(&sc->sample_sizes);
  2464. return AVERROR(ENOMEM);
  2465. }
  2466. ret = ffio_read_size(pb, buf, num_bytes);
  2467. if (ret < 0) {
  2468. av_freep(&sc->sample_sizes);
  2469. av_free(buf);
  2470. av_log(c->fc, AV_LOG_WARNING, "STSZ atom truncated\n");
  2471. return 0;
  2472. }
  2473. init_get_bits(&gb, buf, 8*num_bytes);
  2474. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2475. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  2476. sc->data_size += sc->sample_sizes[i];
  2477. }
  2478. sc->sample_count = i;
  2479. av_free(buf);
  2480. if (pb->eof_reached) {
  2481. av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSZ atom\n");
  2482. return AVERROR_EOF;
  2483. }
  2484. return 0;
  2485. }
  2486. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2487. {
  2488. AVStream *st;
  2489. MOVStreamContext *sc;
  2490. unsigned int i, entries, alloc_size = 0;
  2491. int64_t duration=0;
  2492. int64_t total_sample_count=0;
  2493. if (c->fc->nb_streams < 1)
  2494. return 0;
  2495. st = c->fc->streams[c->fc->nb_streams-1];
  2496. sc = st->priv_data;
  2497. avio_r8(pb); /* version */
  2498. avio_rb24(pb); /* flags */
  2499. entries = avio_rb32(pb);
  2500. av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
  2501. c->fc->nb_streams-1, entries);
  2502. if (sc->stts_data)
  2503. av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
  2504. av_freep(&sc->stts_data);
  2505. sc->stts_count = 0;
  2506. if (entries >= INT_MAX / sizeof(*sc->stts_data))
  2507. return AVERROR(ENOMEM);
  2508. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2509. int sample_duration;
  2510. unsigned int sample_count;
  2511. unsigned int min_entries = FFMIN(FFMAX(i + 1, 1024 * 1024), entries);
  2512. MOVStts *stts_data = av_fast_realloc(sc->stts_data, &alloc_size,
  2513. min_entries * sizeof(*sc->stts_data));
  2514. if (!stts_data) {
  2515. av_freep(&sc->stts_data);
  2516. sc->stts_count = 0;
  2517. return AVERROR(ENOMEM);
  2518. }
  2519. sc->stts_count = min_entries;
  2520. sc->stts_data = stts_data;
  2521. sample_count=avio_rb32(pb);
  2522. sample_duration = avio_rb32(pb);
  2523. sc->stts_data[i].count= sample_count;
  2524. sc->stts_data[i].duration= sample_duration;
  2525. av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
  2526. sample_count, sample_duration);
  2527. if ( i+1 == entries
  2528. && i
  2529. && sample_count == 1
  2530. && total_sample_count > 100
  2531. && sample_duration/10 > duration / total_sample_count)
  2532. sample_duration = duration / total_sample_count;
  2533. duration+=(int64_t)sample_duration*(uint64_t)sample_count;
  2534. total_sample_count+=sample_count;
  2535. }
  2536. sc->stts_count = i;
  2537. if (duration > 0 &&
  2538. duration <= INT64_MAX - sc->duration_for_fps &&
  2539. total_sample_count <= INT64_MAX - sc->nb_frames_for_fps
  2540. ) {
  2541. sc->duration_for_fps += duration;
  2542. sc->nb_frames_for_fps += total_sample_count;
  2543. }
  2544. if (pb->eof_reached) {
  2545. av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STTS atom\n");
  2546. return AVERROR_EOF;
  2547. }
  2548. st->nb_frames= total_sample_count;
  2549. if (duration)
  2550. st->duration= FFMIN(st->duration, duration);
  2551. sc->track_end = duration;
  2552. return 0;
  2553. }
  2554. static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
  2555. {
  2556. if (duration < 0) {
  2557. if (duration == INT_MIN) {
  2558. av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
  2559. duration++;
  2560. }
  2561. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  2562. }
  2563. }
  2564. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2565. {
  2566. AVStream *st;
  2567. MOVStreamContext *sc;
  2568. unsigned int i, entries, ctts_count = 0;
  2569. if (c->fc->nb_streams < 1)
  2570. return 0;
  2571. st = c->fc->streams[c->fc->nb_streams-1];
  2572. sc = st->priv_data;
  2573. avio_r8(pb); /* version */
  2574. avio_rb24(pb); /* flags */
  2575. entries = avio_rb32(pb);
  2576. av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
  2577. if (!entries)
  2578. return 0;
  2579. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  2580. return AVERROR_INVALIDDATA;
  2581. av_freep(&sc->ctts_data);
  2582. sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data));
  2583. if (!sc->ctts_data)
  2584. return AVERROR(ENOMEM);
  2585. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2586. int count =avio_rb32(pb);
  2587. int duration =avio_rb32(pb);
  2588. if (count <= 0) {
  2589. av_log(c->fc, AV_LOG_TRACE,
  2590. "ignoring CTTS entry with count=%d duration=%d\n",
  2591. count, duration);
  2592. continue;
  2593. }
  2594. add_ctts_entry(&sc->ctts_data, &ctts_count, &sc->ctts_allocated_size,
  2595. count, duration);
  2596. av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
  2597. count, duration);
  2598. if (FFNABS(duration) < -(1<<28) && i+2<entries) {
  2599. av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
  2600. av_freep(&sc->ctts_data);
  2601. sc->ctts_count = 0;
  2602. return 0;
  2603. }
  2604. if (i+2<entries)
  2605. mov_update_dts_shift(sc, duration);
  2606. }
  2607. sc->ctts_count = ctts_count;
  2608. if (pb->eof_reached) {
  2609. av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted CTTS atom\n");
  2610. return AVERROR_EOF;
  2611. }
  2612. av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
  2613. return 0;
  2614. }
  2615. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2616. {
  2617. AVStream *st;
  2618. MOVStreamContext *sc;
  2619. unsigned int i, entries;
  2620. uint8_t version;
  2621. uint32_t grouping_type;
  2622. if (c->fc->nb_streams < 1)
  2623. return 0;
  2624. st = c->fc->streams[c->fc->nb_streams-1];
  2625. sc = st->priv_data;
  2626. version = avio_r8(pb); /* version */
  2627. avio_rb24(pb); /* flags */
  2628. grouping_type = avio_rl32(pb);
  2629. if (grouping_type != MKTAG( 'r','a','p',' '))
  2630. return 0; /* only support 'rap ' grouping */
  2631. if (version == 1)
  2632. avio_rb32(pb); /* grouping_type_parameter */
  2633. entries = avio_rb32(pb);
  2634. if (!entries)
  2635. return 0;
  2636. if (sc->rap_group)
  2637. av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
  2638. av_free(sc->rap_group);
  2639. sc->rap_group_count = 0;
  2640. sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
  2641. if (!sc->rap_group)
  2642. return AVERROR(ENOMEM);
  2643. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2644. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  2645. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  2646. }
  2647. sc->rap_group_count = i;
  2648. if (pb->eof_reached) {
  2649. av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted SBGP atom\n");
  2650. return AVERROR_EOF;
  2651. }
  2652. return 0;
  2653. }
  2654. /**
  2655. * Get ith edit list entry (media time, duration).
  2656. */
  2657. static int get_edit_list_entry(MOVContext *mov,
  2658. const MOVStreamContext *msc,
  2659. unsigned int edit_list_index,
  2660. int64_t *edit_list_media_time,
  2661. int64_t *edit_list_duration,
  2662. int64_t global_timescale)
  2663. {
  2664. if (edit_list_index == msc->elst_count) {
  2665. return 0;
  2666. }
  2667. *edit_list_media_time = msc->elst_data[edit_list_index].time;
  2668. *edit_list_duration = msc->elst_data[edit_list_index].duration;
  2669. /* duration is in global timescale units;convert to msc timescale */
  2670. if (global_timescale == 0) {
  2671. avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
  2672. return 0;
  2673. }
  2674. *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
  2675. global_timescale);
  2676. return 1;
  2677. }
  2678. /**
  2679. * Find the closest previous frame to the timestamp_pts, in e_old index
  2680. * entries. Searching for just any frame / just key frames can be controlled by
  2681. * last argument 'flag'.
  2682. * Note that if ctts_data is not NULL, we will always search for a key frame
  2683. * irrespective of the value of 'flag'. If we don't find any keyframe, we will
  2684. * return the first frame of the video.
  2685. *
  2686. * Here the timestamp_pts is considered to be a presentation timestamp and
  2687. * the timestamp of index entries are considered to be decoding timestamps.
  2688. *
  2689. * Returns 0 if successful in finding a frame, else returns -1.
  2690. * Places the found index corresponding output arg.
  2691. *
  2692. * If ctts_old is not NULL, then refines the searched entry by searching
  2693. * backwards from the found timestamp, to find the frame with correct PTS.
  2694. *
  2695. * Places the found ctts_index and ctts_sample in corresponding output args.
  2696. */
  2697. static int find_prev_closest_index(AVStream *st,
  2698. AVIndexEntry *e_old,
  2699. int nb_old,
  2700. MOVStts* ctts_data,
  2701. int64_t ctts_count,
  2702. int64_t timestamp_pts,
  2703. int flag,
  2704. int64_t* index,
  2705. int64_t* ctts_index,
  2706. int64_t* ctts_sample)
  2707. {
  2708. MOVStreamContext *msc = st->priv_data;
  2709. AVIndexEntry *e_keep = st->index_entries;
  2710. int nb_keep = st->nb_index_entries;
  2711. int64_t i = 0;
  2712. int64_t index_ctts_count;
  2713. av_assert0(index);
  2714. // If dts_shift > 0, then all the index timestamps will have to be offset by
  2715. // at least dts_shift amount to obtain PTS.
  2716. // Hence we decrement the searched timestamp_pts by dts_shift to find the closest index element.
  2717. if (msc->dts_shift > 0) {
  2718. timestamp_pts -= msc->dts_shift;
  2719. }
  2720. st->index_entries = e_old;
  2721. st->nb_index_entries = nb_old;
  2722. *index = av_index_search_timestamp(st, timestamp_pts, flag | AVSEEK_FLAG_BACKWARD);
  2723. // Keep going backwards in the index entries until the timestamp is the same.
  2724. if (*index >= 0) {
  2725. for (i = *index; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
  2726. i--) {
  2727. if ((flag & AVSEEK_FLAG_ANY) ||
  2728. (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
  2729. *index = i - 1;
  2730. }
  2731. }
  2732. }
  2733. // If we have CTTS then refine the search, by searching backwards over PTS
  2734. // computed by adding corresponding CTTS durations to index timestamps.
  2735. if (ctts_data && *index >= 0) {
  2736. av_assert0(ctts_index);
  2737. av_assert0(ctts_sample);
  2738. // Find out the ctts_index for the found frame.
  2739. *ctts_index = 0;
  2740. *ctts_sample = 0;
  2741. for (index_ctts_count = 0; index_ctts_count < *index; index_ctts_count++) {
  2742. if (*ctts_index < ctts_count) {
  2743. (*ctts_sample)++;
  2744. if (ctts_data[*ctts_index].count == *ctts_sample) {
  2745. (*ctts_index)++;
  2746. *ctts_sample = 0;
  2747. }
  2748. }
  2749. }
  2750. while (*index >= 0 && (*ctts_index) >= 0 && (*ctts_index) < ctts_count) {
  2751. // Find a "key frame" with PTS <= timestamp_pts (So that we can decode B-frames correctly).
  2752. // No need to add dts_shift to the timestamp here becase timestamp_pts has already been
  2753. // compensated by dts_shift above.
  2754. if ((e_old[*index].timestamp + ctts_data[*ctts_index].duration) <= timestamp_pts &&
  2755. (e_old[*index].flags & AVINDEX_KEYFRAME)) {
  2756. break;
  2757. }
  2758. (*index)--;
  2759. if (*ctts_sample == 0) {
  2760. (*ctts_index)--;
  2761. if (*ctts_index >= 0)
  2762. *ctts_sample = ctts_data[*ctts_index].count - 1;
  2763. } else {
  2764. (*ctts_sample)--;
  2765. }
  2766. }
  2767. }
  2768. /* restore AVStream state*/
  2769. st->index_entries = e_keep;
  2770. st->nb_index_entries = nb_keep;
  2771. return *index >= 0 ? 0 : -1;
  2772. }
  2773. /**
  2774. * Add index entry with the given values, to the end of st->index_entries.
  2775. * Returns the new size st->index_entries if successful, else returns -1.
  2776. *
  2777. * This function is similar to ff_add_index_entry in libavformat/utils.c
  2778. * except that here we are always unconditionally adding an index entry to
  2779. * the end, instead of searching the entries list and skipping the add if
  2780. * there is an existing entry with the same timestamp.
  2781. * This is needed because the mov_fix_index calls this func with the same
  2782. * unincremented timestamp for successive discarded frames.
  2783. */
  2784. static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
  2785. int size, int distance, int flags)
  2786. {
  2787. AVIndexEntry *entries, *ie;
  2788. int64_t index = -1;
  2789. const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
  2790. // Double the allocation each time, to lower memory fragmentation.
  2791. // Another difference from ff_add_index_entry function.
  2792. const size_t requested_size =
  2793. min_size_needed > st->index_entries_allocated_size ?
  2794. FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
  2795. min_size_needed;
  2796. if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
  2797. return -1;
  2798. entries = av_fast_realloc(st->index_entries,
  2799. &st->index_entries_allocated_size,
  2800. requested_size);
  2801. if(!entries)
  2802. return -1;
  2803. st->index_entries= entries;
  2804. index= st->nb_index_entries++;
  2805. ie= &entries[index];
  2806. ie->pos = pos;
  2807. ie->timestamp = timestamp;
  2808. ie->min_distance= distance;
  2809. ie->size= size;
  2810. ie->flags = flags;
  2811. return index;
  2812. }
  2813. /**
  2814. * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
  2815. * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
  2816. */
  2817. static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
  2818. int64_t* frame_duration_buffer,
  2819. int frame_duration_buffer_size) {
  2820. int i = 0;
  2821. av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
  2822. for (i = 0; i < frame_duration_buffer_size; i++) {
  2823. end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
  2824. st->index_entries[end_index - 1 - i].timestamp = end_ts;
  2825. }
  2826. }
  2827. /**
  2828. * Append a new ctts entry to ctts_data.
  2829. * Returns the new ctts_count if successful, else returns -1.
  2830. */
  2831. static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
  2832. int count, int duration)
  2833. {
  2834. MOVStts *ctts_buf_new;
  2835. const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
  2836. const size_t requested_size =
  2837. min_size_needed > *allocated_size ?
  2838. FFMAX(min_size_needed, 2 * (*allocated_size)) :
  2839. min_size_needed;
  2840. if((unsigned)(*ctts_count) >= UINT_MAX / sizeof(MOVStts) - 1)
  2841. return -1;
  2842. ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
  2843. if(!ctts_buf_new)
  2844. return -1;
  2845. *ctts_data = ctts_buf_new;
  2846. ctts_buf_new[*ctts_count].count = count;
  2847. ctts_buf_new[*ctts_count].duration = duration;
  2848. *ctts_count = (*ctts_count) + 1;
  2849. return *ctts_count;
  2850. }
  2851. #define MAX_REORDER_DELAY 16
  2852. static void mov_estimate_video_delay(MOVContext *c, AVStream* st) {
  2853. MOVStreamContext *msc = st->priv_data;
  2854. int ind;
  2855. int ctts_ind = 0;
  2856. int ctts_sample = 0;
  2857. int64_t pts_buf[MAX_REORDER_DELAY + 1]; // Circular buffer to sort pts.
  2858. int buf_start = 0;
  2859. int j, r, num_swaps;
  2860. for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
  2861. pts_buf[j] = INT64_MIN;
  2862. if (st->codecpar->video_delay <= 0 && msc->ctts_data &&
  2863. st->codecpar->codec_id == AV_CODEC_ID_H264) {
  2864. st->codecpar->video_delay = 0;
  2865. for(ind = 0; ind < st->nb_index_entries && ctts_ind < msc->ctts_count; ++ind) {
  2866. // Point j to the last elem of the buffer and insert the current pts there.
  2867. j = buf_start;
  2868. buf_start = (buf_start + 1);
  2869. if (buf_start == MAX_REORDER_DELAY + 1)
  2870. buf_start = 0;
  2871. pts_buf[j] = st->index_entries[ind].timestamp + msc->ctts_data[ctts_ind].duration;
  2872. // The timestamps that are already in the sorted buffer, and are greater than the
  2873. // current pts, are exactly the timestamps that need to be buffered to output PTS
  2874. // in correct sorted order.
  2875. // Hence the video delay (which is the buffer size used to sort DTS and output PTS),
  2876. // can be computed as the maximum no. of swaps any particular timestamp needs to
  2877. // go through, to keep this buffer in sorted order.
  2878. num_swaps = 0;
  2879. while (j != buf_start) {
  2880. r = j - 1;
  2881. if (r < 0) r = MAX_REORDER_DELAY;
  2882. if (pts_buf[j] < pts_buf[r]) {
  2883. FFSWAP(int64_t, pts_buf[j], pts_buf[r]);
  2884. ++num_swaps;
  2885. } else {
  2886. break;
  2887. }
  2888. j = r;
  2889. }
  2890. st->codecpar->video_delay = FFMAX(st->codecpar->video_delay, num_swaps);
  2891. ctts_sample++;
  2892. if (ctts_sample == msc->ctts_data[ctts_ind].count) {
  2893. ctts_ind++;
  2894. ctts_sample = 0;
  2895. }
  2896. }
  2897. av_log(c->fc, AV_LOG_DEBUG, "Setting codecpar->delay to %d for stream st: %d\n",
  2898. st->codecpar->video_delay, st->index);
  2899. }
  2900. }
  2901. static void mov_current_sample_inc(MOVStreamContext *sc)
  2902. {
  2903. sc->current_sample++;
  2904. sc->current_index++;
  2905. if (sc->index_ranges &&
  2906. sc->current_index >= sc->current_index_range->end &&
  2907. sc->current_index_range->end) {
  2908. sc->current_index_range++;
  2909. sc->current_index = sc->current_index_range->start;
  2910. }
  2911. }
  2912. static void mov_current_sample_dec(MOVStreamContext *sc)
  2913. {
  2914. sc->current_sample--;
  2915. sc->current_index--;
  2916. if (sc->index_ranges &&
  2917. sc->current_index < sc->current_index_range->start &&
  2918. sc->current_index_range > sc->index_ranges) {
  2919. sc->current_index_range--;
  2920. sc->current_index = sc->current_index_range->end - 1;
  2921. }
  2922. }
  2923. static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
  2924. {
  2925. int64_t range_size;
  2926. sc->current_sample = current_sample;
  2927. sc->current_index = current_sample;
  2928. if (!sc->index_ranges) {
  2929. return;
  2930. }
  2931. for (sc->current_index_range = sc->index_ranges;
  2932. sc->current_index_range->end;
  2933. sc->current_index_range++) {
  2934. range_size = sc->current_index_range->end - sc->current_index_range->start;
  2935. if (range_size > current_sample) {
  2936. sc->current_index = sc->current_index_range->start + current_sample;
  2937. break;
  2938. }
  2939. current_sample -= range_size;
  2940. }
  2941. }
  2942. /**
  2943. * Fix st->index_entries, so that it contains only the entries (and the entries
  2944. * which are needed to decode them) that fall in the edit list time ranges.
  2945. * Also fixes the timestamps of the index entries to match the timeline
  2946. * specified the edit lists.
  2947. */
  2948. static void mov_fix_index(MOVContext *mov, AVStream *st)
  2949. {
  2950. MOVStreamContext *msc = st->priv_data;
  2951. AVIndexEntry *e_old = st->index_entries;
  2952. int nb_old = st->nb_index_entries;
  2953. const AVIndexEntry *e_old_end = e_old + nb_old;
  2954. const AVIndexEntry *current = NULL;
  2955. MOVStts *ctts_data_old = msc->ctts_data;
  2956. int64_t ctts_index_old = 0;
  2957. int64_t ctts_sample_old = 0;
  2958. int64_t ctts_count_old = msc->ctts_count;
  2959. int64_t edit_list_media_time = 0;
  2960. int64_t edit_list_duration = 0;
  2961. int64_t frame_duration = 0;
  2962. int64_t edit_list_dts_counter = 0;
  2963. int64_t edit_list_dts_entry_end = 0;
  2964. int64_t edit_list_start_ctts_sample = 0;
  2965. int64_t curr_cts;
  2966. int64_t curr_ctts = 0;
  2967. int64_t empty_edits_sum_duration = 0;
  2968. int64_t edit_list_index = 0;
  2969. int64_t index;
  2970. int flags;
  2971. int64_t start_dts = 0;
  2972. int64_t edit_list_start_encountered = 0;
  2973. int64_t search_timestamp = 0;
  2974. int64_t* frame_duration_buffer = NULL;
  2975. int num_discarded_begin = 0;
  2976. int first_non_zero_audio_edit = -1;
  2977. int packet_skip_samples = 0;
  2978. MOVIndexRange *current_index_range;
  2979. int i;
  2980. int found_keyframe_after_edit = 0;
  2981. if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
  2982. return;
  2983. }
  2984. // allocate the index ranges array
  2985. msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));
  2986. if (!msc->index_ranges) {
  2987. av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
  2988. return;
  2989. }
  2990. msc->current_index_range = msc->index_ranges;
  2991. current_index_range = msc->index_ranges - 1;
  2992. // Clean AVStream from traces of old index
  2993. st->index_entries = NULL;
  2994. st->index_entries_allocated_size = 0;
  2995. st->nb_index_entries = 0;
  2996. // Clean ctts fields of MOVStreamContext
  2997. msc->ctts_data = NULL;
  2998. msc->ctts_count = 0;
  2999. msc->ctts_index = 0;
  3000. msc->ctts_sample = 0;
  3001. msc->ctts_allocated_size = 0;
  3002. // Reinitialize min_corrected_pts so that it can be computed again.
  3003. msc->min_corrected_pts = -1;
  3004. // If the dts_shift is positive (in case of negative ctts values in mov),
  3005. // then negate the DTS by dts_shift
  3006. if (msc->dts_shift > 0) {
  3007. edit_list_dts_entry_end -= msc->dts_shift;
  3008. av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift);
  3009. }
  3010. start_dts = edit_list_dts_entry_end;
  3011. while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
  3012. &edit_list_duration, mov->time_scale)) {
  3013. av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
  3014. st->index, edit_list_index, edit_list_media_time, edit_list_duration);
  3015. edit_list_index++;
  3016. edit_list_dts_counter = edit_list_dts_entry_end;
  3017. edit_list_dts_entry_end += edit_list_duration;
  3018. num_discarded_begin = 0;
  3019. if (edit_list_media_time == -1) {
  3020. empty_edits_sum_duration += edit_list_duration;
  3021. continue;
  3022. }
  3023. // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
  3024. // according to the edit list below.
  3025. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  3026. if (first_non_zero_audio_edit < 0) {
  3027. first_non_zero_audio_edit = 1;
  3028. } else {
  3029. first_non_zero_audio_edit = 0;
  3030. }
  3031. if (first_non_zero_audio_edit > 0)
  3032. st->skip_samples = msc->start_pad = 0;
  3033. }
  3034. // While reordering frame index according to edit list we must handle properly
  3035. // the scenario when edit list entry starts from none key frame.
  3036. // We find closest previous key frame and preserve it and consequent frames in index.
  3037. // All frames which are outside edit list entry time boundaries will be dropped after decoding.
  3038. search_timestamp = edit_list_media_time;
  3039. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  3040. // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
  3041. // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
  3042. // edit_list_media_time to cover the decoder delay.
  3043. search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
  3044. }
  3045. if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, 0,
  3046. &index, &ctts_index_old, &ctts_sample_old) < 0) {
  3047. av_log(mov->fc, AV_LOG_WARNING,
  3048. "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
  3049. st->index, edit_list_index, search_timestamp);
  3050. if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, AVSEEK_FLAG_ANY,
  3051. &index, &ctts_index_old, &ctts_sample_old) < 0) {
  3052. av_log(mov->fc, AV_LOG_WARNING,
  3053. "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n",
  3054. st->index, edit_list_index, search_timestamp);
  3055. index = 0;
  3056. ctts_index_old = 0;
  3057. ctts_sample_old = 0;
  3058. }
  3059. }
  3060. current = e_old + index;
  3061. edit_list_start_ctts_sample = ctts_sample_old;
  3062. // Iterate over index and arrange it according to edit list
  3063. edit_list_start_encountered = 0;
  3064. found_keyframe_after_edit = 0;
  3065. for (; current < e_old_end; current++, index++) {
  3066. // check if frame outside edit list mark it for discard
  3067. frame_duration = (current + 1 < e_old_end) ?
  3068. ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
  3069. flags = current->flags;
  3070. // frames (pts) before or after edit list
  3071. curr_cts = current->timestamp + msc->dts_shift;
  3072. curr_ctts = 0;
  3073. if (ctts_data_old && ctts_index_old < ctts_count_old) {
  3074. curr_ctts = ctts_data_old[ctts_index_old].duration;
  3075. av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n",
  3076. curr_cts, curr_ctts, ctts_index_old, ctts_count_old);
  3077. curr_cts += curr_ctts;
  3078. ctts_sample_old++;
  3079. if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
  3080. if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
  3081. &msc->ctts_allocated_size,
  3082. ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
  3083. ctts_data_old[ctts_index_old].duration) == -1) {
  3084. av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
  3085. ctts_index_old,
  3086. ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
  3087. ctts_data_old[ctts_index_old].duration);
  3088. break;
  3089. }
  3090. ctts_index_old++;
  3091. ctts_sample_old = 0;
  3092. edit_list_start_ctts_sample = 0;
  3093. }
  3094. }
  3095. if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
  3096. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
  3097. curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
  3098. first_non_zero_audio_edit > 0) {
  3099. packet_skip_samples = edit_list_media_time - curr_cts;
  3100. st->skip_samples += packet_skip_samples;
  3101. // Shift the index entry timestamp by packet_skip_samples to be correct.
  3102. edit_list_dts_counter -= packet_skip_samples;
  3103. if (edit_list_start_encountered == 0) {
  3104. edit_list_start_encountered = 1;
  3105. // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
  3106. // discarded packets.
  3107. if (frame_duration_buffer) {
  3108. fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
  3109. frame_duration_buffer, num_discarded_begin);
  3110. av_freep(&frame_duration_buffer);
  3111. }
  3112. }
  3113. av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
  3114. } else {
  3115. flags |= AVINDEX_DISCARD_FRAME;
  3116. av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
  3117. if (edit_list_start_encountered == 0) {
  3118. num_discarded_begin++;
  3119. frame_duration_buffer = av_realloc(frame_duration_buffer,
  3120. num_discarded_begin * sizeof(int64_t));
  3121. if (!frame_duration_buffer) {
  3122. av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
  3123. break;
  3124. }
  3125. frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
  3126. // Increment skip_samples for the first non-zero audio edit list
  3127. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  3128. first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
  3129. st->skip_samples += frame_duration;
  3130. }
  3131. }
  3132. }
  3133. } else {
  3134. if (msc->min_corrected_pts < 0) {
  3135. msc->min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift;
  3136. } else {
  3137. msc->min_corrected_pts = FFMIN(msc->min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift);
  3138. }
  3139. if (edit_list_start_encountered == 0) {
  3140. edit_list_start_encountered = 1;
  3141. // Make timestamps strictly monotonically increasing by rewriting timestamps for
  3142. // discarded packets.
  3143. if (frame_duration_buffer) {
  3144. fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
  3145. frame_duration_buffer, num_discarded_begin);
  3146. av_freep(&frame_duration_buffer);
  3147. }
  3148. }
  3149. }
  3150. if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
  3151. current->min_distance, flags) == -1) {
  3152. av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
  3153. break;
  3154. }
  3155. // Update the index ranges array
  3156. if (current_index_range < msc->index_ranges || index != current_index_range->end) {
  3157. current_index_range++;
  3158. current_index_range->start = index;
  3159. }
  3160. current_index_range->end = index + 1;
  3161. // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
  3162. if (edit_list_start_encountered > 0) {
  3163. edit_list_dts_counter = edit_list_dts_counter + frame_duration;
  3164. }
  3165. // Break when found first key frame after edit entry completion
  3166. if ((curr_cts + frame_duration >= (edit_list_duration + edit_list_media_time)) &&
  3167. ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
  3168. if (ctts_data_old) {
  3169. // If we have CTTS and this is the first keyframe after edit elist,
  3170. // wait for one more, because there might be trailing B-frames after this I-frame
  3171. // that do belong to the edit.
  3172. if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO && found_keyframe_after_edit == 0) {
  3173. found_keyframe_after_edit = 1;
  3174. continue;
  3175. }
  3176. if (ctts_sample_old != 0) {
  3177. if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
  3178. &msc->ctts_allocated_size,
  3179. ctts_sample_old - edit_list_start_ctts_sample,
  3180. ctts_data_old[ctts_index_old].duration) == -1) {
  3181. av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
  3182. ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
  3183. ctts_data_old[ctts_index_old].duration);
  3184. break;
  3185. }
  3186. }
  3187. }
  3188. break;
  3189. }
  3190. }
  3191. }
  3192. // If there are empty edits, then msc->min_corrected_pts might be positive
  3193. // intentionally. So we subtract the sum duration of emtpy edits here.
  3194. msc->min_corrected_pts -= empty_edits_sum_duration;
  3195. // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the
  3196. // dts by that amount to make the first pts zero.
  3197. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  3198. if (msc->min_corrected_pts > 0) {
  3199. av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", msc->min_corrected_pts);
  3200. for (i = 0; i < st->nb_index_entries; ++i) {
  3201. st->index_entries[i].timestamp -= msc->min_corrected_pts;
  3202. }
  3203. }
  3204. }
  3205. // Start time should be equal to zero or the duration of any empty edits.
  3206. st->start_time = empty_edits_sum_duration;
  3207. // Update av stream length, if it ends up shorter than the track's media duration
  3208. st->duration = FFMIN(st->duration, edit_list_dts_entry_end - start_dts);
  3209. msc->start_pad = st->skip_samples;
  3210. // Free the old index and the old CTTS structures
  3211. av_free(e_old);
  3212. av_free(ctts_data_old);
  3213. av_freep(&frame_duration_buffer);
  3214. // Null terminate the index ranges array
  3215. current_index_range++;
  3216. current_index_range->start = 0;
  3217. current_index_range->end = 0;
  3218. msc->current_index = msc->index_ranges[0].start;
  3219. }
  3220. static void mov_build_index(MOVContext *mov, AVStream *st)
  3221. {
  3222. MOVStreamContext *sc = st->priv_data;
  3223. int64_t current_offset;
  3224. int64_t current_dts = 0;
  3225. unsigned int stts_index = 0;
  3226. unsigned int stsc_index = 0;
  3227. unsigned int stss_index = 0;
  3228. unsigned int stps_index = 0;
  3229. unsigned int i, j;
  3230. uint64_t stream_size = 0;
  3231. MOVStts *ctts_data_old = sc->ctts_data;
  3232. unsigned int ctts_count_old = sc->ctts_count;
  3233. if (sc->elst_count) {
  3234. int i, edit_start_index = 0, multiple_edits = 0;
  3235. int64_t empty_duration = 0; // empty duration of the first edit list entry
  3236. int64_t start_time = 0; // start time of the media
  3237. for (i = 0; i < sc->elst_count; i++) {
  3238. const MOVElst *e = &sc->elst_data[i];
  3239. if (i == 0 && e->time == -1) {
  3240. /* if empty, the first entry is the start time of the stream
  3241. * relative to the presentation itself */
  3242. empty_duration = e->duration;
  3243. edit_start_index = 1;
  3244. } else if (i == edit_start_index && e->time >= 0) {
  3245. start_time = e->time;
  3246. } else {
  3247. multiple_edits = 1;
  3248. }
  3249. }
  3250. if (multiple_edits && !mov->advanced_editlist)
  3251. av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
  3252. "Use -advanced_editlist to correctly decode otherwise "
  3253. "a/v desync might occur\n");
  3254. /* adjust first dts according to edit list */
  3255. if ((empty_duration || start_time) && mov->time_scale > 0) {
  3256. if (empty_duration)
  3257. empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
  3258. sc->time_offset = start_time - empty_duration;
  3259. sc->min_corrected_pts = start_time;
  3260. if (!mov->advanced_editlist)
  3261. current_dts = -sc->time_offset;
  3262. }
  3263. if (!multiple_edits && !mov->advanced_editlist &&
  3264. st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
  3265. sc->start_pad = start_time;
  3266. }
  3267. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  3268. if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  3269. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  3270. unsigned int current_sample = 0;
  3271. unsigned int stts_sample = 0;
  3272. unsigned int sample_size;
  3273. unsigned int distance = 0;
  3274. unsigned int rap_group_index = 0;
  3275. unsigned int rap_group_sample = 0;
  3276. int64_t last_dts = 0;
  3277. int64_t dts_correction = 0;
  3278. int rap_group_present = sc->rap_group_count && sc->rap_group;
  3279. int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
  3280. current_dts -= sc->dts_shift;
  3281. last_dts = current_dts;
  3282. if (!sc->sample_count || st->nb_index_entries)
  3283. return;
  3284. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  3285. return;
  3286. if (av_reallocp_array(&st->index_entries,
  3287. st->nb_index_entries + sc->sample_count,
  3288. sizeof(*st->index_entries)) < 0) {
  3289. st->nb_index_entries = 0;
  3290. return;
  3291. }
  3292. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  3293. if (ctts_data_old) {
  3294. // Expand ctts entries such that we have a 1-1 mapping with samples
  3295. if (sc->sample_count >= UINT_MAX / sizeof(*sc->ctts_data))
  3296. return;
  3297. sc->ctts_count = 0;
  3298. sc->ctts_allocated_size = 0;
  3299. sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size,
  3300. sc->sample_count * sizeof(*sc->ctts_data));
  3301. if (!sc->ctts_data) {
  3302. av_free(ctts_data_old);
  3303. return;
  3304. }
  3305. memset((uint8_t*)(sc->ctts_data), 0, sc->ctts_allocated_size);
  3306. for (i = 0; i < ctts_count_old &&
  3307. sc->ctts_count < sc->sample_count; i++)
  3308. for (j = 0; j < ctts_data_old[i].count &&
  3309. sc->ctts_count < sc->sample_count; j++)
  3310. add_ctts_entry(&sc->ctts_data, &sc->ctts_count,
  3311. &sc->ctts_allocated_size, 1,
  3312. ctts_data_old[i].duration);
  3313. av_free(ctts_data_old);
  3314. }
  3315. for (i = 0; i < sc->chunk_count; i++) {
  3316. int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
  3317. current_offset = sc->chunk_offsets[i];
  3318. while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
  3319. i + 1 == sc->stsc_data[stsc_index + 1].first)
  3320. stsc_index++;
  3321. if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
  3322. sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
  3323. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
  3324. sc->stsz_sample_size = sc->sample_size;
  3325. }
  3326. if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
  3327. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
  3328. sc->stsz_sample_size = sc->sample_size;
  3329. }
  3330. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  3331. int keyframe = 0;
  3332. if (current_sample >= sc->sample_count) {
  3333. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  3334. return;
  3335. }
  3336. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  3337. keyframe = 1;
  3338. if (stss_index + 1 < sc->keyframe_count)
  3339. stss_index++;
  3340. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  3341. keyframe = 1;
  3342. if (stps_index + 1 < sc->stps_count)
  3343. stps_index++;
  3344. }
  3345. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  3346. if (sc->rap_group[rap_group_index].index > 0)
  3347. keyframe = 1;
  3348. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  3349. rap_group_sample = 0;
  3350. rap_group_index++;
  3351. }
  3352. }
  3353. if (sc->keyframe_absent
  3354. && !sc->stps_count
  3355. && !rap_group_present
  3356. && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
  3357. keyframe = 1;
  3358. if (keyframe)
  3359. distance = 0;
  3360. sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
  3361. if (sc->pseudo_stream_id == -1 ||
  3362. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  3363. AVIndexEntry *e;
  3364. if (sample_size > 0x3FFFFFFF) {
  3365. av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
  3366. return;
  3367. }
  3368. e = &st->index_entries[st->nb_index_entries++];
  3369. e->pos = current_offset;
  3370. e->timestamp = current_dts;
  3371. e->size = sample_size;
  3372. e->min_distance = distance;
  3373. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  3374. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
  3375. "size %u, distance %u, keyframe %d\n", st->index, current_sample,
  3376. current_offset, current_dts, sample_size, distance, keyframe);
  3377. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
  3378. ff_rfps_add_frame(mov->fc, st, current_dts);
  3379. }
  3380. current_offset += sample_size;
  3381. stream_size += sample_size;
  3382. /* A negative sample duration is invalid based on the spec,
  3383. * but some samples need it to correct the DTS. */
  3384. if (sc->stts_data[stts_index].duration < 0) {
  3385. av_log(mov->fc, AV_LOG_WARNING,
  3386. "Invalid SampleDelta %d in STTS, at %d st:%d\n",
  3387. sc->stts_data[stts_index].duration, stts_index,
  3388. st->index);
  3389. dts_correction += sc->stts_data[stts_index].duration - 1;
  3390. sc->stts_data[stts_index].duration = 1;
  3391. }
  3392. current_dts += sc->stts_data[stts_index].duration;
  3393. if (!dts_correction || current_dts + dts_correction > last_dts) {
  3394. current_dts += dts_correction;
  3395. dts_correction = 0;
  3396. } else {
  3397. /* Avoid creating non-monotonous DTS */
  3398. dts_correction += current_dts - last_dts - 1;
  3399. current_dts = last_dts + 1;
  3400. }
  3401. last_dts = current_dts;
  3402. distance++;
  3403. stts_sample++;
  3404. current_sample++;
  3405. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  3406. stts_sample = 0;
  3407. stts_index++;
  3408. }
  3409. }
  3410. }
  3411. if (st->duration > 0)
  3412. st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
  3413. } else {
  3414. unsigned chunk_samples, total = 0;
  3415. if (!sc->chunk_count)
  3416. return;
  3417. // compute total chunk count
  3418. for (i = 0; i < sc->stsc_count; i++) {
  3419. unsigned count, chunk_count;
  3420. chunk_samples = sc->stsc_data[i].count;
  3421. if (i != sc->stsc_count - 1 &&
  3422. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  3423. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  3424. return;
  3425. }
  3426. if (sc->samples_per_frame >= 160) { // gsm
  3427. count = chunk_samples / sc->samples_per_frame;
  3428. } else if (sc->samples_per_frame > 1) {
  3429. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  3430. count = (chunk_samples+samples-1) / samples;
  3431. } else {
  3432. count = (chunk_samples+1023) / 1024;
  3433. }
  3434. if (mov_stsc_index_valid(i, sc->stsc_count))
  3435. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  3436. else
  3437. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  3438. total += chunk_count * count;
  3439. }
  3440. av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
  3441. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  3442. return;
  3443. if (av_reallocp_array(&st->index_entries,
  3444. st->nb_index_entries + total,
  3445. sizeof(*st->index_entries)) < 0) {
  3446. st->nb_index_entries = 0;
  3447. return;
  3448. }
  3449. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  3450. // populate index
  3451. for (i = 0; i < sc->chunk_count; i++) {
  3452. current_offset = sc->chunk_offsets[i];
  3453. if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
  3454. i + 1 == sc->stsc_data[stsc_index + 1].first)
  3455. stsc_index++;
  3456. chunk_samples = sc->stsc_data[stsc_index].count;
  3457. while (chunk_samples > 0) {
  3458. AVIndexEntry *e;
  3459. unsigned size, samples;
  3460. if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
  3461. avpriv_request_sample(mov->fc,
  3462. "Zero bytes per frame, but %d samples per frame",
  3463. sc->samples_per_frame);
  3464. return;
  3465. }
  3466. if (sc->samples_per_frame >= 160) { // gsm
  3467. samples = sc->samples_per_frame;
  3468. size = sc->bytes_per_frame;
  3469. } else {
  3470. if (sc->samples_per_frame > 1) {
  3471. samples = FFMIN((1024 / sc->samples_per_frame)*
  3472. sc->samples_per_frame, chunk_samples);
  3473. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  3474. } else {
  3475. samples = FFMIN(1024, chunk_samples);
  3476. size = samples * sc->sample_size;
  3477. }
  3478. }
  3479. if (st->nb_index_entries >= total) {
  3480. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
  3481. return;
  3482. }
  3483. if (size > 0x3FFFFFFF) {
  3484. av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
  3485. return;
  3486. }
  3487. e = &st->index_entries[st->nb_index_entries++];
  3488. e->pos = current_offset;
  3489. e->timestamp = current_dts;
  3490. e->size = size;
  3491. e->min_distance = 0;
  3492. e->flags = AVINDEX_KEYFRAME;
  3493. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
  3494. "size %u, duration %u\n", st->index, i, current_offset, current_dts,
  3495. size, samples);
  3496. current_offset += size;
  3497. current_dts += samples;
  3498. chunk_samples -= samples;
  3499. }
  3500. }
  3501. }
  3502. if (!mov->ignore_editlist && mov->advanced_editlist) {
  3503. // Fix index according to edit lists.
  3504. mov_fix_index(mov, st);
  3505. }
  3506. // Update start time of the stream.
  3507. if (st->start_time == AV_NOPTS_VALUE && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries > 0) {
  3508. st->start_time = st->index_entries[0].timestamp + sc->dts_shift;
  3509. if (sc->ctts_data) {
  3510. st->start_time += sc->ctts_data[0].duration;
  3511. }
  3512. }
  3513. mov_estimate_video_delay(mov, st);
  3514. }
  3515. static int test_same_origin(const char *src, const char *ref) {
  3516. char src_proto[64];
  3517. char ref_proto[64];
  3518. char src_auth[256];
  3519. char ref_auth[256];
  3520. char src_host[256];
  3521. char ref_host[256];
  3522. int src_port=-1;
  3523. int ref_port=-1;
  3524. av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
  3525. av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
  3526. if (strlen(src) == 0) {
  3527. return -1;
  3528. } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
  3529. strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
  3530. strlen(src_host) + 1 >= sizeof(src_host) ||
  3531. strlen(ref_host) + 1 >= sizeof(ref_host)) {
  3532. return 0;
  3533. } else if (strcmp(src_proto, ref_proto) ||
  3534. strcmp(src_auth, ref_auth) ||
  3535. strcmp(src_host, ref_host) ||
  3536. src_port != ref_port) {
  3537. return 0;
  3538. } else
  3539. return 1;
  3540. }
  3541. static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
  3542. {
  3543. /* try relative path, we do not try the absolute because it can leak information about our
  3544. system to an attacker */
  3545. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  3546. char filename[1025];
  3547. const char *src_path;
  3548. int i, l;
  3549. /* find a source dir */
  3550. src_path = strrchr(src, '/');
  3551. if (src_path)
  3552. src_path++;
  3553. else
  3554. src_path = src;
  3555. /* find a next level down to target */
  3556. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  3557. if (ref->path[l] == '/') {
  3558. if (i == ref->nlvl_to - 1)
  3559. break;
  3560. else
  3561. i++;
  3562. }
  3563. /* compose filename if next level down to target was found */
  3564. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  3565. memcpy(filename, src, src_path - src);
  3566. filename[src_path - src] = 0;
  3567. for (i = 1; i < ref->nlvl_from; i++)
  3568. av_strlcat(filename, "../", sizeof(filename));
  3569. av_strlcat(filename, ref->path + l + 1, sizeof(filename));
  3570. if (!c->use_absolute_path) {
  3571. int same_origin = test_same_origin(src, filename);
  3572. if (!same_origin) {
  3573. av_log(c->fc, AV_LOG_ERROR,
  3574. "Reference with mismatching origin, %s not tried for security reasons, "
  3575. "set demuxer option use_absolute_path to allow it anyway\n",
  3576. ref->path);
  3577. return AVERROR(ENOENT);
  3578. }
  3579. if(strstr(ref->path + l + 1, "..") ||
  3580. strstr(ref->path + l + 1, ":") ||
  3581. (ref->nlvl_from > 1 && same_origin < 0) ||
  3582. (filename[0] == '/' && src_path == src))
  3583. return AVERROR(ENOENT);
  3584. }
  3585. if (strlen(filename) + 1 == sizeof(filename))
  3586. return AVERROR(ENOENT);
  3587. if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
  3588. return 0;
  3589. }
  3590. } else if (c->use_absolute_path) {
  3591. av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
  3592. "this is a possible security issue\n");
  3593. if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
  3594. return 0;
  3595. } else {
  3596. av_log(c->fc, AV_LOG_ERROR,
  3597. "Absolute path %s not tried for security reasons, "
  3598. "set demuxer option use_absolute_path to allow absolute paths\n",
  3599. ref->path);
  3600. }
  3601. return AVERROR(ENOENT);
  3602. }
  3603. static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
  3604. {
  3605. if (sc->time_scale <= 0) {
  3606. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
  3607. sc->time_scale = c->time_scale;
  3608. if (sc->time_scale <= 0)
  3609. sc->time_scale = 1;
  3610. }
  3611. }
  3612. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3613. {
  3614. AVStream *st;
  3615. MOVStreamContext *sc;
  3616. int ret;
  3617. st = avformat_new_stream(c->fc, NULL);
  3618. if (!st) return AVERROR(ENOMEM);
  3619. st->id = c->fc->nb_streams;
  3620. sc = av_mallocz(sizeof(MOVStreamContext));
  3621. if (!sc) return AVERROR(ENOMEM);
  3622. st->priv_data = sc;
  3623. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  3624. sc->ffindex = st->index;
  3625. c->trak_index = st->index;
  3626. if ((ret = mov_read_default(c, pb, atom)) < 0)
  3627. return ret;
  3628. c->trak_index = -1;
  3629. /* sanity checks */
  3630. if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  3631. (!sc->sample_size && !sc->sample_count))) ||
  3632. (!sc->chunk_count && sc->sample_count)) {
  3633. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  3634. st->index);
  3635. return 0;
  3636. }
  3637. if (sc->chunk_count && sc->stsc_count && sc->stsc_data[ sc->stsc_count - 1 ].first > sc->chunk_count) {
  3638. av_log(c->fc, AV_LOG_ERROR, "stream %d, contradictionary STSC and STCO\n",
  3639. st->index);
  3640. return AVERROR_INVALIDDATA;
  3641. }
  3642. fix_timescale(c, sc);
  3643. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  3644. mov_build_index(c, st);
  3645. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  3646. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  3647. if (c->enable_drefs) {
  3648. if (mov_open_dref(c, &sc->pb, c->fc->url, dref) < 0)
  3649. av_log(c->fc, AV_LOG_ERROR,
  3650. "stream %d, error opening alias: path='%s', dir='%s', "
  3651. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  3652. st->index, dref->path, dref->dir, dref->filename,
  3653. dref->volume, dref->nlvl_from, dref->nlvl_to);
  3654. } else {
  3655. av_log(c->fc, AV_LOG_WARNING,
  3656. "Skipped opening external track: "
  3657. "stream %d, alias: path='%s', dir='%s', "
  3658. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
  3659. "Set enable_drefs to allow this.\n",
  3660. st->index, dref->path, dref->dir, dref->filename,
  3661. dref->volume, dref->nlvl_from, dref->nlvl_to);
  3662. }
  3663. } else {
  3664. sc->pb = c->fc->pb;
  3665. sc->pb_is_copied = 1;
  3666. }
  3667. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  3668. if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
  3669. sc->height && sc->width &&
  3670. (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
  3671. st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
  3672. ((double)st->codecpar->width * sc->height), INT_MAX);
  3673. }
  3674. #if FF_API_R_FRAME_RATE
  3675. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  3676. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  3677. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  3678. #endif
  3679. }
  3680. // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  3681. if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
  3682. TAG_IS_AVCI(st->codecpar->codec_tag)) {
  3683. ret = ff_generate_avci_extradata(st);
  3684. if (ret < 0)
  3685. return ret;
  3686. }
  3687. switch (st->codecpar->codec_id) {
  3688. #if CONFIG_H261_DECODER
  3689. case AV_CODEC_ID_H261:
  3690. #endif
  3691. #if CONFIG_H263_DECODER
  3692. case AV_CODEC_ID_H263:
  3693. #endif
  3694. #if CONFIG_MPEG4_DECODER
  3695. case AV_CODEC_ID_MPEG4:
  3696. #endif
  3697. st->codecpar->width = 0; /* let decoder init width/height */
  3698. st->codecpar->height= 0;
  3699. break;
  3700. }
  3701. // If the duration of the mp3 packets is not constant, then they could need a parser
  3702. if (st->codecpar->codec_id == AV_CODEC_ID_MP3
  3703. && sc->stts_count > 3
  3704. && sc->stts_count*10 > st->nb_frames
  3705. && sc->time_scale == st->codecpar->sample_rate) {
  3706. st->need_parsing = AVSTREAM_PARSE_FULL;
  3707. }
  3708. /* Do not need those anymore. */
  3709. av_freep(&sc->chunk_offsets);
  3710. av_freep(&sc->sample_sizes);
  3711. av_freep(&sc->keyframes);
  3712. av_freep(&sc->stts_data);
  3713. av_freep(&sc->stps_data);
  3714. av_freep(&sc->elst_data);
  3715. av_freep(&sc->rap_group);
  3716. return 0;
  3717. }
  3718. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3719. {
  3720. int ret;
  3721. c->itunes_metadata = 1;
  3722. ret = mov_read_default(c, pb, atom);
  3723. c->itunes_metadata = 0;
  3724. return ret;
  3725. }
  3726. static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3727. {
  3728. uint32_t count;
  3729. uint32_t i;
  3730. if (atom.size < 8)
  3731. return 0;
  3732. avio_skip(pb, 4);
  3733. count = avio_rb32(pb);
  3734. if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
  3735. av_log(c->fc, AV_LOG_ERROR,
  3736. "The 'keys' atom with the invalid key count: %"PRIu32"\n", count);
  3737. return AVERROR_INVALIDDATA;
  3738. }
  3739. c->meta_keys_count = count + 1;
  3740. c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
  3741. if (!c->meta_keys)
  3742. return AVERROR(ENOMEM);
  3743. for (i = 1; i <= count; ++i) {
  3744. uint32_t key_size = avio_rb32(pb);
  3745. uint32_t type = avio_rl32(pb);
  3746. if (key_size < 8) {
  3747. av_log(c->fc, AV_LOG_ERROR,
  3748. "The key# %"PRIu32" in meta has invalid size:"
  3749. "%"PRIu32"\n", i, key_size);
  3750. return AVERROR_INVALIDDATA;
  3751. }
  3752. key_size -= 8;
  3753. if (type != MKTAG('m','d','t','a')) {
  3754. avio_skip(pb, key_size);
  3755. }
  3756. c->meta_keys[i] = av_mallocz(key_size + 1);
  3757. if (!c->meta_keys[i])
  3758. return AVERROR(ENOMEM);
  3759. avio_read(pb, c->meta_keys[i], key_size);
  3760. }
  3761. return 0;
  3762. }
  3763. static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3764. {
  3765. int64_t end = avio_tell(pb) + atom.size;
  3766. uint8_t *key = NULL, *val = NULL, *mean = NULL;
  3767. int i;
  3768. int ret = 0;
  3769. AVStream *st;
  3770. MOVStreamContext *sc;
  3771. if (c->fc->nb_streams < 1)
  3772. return 0;
  3773. st = c->fc->streams[c->fc->nb_streams-1];
  3774. sc = st->priv_data;
  3775. for (i = 0; i < 3; i++) {
  3776. uint8_t **p;
  3777. uint32_t len, tag;
  3778. if (end - avio_tell(pb) <= 12)
  3779. break;
  3780. len = avio_rb32(pb);
  3781. tag = avio_rl32(pb);
  3782. avio_skip(pb, 4); // flags
  3783. if (len < 12 || len - 12 > end - avio_tell(pb))
  3784. break;
  3785. len -= 12;
  3786. if (tag == MKTAG('m', 'e', 'a', 'n'))
  3787. p = &mean;
  3788. else if (tag == MKTAG('n', 'a', 'm', 'e'))
  3789. p = &key;
  3790. else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
  3791. avio_skip(pb, 4);
  3792. len -= 4;
  3793. p = &val;
  3794. } else
  3795. break;
  3796. *p = av_malloc(len + 1);
  3797. if (!*p) {
  3798. ret = AVERROR(ENOMEM);
  3799. break;
  3800. }
  3801. ret = ffio_read_size(pb, *p, len);
  3802. if (ret < 0) {
  3803. av_freep(p);
  3804. break;
  3805. }
  3806. (*p)[len] = 0;
  3807. }
  3808. if (mean && key && val) {
  3809. if (strcmp(key, "iTunSMPB") == 0) {
  3810. int priming, remainder, samples;
  3811. if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
  3812. if(priming>0 && priming<16384)
  3813. sc->start_pad = priming;
  3814. }
  3815. }
  3816. if (strcmp(key, "cdec") != 0) {
  3817. av_dict_set(&c->fc->metadata, key, val,
  3818. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  3819. key = val = NULL;
  3820. }
  3821. } else {
  3822. av_log(c->fc, AV_LOG_VERBOSE,
  3823. "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
  3824. }
  3825. avio_seek(pb, end, SEEK_SET);
  3826. av_freep(&key);
  3827. av_freep(&val);
  3828. av_freep(&mean);
  3829. return ret;
  3830. }
  3831. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3832. {
  3833. while (atom.size > 8) {
  3834. uint32_t tag = avio_rl32(pb);
  3835. atom.size -= 4;
  3836. if (tag == MKTAG('h','d','l','r')) {
  3837. avio_seek(pb, -8, SEEK_CUR);
  3838. atom.size += 8;
  3839. return mov_read_default(c, pb, atom);
  3840. }
  3841. }
  3842. return 0;
  3843. }
  3844. // return 1 when matrix is identity, 0 otherwise
  3845. #define IS_MATRIX_IDENT(matrix) \
  3846. ( (matrix)[0][0] == (1 << 16) && \
  3847. (matrix)[1][1] == (1 << 16) && \
  3848. (matrix)[2][2] == (1 << 30) && \
  3849. !(matrix)[0][1] && !(matrix)[0][2] && \
  3850. !(matrix)[1][0] && !(matrix)[1][2] && \
  3851. !(matrix)[2][0] && !(matrix)[2][1])
  3852. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3853. {
  3854. int i, j, e;
  3855. int width;
  3856. int height;
  3857. int display_matrix[3][3];
  3858. int res_display_matrix[3][3] = { { 0 } };
  3859. AVStream *st;
  3860. MOVStreamContext *sc;
  3861. int version;
  3862. int flags;
  3863. if (c->fc->nb_streams < 1)
  3864. return 0;
  3865. st = c->fc->streams[c->fc->nb_streams-1];
  3866. sc = st->priv_data;
  3867. version = avio_r8(pb);
  3868. flags = avio_rb24(pb);
  3869. st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  3870. if (version == 1) {
  3871. avio_rb64(pb);
  3872. avio_rb64(pb);
  3873. } else {
  3874. avio_rb32(pb); /* creation time */
  3875. avio_rb32(pb); /* modification time */
  3876. }
  3877. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  3878. avio_rb32(pb); /* reserved */
  3879. /* highlevel (considering edits) duration in movie timebase */
  3880. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  3881. avio_rb32(pb); /* reserved */
  3882. avio_rb32(pb); /* reserved */
  3883. avio_rb16(pb); /* layer */
  3884. avio_rb16(pb); /* alternate group */
  3885. avio_rb16(pb); /* volume */
  3886. avio_rb16(pb); /* reserved */
  3887. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  3888. // they're kept in fixed point format through all calculations
  3889. // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
  3890. // side data, but the scale factor is not needed to calculate aspect ratio
  3891. for (i = 0; i < 3; i++) {
  3892. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  3893. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  3894. display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  3895. }
  3896. width = avio_rb32(pb); // 16.16 fixed point track width
  3897. height = avio_rb32(pb); // 16.16 fixed point track height
  3898. sc->width = width >> 16;
  3899. sc->height = height >> 16;
  3900. // apply the moov display matrix (after the tkhd one)
  3901. for (i = 0; i < 3; i++) {
  3902. const int sh[3] = { 16, 16, 30 };
  3903. for (j = 0; j < 3; j++) {
  3904. for (e = 0; e < 3; e++) {
  3905. res_display_matrix[i][j] +=
  3906. ((int64_t) display_matrix[i][e] *
  3907. c->movie_display_matrix[e][j]) >> sh[e];
  3908. }
  3909. }
  3910. }
  3911. // save the matrix when it is not the default identity
  3912. if (!IS_MATRIX_IDENT(res_display_matrix)) {
  3913. double rotate;
  3914. av_freep(&sc->display_matrix);
  3915. sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
  3916. if (!sc->display_matrix)
  3917. return AVERROR(ENOMEM);
  3918. for (i = 0; i < 3; i++)
  3919. for (j = 0; j < 3; j++)
  3920. sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
  3921. #if FF_API_OLD_ROTATE_API
  3922. rotate = av_display_rotation_get(sc->display_matrix);
  3923. if (!isnan(rotate)) {
  3924. char rotate_buf[64];
  3925. rotate = -rotate;
  3926. if (rotate < 0) // for backward compatibility
  3927. rotate += 360;
  3928. snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
  3929. av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
  3930. }
  3931. #endif
  3932. }
  3933. // transform the display width/height according to the matrix
  3934. // to keep the same scale, use [width height 1<<16]
  3935. if (width && height && sc->display_matrix) {
  3936. double disp_transform[2];
  3937. for (i = 0; i < 2; i++)
  3938. disp_transform[i] = hypot(sc->display_matrix[0 + i],
  3939. sc->display_matrix[3 + i]);
  3940. if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
  3941. disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
  3942. fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
  3943. st->sample_aspect_ratio = av_d2q(
  3944. disp_transform[0] / disp_transform[1],
  3945. INT_MAX);
  3946. }
  3947. return 0;
  3948. }
  3949. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3950. {
  3951. MOVFragment *frag = &c->fragment;
  3952. MOVTrackExt *trex = NULL;
  3953. int flags, track_id, i;
  3954. avio_r8(pb); /* version */
  3955. flags = avio_rb24(pb);
  3956. track_id = avio_rb32(pb);
  3957. if (!track_id)
  3958. return AVERROR_INVALIDDATA;
  3959. frag->track_id = track_id;
  3960. set_frag_stream(&c->frag_index, track_id);
  3961. for (i = 0; i < c->trex_count; i++)
  3962. if (c->trex_data[i].track_id == frag->track_id) {
  3963. trex = &c->trex_data[i];
  3964. break;
  3965. }
  3966. if (!trex) {
  3967. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  3968. return AVERROR_INVALIDDATA;
  3969. }
  3970. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  3971. avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
  3972. frag->moof_offset : frag->implicit_offset;
  3973. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  3974. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  3975. avio_rb32(pb) : trex->duration;
  3976. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  3977. avio_rb32(pb) : trex->size;
  3978. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  3979. avio_rb32(pb) : trex->flags;
  3980. av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
  3981. return 0;
  3982. }
  3983. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3984. {
  3985. unsigned i, num;
  3986. void *new_tracks;
  3987. num = atom.size / 4;
  3988. if (!(new_tracks = av_malloc_array(num, sizeof(int))))
  3989. return AVERROR(ENOMEM);
  3990. av_free(c->chapter_tracks);
  3991. c->chapter_tracks = new_tracks;
  3992. c->nb_chapter_tracks = num;
  3993. for (i = 0; i < num && !pb->eof_reached; i++)
  3994. c->chapter_tracks[i] = avio_rb32(pb);
  3995. return 0;
  3996. }
  3997. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3998. {
  3999. MOVTrackExt *trex;
  4000. int err;
  4001. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  4002. return AVERROR_INVALIDDATA;
  4003. if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  4004. sizeof(*c->trex_data))) < 0) {
  4005. c->trex_count = 0;
  4006. return err;
  4007. }
  4008. c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
  4009. trex = &c->trex_data[c->trex_count++];
  4010. avio_r8(pb); /* version */
  4011. avio_rb24(pb); /* flags */
  4012. trex->track_id = avio_rb32(pb);
  4013. trex->stsd_id = avio_rb32(pb);
  4014. trex->duration = avio_rb32(pb);
  4015. trex->size = avio_rb32(pb);
  4016. trex->flags = avio_rb32(pb);
  4017. return 0;
  4018. }
  4019. static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4020. {
  4021. MOVFragment *frag = &c->fragment;
  4022. AVStream *st = NULL;
  4023. MOVStreamContext *sc;
  4024. int version, i;
  4025. MOVFragmentStreamInfo * frag_stream_info;
  4026. int64_t base_media_decode_time;
  4027. for (i = 0; i < c->fc->nb_streams; i++) {
  4028. if (c->fc->streams[i]->id == frag->track_id) {
  4029. st = c->fc->streams[i];
  4030. break;
  4031. }
  4032. }
  4033. if (!st) {
  4034. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
  4035. return AVERROR_INVALIDDATA;
  4036. }
  4037. sc = st->priv_data;
  4038. if (sc->pseudo_stream_id + 1 != frag->stsd_id && sc->pseudo_stream_id != -1)
  4039. return 0;
  4040. version = avio_r8(pb);
  4041. avio_rb24(pb); /* flags */
  4042. if (version) {
  4043. base_media_decode_time = avio_rb64(pb);
  4044. } else {
  4045. base_media_decode_time = avio_rb32(pb);
  4046. }
  4047. frag_stream_info = get_current_frag_stream_info(&c->frag_index);
  4048. if (frag_stream_info)
  4049. frag_stream_info->tfdt_dts = base_media_decode_time;
  4050. sc->track_end = base_media_decode_time;
  4051. return 0;
  4052. }
  4053. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4054. {
  4055. MOVFragment *frag = &c->fragment;
  4056. AVStream *st = NULL;
  4057. MOVStreamContext *sc;
  4058. MOVStts *ctts_data;
  4059. uint64_t offset;
  4060. int64_t dts, pts = AV_NOPTS_VALUE;
  4061. int data_offset = 0;
  4062. unsigned entries, first_sample_flags = frag->flags;
  4063. int flags, distance, i;
  4064. int64_t prev_dts = AV_NOPTS_VALUE;
  4065. int next_frag_index = -1, index_entry_pos;
  4066. size_t requested_size;
  4067. size_t old_ctts_allocated_size;
  4068. AVIndexEntry *new_entries;
  4069. MOVFragmentStreamInfo * frag_stream_info;
  4070. for (i = 0; i < c->fc->nb_streams; i++) {
  4071. if (c->fc->streams[i]->id == frag->track_id) {
  4072. st = c->fc->streams[i];
  4073. break;
  4074. }
  4075. }
  4076. if (!st) {
  4077. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
  4078. return AVERROR_INVALIDDATA;
  4079. }
  4080. sc = st->priv_data;
  4081. if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
  4082. return 0;
  4083. // Find the next frag_index index that has a valid index_entry for
  4084. // the current track_id.
  4085. //
  4086. // A valid index_entry means the trun for the fragment was read
  4087. // and it's samples are in index_entries at the given position.
  4088. // New index entries will be inserted before the index_entry found.
  4089. index_entry_pos = st->nb_index_entries;
  4090. for (i = c->frag_index.current + 1; i < c->frag_index.nb_items; i++) {
  4091. frag_stream_info = get_frag_stream_info(&c->frag_index, i, frag->track_id);
  4092. if (frag_stream_info && frag_stream_info->index_entry >= 0) {
  4093. next_frag_index = i;
  4094. index_entry_pos = frag_stream_info->index_entry;
  4095. break;
  4096. }
  4097. }
  4098. avio_r8(pb); /* version */
  4099. flags = avio_rb24(pb);
  4100. entries = avio_rb32(pb);
  4101. av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
  4102. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  4103. return AVERROR_INVALIDDATA;
  4104. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  4105. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  4106. frag_stream_info = get_current_frag_stream_info(&c->frag_index);
  4107. if (frag_stream_info)
  4108. {
  4109. if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE &&
  4110. c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
  4111. pts = frag_stream_info->first_tfra_pts;
  4112. av_log(c->fc, AV_LOG_DEBUG, "found mfra time %"PRId64
  4113. ", using it for pts\n", pts);
  4114. } else if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE) {
  4115. // FIXME: sidx earliest_presentation_time is *PTS*, s.b.
  4116. // pts = frag_stream_info->sidx_pts;
  4117. dts = frag_stream_info->sidx_pts - sc->time_offset;
  4118. av_log(c->fc, AV_LOG_DEBUG, "found sidx time %"PRId64
  4119. ", using it for pts\n", pts);
  4120. } else if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE) {
  4121. dts = frag_stream_info->tfdt_dts - sc->time_offset;
  4122. av_log(c->fc, AV_LOG_DEBUG, "found tfdt time %"PRId64
  4123. ", using it for dts\n", dts);
  4124. } else {
  4125. dts = sc->track_end - sc->time_offset;
  4126. av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
  4127. ", using it for dts\n", dts);
  4128. }
  4129. } else {
  4130. dts = sc->track_end - sc->time_offset;
  4131. av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
  4132. ", using it for dts\n", dts);
  4133. }
  4134. offset = frag->base_data_offset + data_offset;
  4135. distance = 0;
  4136. av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
  4137. // realloc space for new index entries
  4138. if((unsigned)st->nb_index_entries + entries >= UINT_MAX / sizeof(AVIndexEntry)) {
  4139. entries = UINT_MAX / sizeof(AVIndexEntry) - st->nb_index_entries;
  4140. av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
  4141. }
  4142. if (entries <= 0)
  4143. return -1;
  4144. requested_size = (st->nb_index_entries + entries) * sizeof(AVIndexEntry);
  4145. new_entries = av_fast_realloc(st->index_entries,
  4146. &st->index_entries_allocated_size,
  4147. requested_size);
  4148. if(!new_entries)
  4149. return AVERROR(ENOMEM);
  4150. st->index_entries= new_entries;
  4151. requested_size = (st->nb_index_entries + entries) * sizeof(*sc->ctts_data);
  4152. old_ctts_allocated_size = sc->ctts_allocated_size;
  4153. ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size,
  4154. requested_size);
  4155. if (!ctts_data)
  4156. return AVERROR(ENOMEM);
  4157. sc->ctts_data = ctts_data;
  4158. // In case there were samples without ctts entries, ensure they get
  4159. // zero valued entries. This ensures clips which mix boxes with and
  4160. // without ctts entries don't pickup uninitialized data.
  4161. memset((uint8_t*)(sc->ctts_data) + old_ctts_allocated_size, 0,
  4162. sc->ctts_allocated_size - old_ctts_allocated_size);
  4163. if (index_entry_pos < st->nb_index_entries) {
  4164. // Make hole in index_entries and ctts_data for new samples
  4165. memmove(st->index_entries + index_entry_pos + entries,
  4166. st->index_entries + index_entry_pos,
  4167. sizeof(*st->index_entries) *
  4168. (st->nb_index_entries - index_entry_pos));
  4169. memmove(sc->ctts_data + index_entry_pos + entries,
  4170. sc->ctts_data + index_entry_pos,
  4171. sizeof(*sc->ctts_data) * (sc->ctts_count - index_entry_pos));
  4172. if (index_entry_pos < sc->current_sample) {
  4173. sc->current_sample += entries;
  4174. }
  4175. }
  4176. st->nb_index_entries += entries;
  4177. sc->ctts_count = st->nb_index_entries;
  4178. // Record the index_entry position in frag_index of this fragment
  4179. if (frag_stream_info)
  4180. frag_stream_info->index_entry = index_entry_pos;
  4181. if (index_entry_pos > 0)
  4182. prev_dts = st->index_entries[index_entry_pos-1].timestamp;
  4183. for (i = 0; i < entries && !pb->eof_reached; i++) {
  4184. unsigned sample_size = frag->size;
  4185. int sample_flags = i ? frag->flags : first_sample_flags;
  4186. unsigned sample_duration = frag->duration;
  4187. unsigned ctts_duration = 0;
  4188. int keyframe = 0;
  4189. int index_entry_flags = 0;
  4190. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  4191. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  4192. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  4193. if (flags & MOV_TRUN_SAMPLE_CTS) ctts_duration = avio_rb32(pb);
  4194. mov_update_dts_shift(sc, ctts_duration);
  4195. if (pts != AV_NOPTS_VALUE) {
  4196. dts = pts - sc->dts_shift;
  4197. if (flags & MOV_TRUN_SAMPLE_CTS) {
  4198. dts -= ctts_duration;
  4199. } else {
  4200. dts -= sc->time_offset;
  4201. }
  4202. av_log(c->fc, AV_LOG_DEBUG,
  4203. "pts %"PRId64" calculated dts %"PRId64
  4204. " sc->dts_shift %d ctts.duration %d"
  4205. " sc->time_offset %"PRId64
  4206. " flags & MOV_TRUN_SAMPLE_CTS %d\n",
  4207. pts, dts,
  4208. sc->dts_shift, ctts_duration,
  4209. sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
  4210. pts = AV_NOPTS_VALUE;
  4211. }
  4212. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  4213. keyframe = 1;
  4214. else
  4215. keyframe =
  4216. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  4217. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  4218. if (keyframe) {
  4219. distance = 0;
  4220. index_entry_flags |= AVINDEX_KEYFRAME;
  4221. }
  4222. // Fragments can overlap in time. Discard overlapping frames after
  4223. // decoding.
  4224. if (prev_dts >= dts)
  4225. index_entry_flags |= AVINDEX_DISCARD_FRAME;
  4226. st->index_entries[index_entry_pos].pos = offset;
  4227. st->index_entries[index_entry_pos].timestamp = dts;
  4228. st->index_entries[index_entry_pos].size= sample_size;
  4229. st->index_entries[index_entry_pos].min_distance= distance;
  4230. st->index_entries[index_entry_pos].flags = index_entry_flags;
  4231. sc->ctts_data[index_entry_pos].count = 1;
  4232. sc->ctts_data[index_entry_pos].duration = ctts_duration;
  4233. index_entry_pos++;
  4234. av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  4235. "size %u, distance %d, keyframe %d\n", st->index,
  4236. index_entry_pos, offset, dts, sample_size, distance, keyframe);
  4237. distance++;
  4238. dts += sample_duration;
  4239. offset += sample_size;
  4240. sc->data_size += sample_size;
  4241. if (sample_duration <= INT64_MAX - sc->duration_for_fps &&
  4242. 1 <= INT64_MAX - sc->nb_frames_for_fps
  4243. ) {
  4244. sc->duration_for_fps += sample_duration;
  4245. sc->nb_frames_for_fps ++;
  4246. }
  4247. }
  4248. if (i < entries) {
  4249. // EOF found before reading all entries. Fix the hole this would
  4250. // leave in index_entries and ctts_data
  4251. int gap = entries - i;
  4252. memmove(st->index_entries + index_entry_pos,
  4253. st->index_entries + index_entry_pos + gap,
  4254. sizeof(*st->index_entries) *
  4255. (st->nb_index_entries - (index_entry_pos + gap)));
  4256. memmove(sc->ctts_data + index_entry_pos,
  4257. sc->ctts_data + index_entry_pos + gap,
  4258. sizeof(*sc->ctts_data) *
  4259. (sc->ctts_count - (index_entry_pos + gap)));
  4260. st->nb_index_entries -= gap;
  4261. sc->ctts_count -= gap;
  4262. if (index_entry_pos < sc->current_sample) {
  4263. sc->current_sample -= gap;
  4264. }
  4265. entries = i;
  4266. }
  4267. // The end of this new fragment may overlap in time with the start
  4268. // of the next fragment in index_entries. Mark the samples in the next
  4269. // fragment that overlap with AVINDEX_DISCARD_FRAME
  4270. prev_dts = AV_NOPTS_VALUE;
  4271. if (index_entry_pos > 0)
  4272. prev_dts = st->index_entries[index_entry_pos-1].timestamp;
  4273. for (i = index_entry_pos; i < st->nb_index_entries; i++) {
  4274. if (prev_dts < st->index_entries[i].timestamp)
  4275. break;
  4276. st->index_entries[i].flags |= AVINDEX_DISCARD_FRAME;
  4277. }
  4278. // If a hole was created to insert the new index_entries into,
  4279. // the index_entry recorded for all subsequent moof must
  4280. // be incremented by the number of entries inserted.
  4281. fix_frag_index_entries(&c->frag_index, next_frag_index,
  4282. frag->track_id, entries);
  4283. if (pb->eof_reached) {
  4284. av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted TRUN atom\n");
  4285. return AVERROR_EOF;
  4286. }
  4287. frag->implicit_offset = offset;
  4288. sc->track_end = dts + sc->time_offset;
  4289. if (st->duration < sc->track_end)
  4290. st->duration = sc->track_end;
  4291. return 0;
  4292. }
  4293. static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4294. {
  4295. int64_t offset = avio_tell(pb) + atom.size, pts, timestamp;
  4296. uint8_t version;
  4297. unsigned i, j, track_id, item_count;
  4298. AVStream *st = NULL;
  4299. AVStream *ref_st = NULL;
  4300. MOVStreamContext *sc, *ref_sc = NULL;
  4301. AVRational timescale;
  4302. version = avio_r8(pb);
  4303. if (version > 1) {
  4304. avpriv_request_sample(c->fc, "sidx version %u", version);
  4305. return 0;
  4306. }
  4307. avio_rb24(pb); // flags
  4308. track_id = avio_rb32(pb); // Reference ID
  4309. for (i = 0; i < c->fc->nb_streams; i++) {
  4310. if (c->fc->streams[i]->id == track_id) {
  4311. st = c->fc->streams[i];
  4312. break;
  4313. }
  4314. }
  4315. if (!st) {
  4316. av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
  4317. return 0;
  4318. }
  4319. sc = st->priv_data;
  4320. timescale = av_make_q(1, avio_rb32(pb));
  4321. if (timescale.den <= 0) {
  4322. av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
  4323. return AVERROR_INVALIDDATA;
  4324. }
  4325. if (version == 0) {
  4326. pts = avio_rb32(pb);
  4327. offset += avio_rb32(pb);
  4328. } else {
  4329. pts = avio_rb64(pb);
  4330. offset += avio_rb64(pb);
  4331. }
  4332. avio_rb16(pb); // reserved
  4333. item_count = avio_rb16(pb);
  4334. for (i = 0; i < item_count; i++) {
  4335. int index;
  4336. MOVFragmentStreamInfo * frag_stream_info;
  4337. uint32_t size = avio_rb32(pb);
  4338. uint32_t duration = avio_rb32(pb);
  4339. if (size & 0x80000000) {
  4340. avpriv_request_sample(c->fc, "sidx reference_type 1");
  4341. return AVERROR_PATCHWELCOME;
  4342. }
  4343. avio_rb32(pb); // sap_flags
  4344. timestamp = av_rescale_q(pts, st->time_base, timescale);
  4345. index = update_frag_index(c, offset);
  4346. frag_stream_info = get_frag_stream_info(&c->frag_index, index, track_id);
  4347. if (frag_stream_info)
  4348. frag_stream_info->sidx_pts = timestamp;
  4349. offset += size;
  4350. pts += duration;
  4351. }
  4352. st->duration = sc->track_end = pts;
  4353. sc->has_sidx = 1;
  4354. if (offset == avio_size(pb)) {
  4355. // Find first entry in fragment index that came from an sidx.
  4356. // This will pretty much always be the first entry.
  4357. for (i = 0; i < c->frag_index.nb_items; i++) {
  4358. MOVFragmentIndexItem * item = &c->frag_index.item[i];
  4359. for (j = 0; ref_st == NULL && j < item->nb_stream_info; j++) {
  4360. MOVFragmentStreamInfo * si;
  4361. si = &item->stream_info[j];
  4362. if (si->sidx_pts != AV_NOPTS_VALUE) {
  4363. ref_st = c->fc->streams[j];
  4364. ref_sc = ref_st->priv_data;
  4365. break;
  4366. }
  4367. }
  4368. }
  4369. for (i = 0; i < c->fc->nb_streams; i++) {
  4370. st = c->fc->streams[i];
  4371. sc = st->priv_data;
  4372. if (!sc->has_sidx) {
  4373. st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
  4374. }
  4375. }
  4376. c->frag_index.complete = 1;
  4377. }
  4378. return 0;
  4379. }
  4380. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  4381. /* like the files created with Adobe Premiere 5.0, for samples see */
  4382. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  4383. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4384. {
  4385. int err;
  4386. if (atom.size < 8)
  4387. return 0; /* continue */
  4388. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  4389. avio_skip(pb, atom.size - 4);
  4390. return 0;
  4391. }
  4392. atom.type = avio_rl32(pb);
  4393. atom.size -= 8;
  4394. if (atom.type != MKTAG('m','d','a','t')) {
  4395. avio_skip(pb, atom.size);
  4396. return 0;
  4397. }
  4398. err = mov_read_mdat(c, pb, atom);
  4399. return err;
  4400. }
  4401. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4402. {
  4403. #if CONFIG_ZLIB
  4404. AVIOContext ctx;
  4405. uint8_t *cmov_data;
  4406. uint8_t *moov_data; /* uncompressed data */
  4407. long cmov_len, moov_len;
  4408. int ret = -1;
  4409. avio_rb32(pb); /* dcom atom */
  4410. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  4411. return AVERROR_INVALIDDATA;
  4412. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  4413. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
  4414. return AVERROR_INVALIDDATA;
  4415. }
  4416. avio_rb32(pb); /* cmvd atom */
  4417. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  4418. return AVERROR_INVALIDDATA;
  4419. moov_len = avio_rb32(pb); /* uncompressed size */
  4420. cmov_len = atom.size - 6 * 4;
  4421. cmov_data = av_malloc(cmov_len);
  4422. if (!cmov_data)
  4423. return AVERROR(ENOMEM);
  4424. moov_data = av_malloc(moov_len);
  4425. if (!moov_data) {
  4426. av_free(cmov_data);
  4427. return AVERROR(ENOMEM);
  4428. }
  4429. ret = ffio_read_size(pb, cmov_data, cmov_len);
  4430. if (ret < 0)
  4431. goto free_and_return;
  4432. ret = AVERROR_INVALIDDATA;
  4433. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  4434. goto free_and_return;
  4435. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  4436. goto free_and_return;
  4437. ctx.seekable = AVIO_SEEKABLE_NORMAL;
  4438. atom.type = MKTAG('m','o','o','v');
  4439. atom.size = moov_len;
  4440. ret = mov_read_default(c, &ctx, atom);
  4441. free_and_return:
  4442. av_free(moov_data);
  4443. av_free(cmov_data);
  4444. return ret;
  4445. #else
  4446. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  4447. return AVERROR(ENOSYS);
  4448. #endif
  4449. }
  4450. /* edit list atom */
  4451. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4452. {
  4453. MOVStreamContext *sc;
  4454. int i, edit_count, version;
  4455. int64_t elst_entry_size;
  4456. if (c->fc->nb_streams < 1 || c->ignore_editlist)
  4457. return 0;
  4458. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  4459. version = avio_r8(pb); /* version */
  4460. avio_rb24(pb); /* flags */
  4461. edit_count = avio_rb32(pb); /* entries */
  4462. atom.size -= 8;
  4463. elst_entry_size = version == 1 ? 20 : 12;
  4464. if (atom.size != edit_count * elst_entry_size) {
  4465. if (c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  4466. av_log(c->fc, AV_LOG_ERROR, "Invalid edit list entry_count: %d for elst atom of size: %"PRId64" bytes.\n",
  4467. edit_count, atom.size + 8);
  4468. return AVERROR_INVALIDDATA;
  4469. } else {
  4470. edit_count = atom.size / elst_entry_size;
  4471. if (edit_count * elst_entry_size != atom.size) {
  4472. av_log(c->fc, AV_LOG_WARNING, "ELST atom of %"PRId64" bytes, bigger than %d entries.", atom.size, edit_count);
  4473. }
  4474. }
  4475. }
  4476. if (!edit_count)
  4477. return 0;
  4478. if (sc->elst_data)
  4479. av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
  4480. av_free(sc->elst_data);
  4481. sc->elst_count = 0;
  4482. sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
  4483. if (!sc->elst_data)
  4484. return AVERROR(ENOMEM);
  4485. av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
  4486. for (i = 0; i < edit_count && atom.size > 0 && !pb->eof_reached; i++) {
  4487. MOVElst *e = &sc->elst_data[i];
  4488. if (version == 1) {
  4489. e->duration = avio_rb64(pb);
  4490. e->time = avio_rb64(pb);
  4491. atom.size -= 16;
  4492. } else {
  4493. e->duration = avio_rb32(pb); /* segment duration */
  4494. e->time = (int32_t)avio_rb32(pb); /* media time */
  4495. atom.size -= 8;
  4496. }
  4497. e->rate = avio_rb32(pb) / 65536.0;
  4498. atom.size -= 4;
  4499. av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
  4500. e->duration, e->time, e->rate);
  4501. if (e->time < 0 && e->time != -1 &&
  4502. c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  4503. av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
  4504. c->fc->nb_streams-1, i, e->time);
  4505. return AVERROR_INVALIDDATA;
  4506. }
  4507. }
  4508. sc->elst_count = i;
  4509. return 0;
  4510. }
  4511. static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4512. {
  4513. MOVStreamContext *sc;
  4514. if (c->fc->nb_streams < 1)
  4515. return AVERROR_INVALIDDATA;
  4516. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  4517. sc->timecode_track = avio_rb32(pb);
  4518. return 0;
  4519. }
  4520. static int mov_read_av1c(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4521. {
  4522. AVStream *st;
  4523. int ret, version;
  4524. if (c->fc->nb_streams < 1)
  4525. return 0;
  4526. st = c->fc->streams[c->fc->nb_streams - 1];
  4527. if (atom.size < 5) {
  4528. av_log(c->fc, AV_LOG_ERROR, "Empty AV1 Codec Configuration Box\n");
  4529. return AVERROR_INVALIDDATA;
  4530. }
  4531. version = avio_r8(pb);
  4532. if (version != 0) {
  4533. av_log(c->fc, AV_LOG_WARNING, "Unknown AV1 Codec Configuration Box version %d\n", version);
  4534. return 0;
  4535. }
  4536. avio_skip(pb, 3); /* flags */
  4537. avio_skip(pb, 1); /* reserved, initial_presentation_delay_present, initial_presentation_delay_minus_one */
  4538. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 5);
  4539. if (ret < 0)
  4540. return ret;
  4541. return 0;
  4542. }
  4543. static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4544. {
  4545. AVStream *st;
  4546. int version, color_range, color_primaries, color_trc, color_space;
  4547. if (c->fc->nb_streams < 1)
  4548. return 0;
  4549. st = c->fc->streams[c->fc->nb_streams - 1];
  4550. if (atom.size < 5) {
  4551. av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n");
  4552. return AVERROR_INVALIDDATA;
  4553. }
  4554. version = avio_r8(pb);
  4555. if (version != 1) {
  4556. av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version);
  4557. return 0;
  4558. }
  4559. avio_skip(pb, 3); /* flags */
  4560. avio_skip(pb, 2); /* profile + level */
  4561. color_range = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */
  4562. color_primaries = avio_r8(pb);
  4563. color_trc = avio_r8(pb);
  4564. color_space = avio_r8(pb);
  4565. if (avio_rb16(pb)) /* codecIntializationDataSize */
  4566. return AVERROR_INVALIDDATA;
  4567. if (!av_color_primaries_name(color_primaries))
  4568. color_primaries = AVCOL_PRI_UNSPECIFIED;
  4569. if (!av_color_transfer_name(color_trc))
  4570. color_trc = AVCOL_TRC_UNSPECIFIED;
  4571. if (!av_color_space_name(color_space))
  4572. color_space = AVCOL_SPC_UNSPECIFIED;
  4573. st->codecpar->color_range = (color_range & 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
  4574. st->codecpar->color_primaries = color_primaries;
  4575. st->codecpar->color_trc = color_trc;
  4576. st->codecpar->color_space = color_space;
  4577. return 0;
  4578. }
  4579. static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4580. {
  4581. MOVStreamContext *sc;
  4582. const int chroma_den = 50000;
  4583. const int luma_den = 10000;
  4584. int i, j, version;
  4585. if (c->fc->nb_streams < 1)
  4586. return AVERROR_INVALIDDATA;
  4587. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  4588. if (atom.size < 5) {
  4589. av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n");
  4590. return AVERROR_INVALIDDATA;
  4591. }
  4592. version = avio_r8(pb);
  4593. if (version) {
  4594. av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version);
  4595. return 0;
  4596. }
  4597. avio_skip(pb, 3); /* flags */
  4598. sc->mastering = av_mastering_display_metadata_alloc();
  4599. if (!sc->mastering)
  4600. return AVERROR(ENOMEM);
  4601. for (i = 0; i < 3; i++)
  4602. for (j = 0; j < 2; j++)
  4603. sc->mastering->display_primaries[i][j] =
  4604. av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
  4605. for (i = 0; i < 2; i++)
  4606. sc->mastering->white_point[i] =
  4607. av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
  4608. sc->mastering->max_luminance =
  4609. av_make_q(lrint(((double)avio_rb32(pb) / (1 << 8)) * luma_den), luma_den);
  4610. sc->mastering->min_luminance =
  4611. av_make_q(lrint(((double)avio_rb32(pb) / (1 << 14)) * luma_den), luma_den);
  4612. sc->mastering->has_primaries = 1;
  4613. sc->mastering->has_luminance = 1;
  4614. return 0;
  4615. }
  4616. static int mov_read_mdcv(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4617. {
  4618. MOVStreamContext *sc;
  4619. const int mapping[3] = {1, 2, 0};
  4620. const int chroma_den = 50000;
  4621. const int luma_den = 10000;
  4622. int i;
  4623. if (c->fc->nb_streams < 1)
  4624. return AVERROR_INVALIDDATA;
  4625. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  4626. if (atom.size < 24) {
  4627. av_log(c->fc, AV_LOG_ERROR, "Invalid Mastering Display Color Volume box\n");
  4628. return AVERROR_INVALIDDATA;
  4629. }
  4630. sc->mastering = av_mastering_display_metadata_alloc();
  4631. if (!sc->mastering)
  4632. return AVERROR(ENOMEM);
  4633. for (i = 0; i < 3; i++) {
  4634. const int j = mapping[i];
  4635. sc->mastering->display_primaries[j][0] = av_make_q(avio_rb16(pb), chroma_den);
  4636. sc->mastering->display_primaries[j][1] = av_make_q(avio_rb16(pb), chroma_den);
  4637. }
  4638. sc->mastering->white_point[0] = av_make_q(avio_rb16(pb), chroma_den);
  4639. sc->mastering->white_point[1] = av_make_q(avio_rb16(pb), chroma_den);
  4640. sc->mastering->max_luminance = av_make_q(avio_rb32(pb), luma_den);
  4641. sc->mastering->min_luminance = av_make_q(avio_rb32(pb), luma_den);
  4642. sc->mastering->has_luminance = 1;
  4643. sc->mastering->has_primaries = 1;
  4644. return 0;
  4645. }
  4646. static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4647. {
  4648. MOVStreamContext *sc;
  4649. int version;
  4650. if (c->fc->nb_streams < 1)
  4651. return AVERROR_INVALIDDATA;
  4652. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  4653. if (atom.size < 5) {
  4654. av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n");
  4655. return AVERROR_INVALIDDATA;
  4656. }
  4657. version = avio_r8(pb);
  4658. if (version) {
  4659. av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version);
  4660. return 0;
  4661. }
  4662. avio_skip(pb, 3); /* flags */
  4663. sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
  4664. if (!sc->coll)
  4665. return AVERROR(ENOMEM);
  4666. sc->coll->MaxCLL = avio_rb16(pb);
  4667. sc->coll->MaxFALL = avio_rb16(pb);
  4668. return 0;
  4669. }
  4670. static int mov_read_clli(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4671. {
  4672. MOVStreamContext *sc;
  4673. if (c->fc->nb_streams < 1)
  4674. return AVERROR_INVALIDDATA;
  4675. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  4676. if (atom.size < 4) {
  4677. av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level Info box\n");
  4678. return AVERROR_INVALIDDATA;
  4679. }
  4680. sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
  4681. if (!sc->coll)
  4682. return AVERROR(ENOMEM);
  4683. sc->coll->MaxCLL = avio_rb16(pb);
  4684. sc->coll->MaxFALL = avio_rb16(pb);
  4685. return 0;
  4686. }
  4687. static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4688. {
  4689. AVStream *st;
  4690. MOVStreamContext *sc;
  4691. enum AVStereo3DType type;
  4692. int mode;
  4693. if (c->fc->nb_streams < 1)
  4694. return 0;
  4695. st = c->fc->streams[c->fc->nb_streams - 1];
  4696. sc = st->priv_data;
  4697. if (atom.size < 5) {
  4698. av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
  4699. return AVERROR_INVALIDDATA;
  4700. }
  4701. avio_skip(pb, 4); /* version + flags */
  4702. mode = avio_r8(pb);
  4703. switch (mode) {
  4704. case 0:
  4705. type = AV_STEREO3D_2D;
  4706. break;
  4707. case 1:
  4708. type = AV_STEREO3D_TOPBOTTOM;
  4709. break;
  4710. case 2:
  4711. type = AV_STEREO3D_SIDEBYSIDE;
  4712. break;
  4713. default:
  4714. av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
  4715. return 0;
  4716. }
  4717. sc->stereo3d = av_stereo3d_alloc();
  4718. if (!sc->stereo3d)
  4719. return AVERROR(ENOMEM);
  4720. sc->stereo3d->type = type;
  4721. return 0;
  4722. }
  4723. static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4724. {
  4725. AVStream *st;
  4726. MOVStreamContext *sc;
  4727. int size, version, layout;
  4728. int32_t yaw, pitch, roll;
  4729. uint32_t l = 0, t = 0, r = 0, b = 0;
  4730. uint32_t tag, padding = 0;
  4731. enum AVSphericalProjection projection;
  4732. if (c->fc->nb_streams < 1)
  4733. return 0;
  4734. st = c->fc->streams[c->fc->nb_streams - 1];
  4735. sc = st->priv_data;
  4736. if (atom.size < 8) {
  4737. av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
  4738. return AVERROR_INVALIDDATA;
  4739. }
  4740. size = avio_rb32(pb);
  4741. if (size <= 12 || size > atom.size)
  4742. return AVERROR_INVALIDDATA;
  4743. tag = avio_rl32(pb);
  4744. if (tag != MKTAG('s','v','h','d')) {
  4745. av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
  4746. return 0;
  4747. }
  4748. version = avio_r8(pb);
  4749. if (version != 0) {
  4750. av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
  4751. version);
  4752. return 0;
  4753. }
  4754. avio_skip(pb, 3); /* flags */
  4755. avio_skip(pb, size - 12); /* metadata_source */
  4756. size = avio_rb32(pb);
  4757. if (size > atom.size)
  4758. return AVERROR_INVALIDDATA;
  4759. tag = avio_rl32(pb);
  4760. if (tag != MKTAG('p','r','o','j')) {
  4761. av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
  4762. return 0;
  4763. }
  4764. size = avio_rb32(pb);
  4765. if (size > atom.size)
  4766. return AVERROR_INVALIDDATA;
  4767. tag = avio_rl32(pb);
  4768. if (tag != MKTAG('p','r','h','d')) {
  4769. av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
  4770. return 0;
  4771. }
  4772. version = avio_r8(pb);
  4773. if (version != 0) {
  4774. av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
  4775. version);
  4776. return 0;
  4777. }
  4778. avio_skip(pb, 3); /* flags */
  4779. /* 16.16 fixed point */
  4780. yaw = avio_rb32(pb);
  4781. pitch = avio_rb32(pb);
  4782. roll = avio_rb32(pb);
  4783. size = avio_rb32(pb);
  4784. if (size > atom.size)
  4785. return AVERROR_INVALIDDATA;
  4786. tag = avio_rl32(pb);
  4787. version = avio_r8(pb);
  4788. if (version != 0) {
  4789. av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
  4790. version);
  4791. return 0;
  4792. }
  4793. avio_skip(pb, 3); /* flags */
  4794. switch (tag) {
  4795. case MKTAG('c','b','m','p'):
  4796. layout = avio_rb32(pb);
  4797. if (layout) {
  4798. av_log(c->fc, AV_LOG_WARNING,
  4799. "Unsupported cubemap layout %d\n", layout);
  4800. return 0;
  4801. }
  4802. projection = AV_SPHERICAL_CUBEMAP;
  4803. padding = avio_rb32(pb);
  4804. break;
  4805. case MKTAG('e','q','u','i'):
  4806. t = avio_rb32(pb);
  4807. b = avio_rb32(pb);
  4808. l = avio_rb32(pb);
  4809. r = avio_rb32(pb);
  4810. if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
  4811. av_log(c->fc, AV_LOG_ERROR,
  4812. "Invalid bounding rectangle coordinates "
  4813. "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
  4814. return AVERROR_INVALIDDATA;
  4815. }
  4816. if (l || t || r || b)
  4817. projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
  4818. else
  4819. projection = AV_SPHERICAL_EQUIRECTANGULAR;
  4820. break;
  4821. default:
  4822. av_log(c->fc, AV_LOG_ERROR, "Unknown projection type: %s\n", av_fourcc2str(tag));
  4823. return 0;
  4824. }
  4825. sc->spherical = av_spherical_alloc(&sc->spherical_size);
  4826. if (!sc->spherical)
  4827. return AVERROR(ENOMEM);
  4828. sc->spherical->projection = projection;
  4829. sc->spherical->yaw = yaw;
  4830. sc->spherical->pitch = pitch;
  4831. sc->spherical->roll = roll;
  4832. sc->spherical->padding = padding;
  4833. sc->spherical->bound_left = l;
  4834. sc->spherical->bound_top = t;
  4835. sc->spherical->bound_right = r;
  4836. sc->spherical->bound_bottom = b;
  4837. return 0;
  4838. }
  4839. static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
  4840. {
  4841. int ret = 0;
  4842. uint8_t *buffer = av_malloc(len + 1);
  4843. const char *val;
  4844. if (!buffer)
  4845. return AVERROR(ENOMEM);
  4846. buffer[len] = '\0';
  4847. ret = ffio_read_size(pb, buffer, len);
  4848. if (ret < 0)
  4849. goto out;
  4850. /* Check for mandatory keys and values, try to support XML as best-effort */
  4851. if (!sc->spherical &&
  4852. av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
  4853. (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
  4854. av_stristr(val, "true") &&
  4855. (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
  4856. av_stristr(val, "true") &&
  4857. (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
  4858. av_stristr(val, "equirectangular")) {
  4859. sc->spherical = av_spherical_alloc(&sc->spherical_size);
  4860. if (!sc->spherical)
  4861. goto out;
  4862. sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR;
  4863. if (av_stristr(buffer, "<GSpherical:StereoMode>") && !sc->stereo3d) {
  4864. enum AVStereo3DType mode;
  4865. if (av_stristr(buffer, "left-right"))
  4866. mode = AV_STEREO3D_SIDEBYSIDE;
  4867. else if (av_stristr(buffer, "top-bottom"))
  4868. mode = AV_STEREO3D_TOPBOTTOM;
  4869. else
  4870. mode = AV_STEREO3D_2D;
  4871. sc->stereo3d = av_stereo3d_alloc();
  4872. if (!sc->stereo3d)
  4873. goto out;
  4874. sc->stereo3d->type = mode;
  4875. }
  4876. /* orientation */
  4877. val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
  4878. if (val)
  4879. sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
  4880. val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
  4881. if (val)
  4882. sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
  4883. val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
  4884. if (val)
  4885. sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
  4886. }
  4887. out:
  4888. av_free(buffer);
  4889. return ret;
  4890. }
  4891. static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4892. {
  4893. AVStream *st;
  4894. MOVStreamContext *sc;
  4895. int64_t ret;
  4896. uint8_t uuid[16];
  4897. static const uint8_t uuid_isml_manifest[] = {
  4898. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  4899. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  4900. };
  4901. static const uint8_t uuid_xmp[] = {
  4902. 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
  4903. 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
  4904. };
  4905. static const uint8_t uuid_spherical[] = {
  4906. 0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
  4907. 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
  4908. };
  4909. if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
  4910. return AVERROR_INVALIDDATA;
  4911. if (c->fc->nb_streams < 1)
  4912. return 0;
  4913. st = c->fc->streams[c->fc->nb_streams - 1];
  4914. sc = st->priv_data;
  4915. ret = avio_read(pb, uuid, sizeof(uuid));
  4916. if (ret < 0) {
  4917. return ret;
  4918. } else if (ret != sizeof(uuid)) {
  4919. return AVERROR_INVALIDDATA;
  4920. }
  4921. if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
  4922. uint8_t *buffer, *ptr;
  4923. char *endptr;
  4924. size_t len = atom.size - sizeof(uuid);
  4925. if (len < 4) {
  4926. return AVERROR_INVALIDDATA;
  4927. }
  4928. ret = avio_skip(pb, 4); // zeroes
  4929. len -= 4;
  4930. buffer = av_mallocz(len + 1);
  4931. if (!buffer) {
  4932. return AVERROR(ENOMEM);
  4933. }
  4934. ret = avio_read(pb, buffer, len);
  4935. if (ret < 0) {
  4936. av_free(buffer);
  4937. return ret;
  4938. } else if (ret != len) {
  4939. av_free(buffer);
  4940. return AVERROR_INVALIDDATA;
  4941. }
  4942. ptr = buffer;
  4943. while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
  4944. ptr += sizeof("systemBitrate=\"") - 1;
  4945. c->bitrates_count++;
  4946. c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
  4947. if (!c->bitrates) {
  4948. c->bitrates_count = 0;
  4949. av_free(buffer);
  4950. return AVERROR(ENOMEM);
  4951. }
  4952. errno = 0;
  4953. ret = strtol(ptr, &endptr, 10);
  4954. if (ret < 0 || errno || *endptr != '"') {
  4955. c->bitrates[c->bitrates_count - 1] = 0;
  4956. } else {
  4957. c->bitrates[c->bitrates_count - 1] = ret;
  4958. }
  4959. }
  4960. av_free(buffer);
  4961. } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
  4962. uint8_t *buffer;
  4963. size_t len = atom.size - sizeof(uuid);
  4964. if (c->export_xmp) {
  4965. buffer = av_mallocz(len + 1);
  4966. if (!buffer) {
  4967. return AVERROR(ENOMEM);
  4968. }
  4969. ret = avio_read(pb, buffer, len);
  4970. if (ret < 0) {
  4971. av_free(buffer);
  4972. return ret;
  4973. } else if (ret != len) {
  4974. av_free(buffer);
  4975. return AVERROR_INVALIDDATA;
  4976. }
  4977. buffer[len] = '\0';
  4978. av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
  4979. av_free(buffer);
  4980. } else {
  4981. // skip all uuid atom, which makes it fast for long uuid-xmp file
  4982. ret = avio_skip(pb, len);
  4983. if (ret < 0)
  4984. return ret;
  4985. }
  4986. } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {
  4987. size_t len = atom.size - sizeof(uuid);
  4988. ret = mov_parse_uuid_spherical(sc, pb, len);
  4989. if (ret < 0)
  4990. return ret;
  4991. if (!sc->spherical)
  4992. av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n");
  4993. }
  4994. return 0;
  4995. }
  4996. static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4997. {
  4998. int ret;
  4999. uint8_t content[16];
  5000. if (atom.size < 8)
  5001. return 0;
  5002. ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
  5003. if (ret < 0)
  5004. return ret;
  5005. if ( !c->found_moov
  5006. && !c->found_mdat
  5007. && !memcmp(content, "Anevia\x1A\x1A", 8)
  5008. && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
  5009. c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
  5010. }
  5011. return 0;
  5012. }
  5013. static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  5014. {
  5015. uint32_t format = avio_rl32(pb);
  5016. MOVStreamContext *sc;
  5017. enum AVCodecID id;
  5018. AVStream *st;
  5019. if (c->fc->nb_streams < 1)
  5020. return 0;
  5021. st = c->fc->streams[c->fc->nb_streams - 1];
  5022. sc = st->priv_data;
  5023. switch (sc->format)
  5024. {
  5025. case MKTAG('e','n','c','v'): // encrypted video
  5026. case MKTAG('e','n','c','a'): // encrypted audio
  5027. id = mov_codec_id(st, format);
  5028. if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
  5029. st->codecpar->codec_id != id) {
  5030. av_log(c->fc, AV_LOG_WARNING,
  5031. "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
  5032. (char*)&format, st->codecpar->codec_id);
  5033. break;
  5034. }
  5035. st->codecpar->codec_id = id;
  5036. sc->format = format;
  5037. break;
  5038. default:
  5039. if (format != sc->format) {
  5040. av_log(c->fc, AV_LOG_WARNING,
  5041. "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
  5042. (char*)&format, (char*)&sc->format);
  5043. }
  5044. break;
  5045. }
  5046. return 0;
  5047. }
  5048. /**
  5049. * Gets the current encryption info and associated current stream context. If
  5050. * we are parsing a track fragment, this will return the specific encryption
  5051. * info for this fragment; otherwise this will return the global encryption
  5052. * info for the current stream.
  5053. */
  5054. static int get_current_encryption_info(MOVContext *c, MOVEncryptionIndex **encryption_index, MOVStreamContext **sc)
  5055. {
  5056. MOVFragmentStreamInfo *frag_stream_info;
  5057. AVStream *st;
  5058. int i;
  5059. frag_stream_info = get_current_frag_stream_info(&c->frag_index);
  5060. if (frag_stream_info) {
  5061. for (i = 0; i < c->fc->nb_streams; i++) {
  5062. if (c->fc->streams[i]->id == frag_stream_info->id) {
  5063. st = c->fc->streams[i];
  5064. break;
  5065. }
  5066. }
  5067. if (i == c->fc->nb_streams)
  5068. return 0;
  5069. *sc = st->priv_data;
  5070. if (!frag_stream_info->encryption_index) {
  5071. frag_stream_info->encryption_index = av_mallocz(sizeof(*frag_stream_info->encryption_index));
  5072. if (!frag_stream_info->encryption_index)
  5073. return AVERROR(ENOMEM);
  5074. }
  5075. *encryption_index = frag_stream_info->encryption_index;
  5076. return 1;
  5077. } else {
  5078. // No current track fragment, using stream level encryption info.
  5079. if (c->fc->nb_streams < 1)
  5080. return 0;
  5081. st = c->fc->streams[c->fc->nb_streams - 1];
  5082. *sc = st->priv_data;
  5083. if (!(*sc)->cenc.encryption_index) {
  5084. (*sc)->cenc.encryption_index = av_mallocz(sizeof(*frag_stream_info->encryption_index));
  5085. if (!(*sc)->cenc.encryption_index)
  5086. return AVERROR(ENOMEM);
  5087. }
  5088. *encryption_index = (*sc)->cenc.encryption_index;
  5089. return 1;
  5090. }
  5091. }
  5092. static int mov_read_sample_encryption_info(MOVContext *c, AVIOContext *pb, MOVStreamContext *sc, AVEncryptionInfo **sample, int use_subsamples)
  5093. {
  5094. int i;
  5095. unsigned int subsample_count;
  5096. AVSubsampleEncryptionInfo *subsamples;
  5097. if (!sc->cenc.default_encrypted_sample) {
  5098. av_log(c->fc, AV_LOG_ERROR, "Missing schm or tenc\n");
  5099. return AVERROR_INVALIDDATA;
  5100. }
  5101. *sample = av_encryption_info_clone(sc->cenc.default_encrypted_sample);
  5102. if (!*sample)
  5103. return AVERROR(ENOMEM);
  5104. if (sc->cenc.per_sample_iv_size != 0) {
  5105. if (avio_read(pb, (*sample)->iv, sc->cenc.per_sample_iv_size) != sc->cenc.per_sample_iv_size) {
  5106. av_log(c->fc, AV_LOG_ERROR, "failed to read the initialization vector\n");
  5107. av_encryption_info_free(*sample);
  5108. *sample = NULL;
  5109. return AVERROR_INVALIDDATA;
  5110. }
  5111. }
  5112. if (use_subsamples) {
  5113. subsample_count = avio_rb16(pb);
  5114. av_free((*sample)->subsamples);
  5115. (*sample)->subsamples = av_mallocz_array(subsample_count, sizeof(*subsamples));
  5116. if (!(*sample)->subsamples) {
  5117. av_encryption_info_free(*sample);
  5118. *sample = NULL;
  5119. return AVERROR(ENOMEM);
  5120. }
  5121. for (i = 0; i < subsample_count && !pb->eof_reached; i++) {
  5122. (*sample)->subsamples[i].bytes_of_clear_data = avio_rb16(pb);
  5123. (*sample)->subsamples[i].bytes_of_protected_data = avio_rb32(pb);
  5124. }
  5125. if (pb->eof_reached) {
  5126. av_log(c->fc, AV_LOG_ERROR, "hit EOF while reading sub-sample encryption info\n");
  5127. av_encryption_info_free(*sample);
  5128. *sample = NULL;
  5129. return AVERROR_INVALIDDATA;
  5130. }
  5131. (*sample)->subsample_count = subsample_count;
  5132. }
  5133. return 0;
  5134. }
  5135. static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  5136. {
  5137. AVEncryptionInfo **encrypted_samples;
  5138. MOVEncryptionIndex *encryption_index;
  5139. MOVStreamContext *sc;
  5140. int use_subsamples, ret;
  5141. unsigned int sample_count, i, alloc_size = 0;
  5142. ret = get_current_encryption_info(c, &encryption_index, &sc);
  5143. if (ret != 1)
  5144. return ret;
  5145. if (encryption_index->nb_encrypted_samples) {
  5146. // This can happen if we have both saio/saiz and senc atoms.
  5147. av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in senc\n");
  5148. return 0;
  5149. }
  5150. avio_r8(pb); /* version */
  5151. use_subsamples = avio_rb24(pb) & 0x02; /* flags */
  5152. sample_count = avio_rb32(pb);
  5153. if (sample_count >= INT_MAX / sizeof(*encrypted_samples))
  5154. return AVERROR(ENOMEM);
  5155. for (i = 0; i < sample_count; i++) {
  5156. unsigned int min_samples = FFMIN(FFMAX(i + 1, 1024 * 1024), sample_count);
  5157. encrypted_samples = av_fast_realloc(encryption_index->encrypted_samples, &alloc_size,
  5158. min_samples * sizeof(*encrypted_samples));
  5159. if (encrypted_samples) {
  5160. encryption_index->encrypted_samples = encrypted_samples;
  5161. ret = mov_read_sample_encryption_info(
  5162. c, pb, sc, &encryption_index->encrypted_samples[i], use_subsamples);
  5163. } else {
  5164. ret = AVERROR(ENOMEM);
  5165. }
  5166. if (pb->eof_reached) {
  5167. av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading senc\n");
  5168. ret = AVERROR_INVALIDDATA;
  5169. }
  5170. if (ret < 0) {
  5171. for (; i > 0; i--)
  5172. av_encryption_info_free(encryption_index->encrypted_samples[i - 1]);
  5173. av_freep(&encryption_index->encrypted_samples);
  5174. return ret;
  5175. }
  5176. }
  5177. encryption_index->nb_encrypted_samples = sample_count;
  5178. return 0;
  5179. }
  5180. static int mov_parse_auxiliary_info(MOVContext *c, MOVStreamContext *sc, AVIOContext *pb, MOVEncryptionIndex *encryption_index)
  5181. {
  5182. AVEncryptionInfo **sample, **encrypted_samples;
  5183. int64_t prev_pos;
  5184. size_t sample_count, sample_info_size, i;
  5185. int ret = 0;
  5186. unsigned int alloc_size = 0;
  5187. if (encryption_index->nb_encrypted_samples)
  5188. return 0;
  5189. sample_count = encryption_index->auxiliary_info_sample_count;
  5190. if (encryption_index->auxiliary_offsets_count != 1) {
  5191. av_log(c->fc, AV_LOG_ERROR, "Multiple auxiliary info chunks are not supported\n");
  5192. return AVERROR_PATCHWELCOME;
  5193. }
  5194. if (sample_count >= INT_MAX / sizeof(*encrypted_samples))
  5195. return AVERROR(ENOMEM);
  5196. prev_pos = avio_tell(pb);
  5197. if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) ||
  5198. avio_seek(pb, encryption_index->auxiliary_offsets[0], SEEK_SET) != encryption_index->auxiliary_offsets[0]) {
  5199. av_log(c->fc, AV_LOG_INFO, "Failed to seek for auxiliary info, will only parse senc atoms for encryption info\n");
  5200. goto finish;
  5201. }
  5202. for (i = 0; i < sample_count && !pb->eof_reached; i++) {
  5203. unsigned int min_samples = FFMIN(FFMAX(i + 1, 1024 * 1024), sample_count);
  5204. encrypted_samples = av_fast_realloc(encryption_index->encrypted_samples, &alloc_size,
  5205. min_samples * sizeof(*encrypted_samples));
  5206. if (!encrypted_samples) {
  5207. ret = AVERROR(ENOMEM);
  5208. goto finish;
  5209. }
  5210. encryption_index->encrypted_samples = encrypted_samples;
  5211. sample = &encryption_index->encrypted_samples[i];
  5212. sample_info_size = encryption_index->auxiliary_info_default_size
  5213. ? encryption_index->auxiliary_info_default_size
  5214. : encryption_index->auxiliary_info_sizes[i];
  5215. ret = mov_read_sample_encryption_info(c, pb, sc, sample, sample_info_size > sc->cenc.per_sample_iv_size);
  5216. if (ret < 0)
  5217. goto finish;
  5218. }
  5219. if (pb->eof_reached) {
  5220. av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading auxiliary info\n");
  5221. ret = AVERROR_INVALIDDATA;
  5222. } else {
  5223. encryption_index->nb_encrypted_samples = sample_count;
  5224. }
  5225. finish:
  5226. avio_seek(pb, prev_pos, SEEK_SET);
  5227. if (ret < 0) {
  5228. for (; i > 0; i--) {
  5229. av_encryption_info_free(encryption_index->encrypted_samples[i - 1]);
  5230. }
  5231. av_freep(&encryption_index->encrypted_samples);
  5232. }
  5233. return ret;
  5234. }
  5235. /**
  5236. * Tries to read the given number of bytes from the stream and puts it in a
  5237. * newly allocated buffer. This reads in small chunks to avoid allocating large
  5238. * memory if the file contains an invalid/malicious size value.
  5239. */
  5240. static int mov_try_read_block(AVIOContext *pb, size_t size, uint8_t **data)
  5241. {
  5242. const unsigned int block_size = 1024 * 1024;
  5243. uint8_t *buffer = NULL;
  5244. unsigned int alloc_size = 0, offset = 0;
  5245. while (offset < size) {
  5246. unsigned int new_size =
  5247. alloc_size >= INT_MAX - block_size ? INT_MAX : alloc_size + block_size;
  5248. uint8_t *new_buffer = av_fast_realloc(buffer, &alloc_size, new_size);
  5249. unsigned int to_read = FFMIN(size, alloc_size) - offset;
  5250. if (!new_buffer) {
  5251. av_free(buffer);
  5252. return AVERROR(ENOMEM);
  5253. }
  5254. buffer = new_buffer;
  5255. if (avio_read(pb, buffer + offset, to_read) != to_read) {
  5256. av_free(buffer);
  5257. return AVERROR_INVALIDDATA;
  5258. }
  5259. offset += to_read;
  5260. }
  5261. *data = buffer;
  5262. return 0;
  5263. }
  5264. static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  5265. {
  5266. MOVEncryptionIndex *encryption_index;
  5267. MOVStreamContext *sc;
  5268. int ret;
  5269. unsigned int sample_count, aux_info_type, aux_info_param;
  5270. ret = get_current_encryption_info(c, &encryption_index, &sc);
  5271. if (ret != 1)
  5272. return ret;
  5273. if (encryption_index->nb_encrypted_samples) {
  5274. // This can happen if we have both saio/saiz and senc atoms.
  5275. av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in saiz\n");
  5276. return 0;
  5277. }
  5278. if (encryption_index->auxiliary_info_sample_count) {
  5279. av_log(c->fc, AV_LOG_ERROR, "Duplicate saiz atom\n");
  5280. return AVERROR_INVALIDDATA;
  5281. }
  5282. avio_r8(pb); /* version */
  5283. if (avio_rb24(pb) & 0x01) { /* flags */
  5284. aux_info_type = avio_rb32(pb);
  5285. aux_info_param = avio_rb32(pb);
  5286. if (sc->cenc.default_encrypted_sample) {
  5287. if (aux_info_type != sc->cenc.default_encrypted_sample->scheme) {
  5288. av_log(c->fc, AV_LOG_DEBUG, "Ignoring saiz box with non-zero aux_info_type\n");
  5289. return 0;
  5290. }
  5291. if (aux_info_param != 0) {
  5292. av_log(c->fc, AV_LOG_DEBUG, "Ignoring saiz box with non-zero aux_info_type_parameter\n");
  5293. return 0;
  5294. }
  5295. } else {
  5296. // Didn't see 'schm' or 'tenc', so this isn't encrypted.
  5297. if ((aux_info_type == MKBETAG('c','e','n','c') ||
  5298. aux_info_type == MKBETAG('c','e','n','s') ||
  5299. aux_info_type == MKBETAG('c','b','c','1') ||
  5300. aux_info_type == MKBETAG('c','b','c','s')) &&
  5301. aux_info_param == 0) {
  5302. av_log(c->fc, AV_LOG_ERROR, "Saw encrypted saiz without schm/tenc\n");
  5303. return AVERROR_INVALIDDATA;
  5304. } else {
  5305. return 0;
  5306. }
  5307. }
  5308. } else if (!sc->cenc.default_encrypted_sample) {
  5309. // Didn't see 'schm' or 'tenc', so this isn't encrypted.
  5310. return 0;
  5311. }
  5312. encryption_index->auxiliary_info_default_size = avio_r8(pb);
  5313. sample_count = avio_rb32(pb);
  5314. encryption_index->auxiliary_info_sample_count = sample_count;
  5315. if (encryption_index->auxiliary_info_default_size == 0) {
  5316. ret = mov_try_read_block(pb, sample_count, &encryption_index->auxiliary_info_sizes);
  5317. if (ret < 0) {
  5318. av_log(c->fc, AV_LOG_ERROR, "Failed to read the auxiliary info\n");
  5319. return ret;
  5320. }
  5321. }
  5322. if (encryption_index->auxiliary_offsets_count) {
  5323. return mov_parse_auxiliary_info(c, sc, pb, encryption_index);
  5324. }
  5325. return 0;
  5326. }
  5327. static int mov_read_saio(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  5328. {
  5329. uint64_t *auxiliary_offsets;
  5330. MOVEncryptionIndex *encryption_index;
  5331. MOVStreamContext *sc;
  5332. int i, ret;
  5333. unsigned int version, entry_count, aux_info_type, aux_info_param;
  5334. unsigned int alloc_size = 0;
  5335. ret = get_current_encryption_info(c, &encryption_index, &sc);
  5336. if (ret != 1)
  5337. return ret;
  5338. if (encryption_index->nb_encrypted_samples) {
  5339. // This can happen if we have both saio/saiz and senc atoms.
  5340. av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in saio\n");
  5341. return 0;
  5342. }
  5343. if (encryption_index->auxiliary_offsets_count) {
  5344. av_log(c->fc, AV_LOG_ERROR, "Duplicate saio atom\n");
  5345. return AVERROR_INVALIDDATA;
  5346. }
  5347. version = avio_r8(pb); /* version */
  5348. if (avio_rb24(pb) & 0x01) { /* flags */
  5349. aux_info_type = avio_rb32(pb);
  5350. aux_info_param = avio_rb32(pb);
  5351. if (sc->cenc.default_encrypted_sample) {
  5352. if (aux_info_type != sc->cenc.default_encrypted_sample->scheme) {
  5353. av_log(c->fc, AV_LOG_DEBUG, "Ignoring saio box with non-zero aux_info_type\n");
  5354. return 0;
  5355. }
  5356. if (aux_info_param != 0) {
  5357. av_log(c->fc, AV_LOG_DEBUG, "Ignoring saio box with non-zero aux_info_type_parameter\n");
  5358. return 0;
  5359. }
  5360. } else {
  5361. // Didn't see 'schm' or 'tenc', so this isn't encrypted.
  5362. if ((aux_info_type == MKBETAG('c','e','n','c') ||
  5363. aux_info_type == MKBETAG('c','e','n','s') ||
  5364. aux_info_type == MKBETAG('c','b','c','1') ||
  5365. aux_info_type == MKBETAG('c','b','c','s')) &&
  5366. aux_info_param == 0) {
  5367. av_log(c->fc, AV_LOG_ERROR, "Saw encrypted saio without schm/tenc\n");
  5368. return AVERROR_INVALIDDATA;
  5369. } else {
  5370. return 0;
  5371. }
  5372. }
  5373. } else if (!sc->cenc.default_encrypted_sample) {
  5374. // Didn't see 'schm' or 'tenc', so this isn't encrypted.
  5375. return 0;
  5376. }
  5377. entry_count = avio_rb32(pb);
  5378. if (entry_count >= INT_MAX / sizeof(*auxiliary_offsets))
  5379. return AVERROR(ENOMEM);
  5380. for (i = 0; i < entry_count && !pb->eof_reached; i++) {
  5381. unsigned int min_offsets = FFMIN(FFMAX(i + 1, 1024), entry_count);
  5382. auxiliary_offsets = av_fast_realloc(
  5383. encryption_index->auxiliary_offsets, &alloc_size,
  5384. min_offsets * sizeof(*auxiliary_offsets));
  5385. if (!auxiliary_offsets) {
  5386. av_freep(&encryption_index->auxiliary_offsets);
  5387. return AVERROR(ENOMEM);
  5388. }
  5389. encryption_index->auxiliary_offsets = auxiliary_offsets;
  5390. if (version == 0) {
  5391. encryption_index->auxiliary_offsets[i] = avio_rb32(pb);
  5392. } else {
  5393. encryption_index->auxiliary_offsets[i] = avio_rb64(pb);
  5394. }
  5395. if (c->frag_index.current >= 0) {
  5396. encryption_index->auxiliary_offsets[i] += c->fragment.base_data_offset;
  5397. }
  5398. }
  5399. if (pb->eof_reached) {
  5400. av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading saio\n");
  5401. av_freep(&encryption_index->auxiliary_offsets);
  5402. return AVERROR_INVALIDDATA;
  5403. }
  5404. encryption_index->auxiliary_offsets_count = entry_count;
  5405. if (encryption_index->auxiliary_info_sample_count) {
  5406. return mov_parse_auxiliary_info(c, sc, pb, encryption_index);
  5407. }
  5408. return 0;
  5409. }
  5410. static int mov_read_pssh(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  5411. {
  5412. AVEncryptionInitInfo *info, *old_init_info;
  5413. uint8_t **key_ids;
  5414. AVStream *st;
  5415. uint8_t *side_data, *extra_data, *old_side_data;
  5416. size_t side_data_size;
  5417. int ret = 0, old_side_data_size;
  5418. unsigned int version, kid_count, extra_data_size, alloc_size = 0;
  5419. if (c->fc->nb_streams < 1)
  5420. return 0;
  5421. st = c->fc->streams[c->fc->nb_streams-1];
  5422. version = avio_r8(pb); /* version */
  5423. avio_rb24(pb); /* flags */
  5424. info = av_encryption_init_info_alloc(/* system_id_size */ 16, /* num_key_ids */ 0,
  5425. /* key_id_size */ 16, /* data_size */ 0);
  5426. if (!info)
  5427. return AVERROR(ENOMEM);
  5428. if (avio_read(pb, info->system_id, 16) != 16) {
  5429. av_log(c->fc, AV_LOG_ERROR, "Failed to read the system id\n");
  5430. ret = AVERROR_INVALIDDATA;
  5431. goto finish;
  5432. }
  5433. if (version > 0) {
  5434. kid_count = avio_rb32(pb);
  5435. if (kid_count >= INT_MAX / sizeof(*key_ids))
  5436. return AVERROR(ENOMEM);
  5437. for (unsigned int i = 0; i < kid_count && !pb->eof_reached; i++) {
  5438. unsigned int min_kid_count = FFMIN(FFMAX(i + 1, 1024), kid_count);
  5439. key_ids = av_fast_realloc(info->key_ids, &alloc_size,
  5440. min_kid_count * sizeof(*key_ids));
  5441. if (!key_ids) {
  5442. ret = AVERROR(ENOMEM);
  5443. goto finish;
  5444. }
  5445. info->key_ids = key_ids;
  5446. info->key_ids[i] = av_mallocz(16);
  5447. if (!info->key_ids[i]) {
  5448. ret = AVERROR(ENOMEM);
  5449. goto finish;
  5450. }
  5451. info->num_key_ids = i + 1;
  5452. if (avio_read(pb, info->key_ids[i], 16) != 16) {
  5453. av_log(c->fc, AV_LOG_ERROR, "Failed to read the key id\n");
  5454. ret = AVERROR_INVALIDDATA;
  5455. goto finish;
  5456. }
  5457. }
  5458. if (pb->eof_reached) {
  5459. av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading pssh\n");
  5460. ret = AVERROR_INVALIDDATA;
  5461. goto finish;
  5462. }
  5463. }
  5464. extra_data_size = avio_rb32(pb);
  5465. ret = mov_try_read_block(pb, extra_data_size, &extra_data);
  5466. if (ret < 0)
  5467. goto finish;
  5468. av_freep(&info->data); // malloc(0) may still allocate something.
  5469. info->data = extra_data;
  5470. info->data_size = extra_data_size;
  5471. // If there is existing initialization data, append to the list.
  5472. old_side_data = av_stream_get_side_data(st, AV_PKT_DATA_ENCRYPTION_INIT_INFO, &old_side_data_size);
  5473. if (old_side_data) {
  5474. old_init_info = av_encryption_init_info_get_side_data(old_side_data, old_side_data_size);
  5475. if (old_init_info) {
  5476. // Append to the end of the list.
  5477. for (AVEncryptionInitInfo *cur = old_init_info;; cur = cur->next) {
  5478. if (!cur->next) {
  5479. cur->next = info;
  5480. break;
  5481. }
  5482. }
  5483. info = old_init_info;
  5484. } else {
  5485. // Assume existing side-data will be valid, so the only error we could get is OOM.
  5486. ret = AVERROR(ENOMEM);
  5487. goto finish;
  5488. }
  5489. }
  5490. side_data = av_encryption_init_info_add_side_data(info, &side_data_size);
  5491. if (!side_data) {
  5492. ret = AVERROR(ENOMEM);
  5493. goto finish;
  5494. }
  5495. ret = av_stream_add_side_data(st, AV_PKT_DATA_ENCRYPTION_INIT_INFO,
  5496. side_data, side_data_size);
  5497. if (ret < 0)
  5498. av_free(side_data);
  5499. finish:
  5500. av_encryption_init_info_free(info);
  5501. return ret;
  5502. }
  5503. static int mov_read_schm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  5504. {
  5505. AVStream *st;
  5506. MOVStreamContext *sc;
  5507. if (c->fc->nb_streams < 1)
  5508. return 0;
  5509. st = c->fc->streams[c->fc->nb_streams-1];
  5510. sc = st->priv_data;
  5511. if (sc->pseudo_stream_id != 0) {
  5512. av_log(c->fc, AV_LOG_ERROR, "schm boxes are only supported in first sample descriptor\n");
  5513. return AVERROR_PATCHWELCOME;
  5514. }
  5515. if (atom.size < 8)
  5516. return AVERROR_INVALIDDATA;
  5517. avio_rb32(pb); /* version and flags */
  5518. if (!sc->cenc.default_encrypted_sample) {
  5519. sc->cenc.default_encrypted_sample = av_encryption_info_alloc(0, 16, 16);
  5520. if (!sc->cenc.default_encrypted_sample) {
  5521. return AVERROR(ENOMEM);
  5522. }
  5523. }
  5524. sc->cenc.default_encrypted_sample->scheme = avio_rb32(pb);
  5525. return 0;
  5526. }
  5527. static int mov_read_tenc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  5528. {
  5529. AVStream *st;
  5530. MOVStreamContext *sc;
  5531. unsigned int version, pattern, is_protected, iv_size;
  5532. if (c->fc->nb_streams < 1)
  5533. return 0;
  5534. st = c->fc->streams[c->fc->nb_streams-1];
  5535. sc = st->priv_data;
  5536. if (sc->pseudo_stream_id != 0) {
  5537. av_log(c->fc, AV_LOG_ERROR, "tenc atom are only supported in first sample descriptor\n");
  5538. return AVERROR_PATCHWELCOME;
  5539. }
  5540. if (!sc->cenc.default_encrypted_sample) {
  5541. sc->cenc.default_encrypted_sample = av_encryption_info_alloc(0, 16, 16);
  5542. if (!sc->cenc.default_encrypted_sample) {
  5543. return AVERROR(ENOMEM);
  5544. }
  5545. }
  5546. if (atom.size < 20)
  5547. return AVERROR_INVALIDDATA;
  5548. version = avio_r8(pb); /* version */
  5549. avio_rb24(pb); /* flags */
  5550. avio_r8(pb); /* reserved */
  5551. pattern = avio_r8(pb);
  5552. if (version > 0) {
  5553. sc->cenc.default_encrypted_sample->crypt_byte_block = pattern >> 4;
  5554. sc->cenc.default_encrypted_sample->skip_byte_block = pattern & 0xf;
  5555. }
  5556. is_protected = avio_r8(pb);
  5557. if (is_protected && !sc->cenc.encryption_index) {
  5558. // The whole stream should be by-default encrypted.
  5559. sc->cenc.encryption_index = av_mallocz(sizeof(MOVEncryptionIndex));
  5560. if (!sc->cenc.encryption_index)
  5561. return AVERROR(ENOMEM);
  5562. }
  5563. sc->cenc.per_sample_iv_size = avio_r8(pb);
  5564. if (sc->cenc.per_sample_iv_size != 0 && sc->cenc.per_sample_iv_size != 8 &&
  5565. sc->cenc.per_sample_iv_size != 16) {
  5566. av_log(c->fc, AV_LOG_ERROR, "invalid per-sample IV size value\n");
  5567. return AVERROR_INVALIDDATA;
  5568. }
  5569. if (avio_read(pb, sc->cenc.default_encrypted_sample->key_id, 16) != 16) {
  5570. av_log(c->fc, AV_LOG_ERROR, "failed to read the default key ID\n");
  5571. return AVERROR_INVALIDDATA;
  5572. }
  5573. if (is_protected && !sc->cenc.per_sample_iv_size) {
  5574. iv_size = avio_r8(pb);
  5575. if (iv_size != 8 && iv_size != 16) {
  5576. av_log(c->fc, AV_LOG_ERROR, "invalid default_constant_IV_size in tenc atom\n");
  5577. return AVERROR_INVALIDDATA;
  5578. }
  5579. if (avio_read(pb, sc->cenc.default_encrypted_sample->iv, iv_size) != iv_size) {
  5580. av_log(c->fc, AV_LOG_ERROR, "failed to read the default IV\n");
  5581. return AVERROR_INVALIDDATA;
  5582. }
  5583. }
  5584. return 0;
  5585. }
  5586. static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  5587. {
  5588. AVStream *st;
  5589. int last, type, size, ret;
  5590. uint8_t buf[4];
  5591. if (c->fc->nb_streams < 1)
  5592. return 0;
  5593. st = c->fc->streams[c->fc->nb_streams-1];
  5594. if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
  5595. return AVERROR_INVALIDDATA;
  5596. /* Check FlacSpecificBox version. */
  5597. if (avio_r8(pb) != 0)
  5598. return AVERROR_INVALIDDATA;
  5599. avio_rb24(pb); /* Flags */
  5600. avio_read(pb, buf, sizeof(buf));
  5601. flac_parse_block_header(buf, &last, &type, &size);
  5602. if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) {
  5603. av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
  5604. return AVERROR_INVALIDDATA;
  5605. }
  5606. ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
  5607. if (ret < 0)
  5608. return ret;
  5609. if (!last)
  5610. av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
  5611. return 0;
  5612. }
  5613. static int cenc_decrypt(MOVContext *c, MOVStreamContext *sc, AVEncryptionInfo *sample, uint8_t *input, int size)
  5614. {
  5615. int i, ret;
  5616. if (sample->scheme != MKBETAG('c','e','n','c') || sample->crypt_byte_block != 0 || sample->skip_byte_block != 0) {
  5617. av_log(c->fc, AV_LOG_ERROR, "Only the 'cenc' encryption scheme is supported\n");
  5618. return AVERROR_PATCHWELCOME;
  5619. }
  5620. if (!sc->cenc.aes_ctr) {
  5621. /* initialize the cipher */
  5622. sc->cenc.aes_ctr = av_aes_ctr_alloc();
  5623. if (!sc->cenc.aes_ctr) {
  5624. return AVERROR(ENOMEM);
  5625. }
  5626. ret = av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
  5627. if (ret < 0) {
  5628. return ret;
  5629. }
  5630. }
  5631. av_aes_ctr_set_full_iv(sc->cenc.aes_ctr, sample->iv);
  5632. if (!sample->subsample_count)
  5633. {
  5634. /* decrypt the whole packet */
  5635. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
  5636. return 0;
  5637. }
  5638. for (i = 0; i < sample->subsample_count; i++)
  5639. {
  5640. if (sample->subsamples[i].bytes_of_clear_data + sample->subsamples[i].bytes_of_protected_data > size) {
  5641. av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
  5642. return AVERROR_INVALIDDATA;
  5643. }
  5644. /* skip the clear bytes */
  5645. input += sample->subsamples[i].bytes_of_clear_data;
  5646. size -= sample->subsamples[i].bytes_of_clear_data;
  5647. /* decrypt the encrypted bytes */
  5648. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, sample->subsamples[i].bytes_of_protected_data);
  5649. input += sample->subsamples[i].bytes_of_protected_data;
  5650. size -= sample->subsamples[i].bytes_of_protected_data;
  5651. }
  5652. if (size > 0) {
  5653. av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
  5654. return AVERROR_INVALIDDATA;
  5655. }
  5656. return 0;
  5657. }
  5658. static int cenc_filter(MOVContext *mov, MOVStreamContext *sc, AVPacket *pkt, int current_index)
  5659. {
  5660. MOVFragmentStreamInfo *frag_stream_info;
  5661. MOVEncryptionIndex *encryption_index;
  5662. AVEncryptionInfo *encrypted_sample;
  5663. int encrypted_index, ret;
  5664. frag_stream_info = get_current_frag_stream_info(&mov->frag_index);
  5665. encrypted_index = current_index;
  5666. encryption_index = NULL;
  5667. if (frag_stream_info) {
  5668. // Note this only supports encryption info in the first sample descriptor.
  5669. if (mov->fragment.stsd_id == 1) {
  5670. if (frag_stream_info->encryption_index) {
  5671. encrypted_index = current_index - frag_stream_info->index_entry;
  5672. encryption_index = frag_stream_info->encryption_index;
  5673. } else {
  5674. encryption_index = sc->cenc.encryption_index;
  5675. }
  5676. }
  5677. } else {
  5678. encryption_index = sc->cenc.encryption_index;
  5679. }
  5680. if (encryption_index) {
  5681. if (encryption_index->auxiliary_info_sample_count &&
  5682. !encryption_index->nb_encrypted_samples) {
  5683. av_log(mov->fc, AV_LOG_ERROR, "saiz atom found without saio\n");
  5684. return AVERROR_INVALIDDATA;
  5685. }
  5686. if (encryption_index->auxiliary_offsets_count &&
  5687. !encryption_index->nb_encrypted_samples) {
  5688. av_log(mov->fc, AV_LOG_ERROR, "saio atom found without saiz\n");
  5689. return AVERROR_INVALIDDATA;
  5690. }
  5691. if (!encryption_index->nb_encrypted_samples) {
  5692. // Full-sample encryption with default settings.
  5693. encrypted_sample = sc->cenc.default_encrypted_sample;
  5694. } else if (encrypted_index >= 0 && encrypted_index < encryption_index->nb_encrypted_samples) {
  5695. // Per-sample setting override.
  5696. encrypted_sample = encryption_index->encrypted_samples[encrypted_index];
  5697. } else {
  5698. av_log(mov->fc, AV_LOG_ERROR, "Incorrect number of samples in encryption info\n");
  5699. return AVERROR_INVALIDDATA;
  5700. }
  5701. if (mov->decryption_key) {
  5702. return cenc_decrypt(mov, sc, encrypted_sample, pkt->data, pkt->size);
  5703. } else {
  5704. size_t size;
  5705. uint8_t *side_data = av_encryption_info_add_side_data(encrypted_sample, &size);
  5706. if (!side_data)
  5707. return AVERROR(ENOMEM);
  5708. ret = av_packet_add_side_data(pkt, AV_PKT_DATA_ENCRYPTION_INFO, side_data, size);
  5709. if (ret < 0)
  5710. av_free(side_data);
  5711. return ret;
  5712. }
  5713. }
  5714. return 0;
  5715. }
  5716. static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  5717. {
  5718. const int OPUS_SEEK_PREROLL_MS = 80;
  5719. AVStream *st;
  5720. size_t size;
  5721. int16_t pre_skip;
  5722. if (c->fc->nb_streams < 1)
  5723. return 0;
  5724. st = c->fc->streams[c->fc->nb_streams-1];
  5725. if ((uint64_t)atom.size > (1<<30) || atom.size < 11)
  5726. return AVERROR_INVALIDDATA;
  5727. /* Check OpusSpecificBox version. */
  5728. if (avio_r8(pb) != 0) {
  5729. av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
  5730. return AVERROR_INVALIDDATA;
  5731. }
  5732. /* OpusSpecificBox size plus magic for Ogg OpusHead header. */
  5733. size = atom.size + 8;
  5734. if (ff_alloc_extradata(st->codecpar, size))
  5735. return AVERROR(ENOMEM);
  5736. AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s'));
  5737. AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
  5738. AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
  5739. avio_read(pb, st->codecpar->extradata + 9, size - 9);
  5740. /* OpusSpecificBox is stored in big-endian, but OpusHead is
  5741. little-endian; aside from the preceeding magic and version they're
  5742. otherwise currently identical. Data after output gain at offset 16
  5743. doesn't need to be bytewapped. */
  5744. pre_skip = AV_RB16(st->codecpar->extradata + 10);
  5745. AV_WL16(st->codecpar->extradata + 10, pre_skip);
  5746. AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12));
  5747. AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16));
  5748. st->codecpar->initial_padding = pre_skip;
  5749. st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS,
  5750. (AVRational){1, 1000},
  5751. (AVRational){1, 48000});
  5752. return 0;
  5753. }
  5754. static const MOVParseTableEntry mov_default_parse_table[] = {
  5755. { MKTAG('A','C','L','R'), mov_read_aclr },
  5756. { MKTAG('A','P','R','G'), mov_read_avid },
  5757. { MKTAG('A','A','L','P'), mov_read_avid },
  5758. { MKTAG('A','R','E','S'), mov_read_ares },
  5759. { MKTAG('a','v','s','s'), mov_read_avss },
  5760. { MKTAG('a','v','1','C'), mov_read_av1c },
  5761. { MKTAG('c','h','p','l'), mov_read_chpl },
  5762. { MKTAG('c','o','6','4'), mov_read_stco },
  5763. { MKTAG('c','o','l','r'), mov_read_colr },
  5764. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  5765. { MKTAG('d','i','n','f'), mov_read_default },
  5766. { MKTAG('D','p','x','E'), mov_read_dpxe },
  5767. { MKTAG('d','r','e','f'), mov_read_dref },
  5768. { MKTAG('e','d','t','s'), mov_read_default },
  5769. { MKTAG('e','l','s','t'), mov_read_elst },
  5770. { MKTAG('e','n','d','a'), mov_read_enda },
  5771. { MKTAG('f','i','e','l'), mov_read_fiel },
  5772. { MKTAG('a','d','r','m'), mov_read_adrm },
  5773. { MKTAG('f','t','y','p'), mov_read_ftyp },
  5774. { MKTAG('g','l','b','l'), mov_read_glbl },
  5775. { MKTAG('h','d','l','r'), mov_read_hdlr },
  5776. { MKTAG('i','l','s','t'), mov_read_ilst },
  5777. { MKTAG('j','p','2','h'), mov_read_jp2h },
  5778. { MKTAG('m','d','a','t'), mov_read_mdat },
  5779. { MKTAG('m','d','h','d'), mov_read_mdhd },
  5780. { MKTAG('m','d','i','a'), mov_read_default },
  5781. { MKTAG('m','e','t','a'), mov_read_meta },
  5782. { MKTAG('m','i','n','f'), mov_read_default },
  5783. { MKTAG('m','o','o','f'), mov_read_moof },
  5784. { MKTAG('m','o','o','v'), mov_read_moov },
  5785. { MKTAG('m','v','e','x'), mov_read_default },
  5786. { MKTAG('m','v','h','d'), mov_read_mvhd },
  5787. { MKTAG('S','M','I',' '), mov_read_svq3 },
  5788. { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
  5789. { MKTAG('a','v','c','C'), mov_read_glbl },
  5790. { MKTAG('p','a','s','p'), mov_read_pasp },
  5791. { MKTAG('s','i','d','x'), mov_read_sidx },
  5792. { MKTAG('s','t','b','l'), mov_read_default },
  5793. { MKTAG('s','t','c','o'), mov_read_stco },
  5794. { MKTAG('s','t','p','s'), mov_read_stps },
  5795. { MKTAG('s','t','r','f'), mov_read_strf },
  5796. { MKTAG('s','t','s','c'), mov_read_stsc },
  5797. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  5798. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  5799. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  5800. { MKTAG('s','t','t','s'), mov_read_stts },
  5801. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  5802. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  5803. { MKTAG('t','f','d','t'), mov_read_tfdt },
  5804. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  5805. { MKTAG('t','r','a','k'), mov_read_trak },
  5806. { MKTAG('t','r','a','f'), mov_read_default },
  5807. { MKTAG('t','r','e','f'), mov_read_default },
  5808. { MKTAG('t','m','c','d'), mov_read_tmcd },
  5809. { MKTAG('c','h','a','p'), mov_read_chap },
  5810. { MKTAG('t','r','e','x'), mov_read_trex },
  5811. { MKTAG('t','r','u','n'), mov_read_trun },
  5812. { MKTAG('u','d','t','a'), mov_read_default },
  5813. { MKTAG('w','a','v','e'), mov_read_wave },
  5814. { MKTAG('e','s','d','s'), mov_read_esds },
  5815. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  5816. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  5817. { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
  5818. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  5819. { MKTAG('w','f','e','x'), mov_read_wfex },
  5820. { MKTAG('c','m','o','v'), mov_read_cmov },
  5821. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  5822. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  5823. { MKTAG('s','b','g','p'), mov_read_sbgp },
  5824. { MKTAG('h','v','c','C'), mov_read_glbl },
  5825. { MKTAG('u','u','i','d'), mov_read_uuid },
  5826. { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
  5827. { MKTAG('f','r','e','e'), mov_read_free },
  5828. { MKTAG('-','-','-','-'), mov_read_custom },
  5829. { MKTAG('s','i','n','f'), mov_read_default },
  5830. { MKTAG('f','r','m','a'), mov_read_frma },
  5831. { MKTAG('s','e','n','c'), mov_read_senc },
  5832. { MKTAG('s','a','i','z'), mov_read_saiz },
  5833. { MKTAG('s','a','i','o'), mov_read_saio },
  5834. { MKTAG('p','s','s','h'), mov_read_pssh },
  5835. { MKTAG('s','c','h','m'), mov_read_schm },
  5836. { MKTAG('s','c','h','i'), mov_read_default },
  5837. { MKTAG('t','e','n','c'), mov_read_tenc },
  5838. { MKTAG('d','f','L','a'), mov_read_dfla },
  5839. { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
  5840. { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
  5841. { MKTAG('d','O','p','s'), mov_read_dops },
  5842. { MKTAG('S','m','D','m'), mov_read_smdm },
  5843. { MKTAG('C','o','L','L'), mov_read_coll },
  5844. { MKTAG('v','p','c','C'), mov_read_vpcc },
  5845. { MKTAG('m','d','c','v'), mov_read_mdcv },
  5846. { MKTAG('c','l','l','i'), mov_read_clli },
  5847. { 0, NULL }
  5848. };
  5849. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  5850. {
  5851. int64_t total_size = 0;
  5852. MOVAtom a;
  5853. int i;
  5854. if (c->atom_depth > 10) {
  5855. av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
  5856. return AVERROR_INVALIDDATA;
  5857. }
  5858. c->atom_depth ++;
  5859. if (atom.size < 0)
  5860. atom.size = INT64_MAX;
  5861. while (total_size <= atom.size - 8 && !avio_feof(pb)) {
  5862. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  5863. a.size = atom.size;
  5864. a.type=0;
  5865. if (atom.size >= 8) {
  5866. a.size = avio_rb32(pb);
  5867. a.type = avio_rl32(pb);
  5868. if (a.type == MKTAG('f','r','e','e') &&
  5869. a.size >= 8 &&
  5870. c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT &&
  5871. c->moov_retry) {
  5872. uint8_t buf[8];
  5873. uint32_t *type = (uint32_t *)buf + 1;
  5874. if (avio_read(pb, buf, 8) != 8)
  5875. return AVERROR_INVALIDDATA;
  5876. avio_seek(pb, -8, SEEK_CUR);
  5877. if (*type == MKTAG('m','v','h','d') ||
  5878. *type == MKTAG('c','m','o','v')) {
  5879. av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
  5880. a.type = MKTAG('m','o','o','v');
  5881. }
  5882. }
  5883. if (atom.type != MKTAG('r','o','o','t') &&
  5884. atom.type != MKTAG('m','o','o','v'))
  5885. {
  5886. if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
  5887. {
  5888. av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
  5889. avio_skip(pb, -8);
  5890. c->atom_depth --;
  5891. return 0;
  5892. }
  5893. }
  5894. total_size += 8;
  5895. if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
  5896. a.size = avio_rb64(pb) - 8;
  5897. total_size += 8;
  5898. }
  5899. }
  5900. av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  5901. av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size);
  5902. if (a.size == 0) {
  5903. a.size = atom.size - total_size + 8;
  5904. }
  5905. a.size -= 8;
  5906. if (a.size < 0)
  5907. break;
  5908. a.size = FFMIN(a.size, atom.size - total_size);
  5909. for (i = 0; mov_default_parse_table[i].type; i++)
  5910. if (mov_default_parse_table[i].type == a.type) {
  5911. parse = mov_default_parse_table[i].parse;
  5912. break;
  5913. }
  5914. // container is user data
  5915. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  5916. atom.type == MKTAG('i','l','s','t')))
  5917. parse = mov_read_udta_string;
  5918. // Supports parsing the QuickTime Metadata Keys.
  5919. // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
  5920. if (!parse && c->found_hdlr_mdta &&
  5921. atom.type == MKTAG('m','e','t','a') &&
  5922. a.type == MKTAG('k','e','y','s')) {
  5923. parse = mov_read_keys;
  5924. }
  5925. if (!parse) { /* skip leaf atoms data */
  5926. avio_skip(pb, a.size);
  5927. } else {
  5928. int64_t start_pos = avio_tell(pb);
  5929. int64_t left;
  5930. int err = parse(c, pb, a);
  5931. if (err < 0) {
  5932. c->atom_depth --;
  5933. return err;
  5934. }
  5935. if (c->found_moov && c->found_mdat &&
  5936. ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete) ||
  5937. start_pos + a.size == avio_size(pb))) {
  5938. if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete)
  5939. c->next_root_atom = start_pos + a.size;
  5940. c->atom_depth --;
  5941. return 0;
  5942. }
  5943. left = a.size - avio_tell(pb) + start_pos;
  5944. if (left > 0) /* skip garbage at atom end */
  5945. avio_skip(pb, left);
  5946. else if (left < 0) {
  5947. av_log(c->fc, AV_LOG_WARNING,
  5948. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  5949. (char*)&a.type, -left);
  5950. avio_seek(pb, left, SEEK_CUR);
  5951. }
  5952. }
  5953. total_size += a.size;
  5954. }
  5955. if (total_size < atom.size && atom.size < 0x7ffff)
  5956. avio_skip(pb, atom.size - total_size);
  5957. c->atom_depth --;
  5958. return 0;
  5959. }
  5960. static int mov_probe(AVProbeData *p)
  5961. {
  5962. int64_t offset;
  5963. uint32_t tag;
  5964. int score = 0;
  5965. int moov_offset = -1;
  5966. /* check file header */
  5967. offset = 0;
  5968. for (;;) {
  5969. /* ignore invalid offset */
  5970. if ((offset + 8) > (unsigned int)p->buf_size)
  5971. break;
  5972. tag = AV_RL32(p->buf + offset + 4);
  5973. switch(tag) {
  5974. /* check for obvious tags */
  5975. case MKTAG('m','o','o','v'):
  5976. moov_offset = offset + 4;
  5977. case MKTAG('m','d','a','t'):
  5978. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  5979. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  5980. case MKTAG('f','t','y','p'):
  5981. if (AV_RB32(p->buf+offset) < 8 &&
  5982. (AV_RB32(p->buf+offset) != 1 ||
  5983. offset + 12 > (unsigned int)p->buf_size ||
  5984. AV_RB64(p->buf+offset + 8) == 0)) {
  5985. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  5986. } else if (tag == MKTAG('f','t','y','p') &&
  5987. ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
  5988. || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
  5989. )) {
  5990. score = FFMAX(score, 5);
  5991. } else {
  5992. score = AVPROBE_SCORE_MAX;
  5993. }
  5994. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  5995. break;
  5996. /* those are more common words, so rate then a bit less */
  5997. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  5998. case MKTAG('w','i','d','e'):
  5999. case MKTAG('f','r','e','e'):
  6000. case MKTAG('j','u','n','k'):
  6001. case MKTAG('p','i','c','t'):
  6002. score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
  6003. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  6004. break;
  6005. case MKTAG(0x82,0x82,0x7f,0x7d):
  6006. case MKTAG('s','k','i','p'):
  6007. case MKTAG('u','u','i','d'):
  6008. case MKTAG('p','r','f','l'):
  6009. /* if we only find those cause probedata is too small at least rate them */
  6010. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  6011. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  6012. break;
  6013. default:
  6014. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  6015. }
  6016. }
  6017. if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
  6018. /* moov atom in the header - we should make sure that this is not a
  6019. * MOV-packed MPEG-PS */
  6020. offset = moov_offset;
  6021. while(offset < (p->buf_size - 16)){ /* Sufficient space */
  6022. /* We found an actual hdlr atom */
  6023. if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
  6024. AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
  6025. AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
  6026. av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
  6027. /* We found a media handler reference atom describing an
  6028. * MPEG-PS-in-MOV, return a
  6029. * low score to force expanding the probe window until
  6030. * mpegps_probe finds what it needs */
  6031. return 5;
  6032. }else
  6033. /* Keep looking */
  6034. offset+=2;
  6035. }
  6036. }
  6037. return score;
  6038. }
  6039. // must be done after parsing all trak because there's no order requirement
  6040. static void mov_read_chapters(AVFormatContext *s)
  6041. {
  6042. MOVContext *mov = s->priv_data;
  6043. AVStream *st;
  6044. MOVStreamContext *sc;
  6045. int64_t cur_pos;
  6046. int i, j;
  6047. int chapter_track;
  6048. for (j = 0; j < mov->nb_chapter_tracks; j++) {
  6049. chapter_track = mov->chapter_tracks[j];
  6050. st = NULL;
  6051. for (i = 0; i < s->nb_streams; i++)
  6052. if (s->streams[i]->id == chapter_track) {
  6053. st = s->streams[i];
  6054. break;
  6055. }
  6056. if (!st) {
  6057. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  6058. continue;
  6059. }
  6060. sc = st->priv_data;
  6061. cur_pos = avio_tell(sc->pb);
  6062. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  6063. st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS;
  6064. if (st->nb_index_entries) {
  6065. // Retrieve the first frame, if possible
  6066. AVPacket pkt;
  6067. AVIndexEntry *sample = &st->index_entries[0];
  6068. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  6069. av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
  6070. goto finish;
  6071. }
  6072. if (av_get_packet(sc->pb, &pkt, sample->size) < 0)
  6073. goto finish;
  6074. st->attached_pic = pkt;
  6075. st->attached_pic.stream_index = st->index;
  6076. st->attached_pic.flags |= AV_PKT_FLAG_KEY;
  6077. }
  6078. } else {
  6079. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  6080. st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
  6081. st->discard = AVDISCARD_ALL;
  6082. for (i = 0; i < st->nb_index_entries; i++) {
  6083. AVIndexEntry *sample = &st->index_entries[i];
  6084. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  6085. uint8_t *title;
  6086. uint16_t ch;
  6087. int len, title_len;
  6088. if (end < sample->timestamp) {
  6089. av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
  6090. end = AV_NOPTS_VALUE;
  6091. }
  6092. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  6093. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  6094. goto finish;
  6095. }
  6096. // the first two bytes are the length of the title
  6097. len = avio_rb16(sc->pb);
  6098. if (len > sample->size-2)
  6099. continue;
  6100. title_len = 2*len + 1;
  6101. if (!(title = av_mallocz(title_len)))
  6102. goto finish;
  6103. // The samples could theoretically be in any encoding if there's an encd
  6104. // atom following, but in practice are only utf-8 or utf-16, distinguished
  6105. // instead by the presence of a BOM
  6106. if (!len) {
  6107. title[0] = 0;
  6108. } else {
  6109. ch = avio_rb16(sc->pb);
  6110. if (ch == 0xfeff)
  6111. avio_get_str16be(sc->pb, len, title, title_len);
  6112. else if (ch == 0xfffe)
  6113. avio_get_str16le(sc->pb, len, title, title_len);
  6114. else {
  6115. AV_WB16(title, ch);
  6116. if (len == 1 || len == 2)
  6117. title[len] = 0;
  6118. else
  6119. avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
  6120. }
  6121. }
  6122. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  6123. av_freep(&title);
  6124. }
  6125. }
  6126. finish:
  6127. avio_seek(sc->pb, cur_pos, SEEK_SET);
  6128. }
  6129. }
  6130. static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
  6131. uint32_t value, int flags)
  6132. {
  6133. AVTimecode tc;
  6134. char buf[AV_TIMECODE_STR_SIZE];
  6135. AVRational rate = st->avg_frame_rate;
  6136. int ret = av_timecode_init(&tc, rate, flags, 0, s);
  6137. if (ret < 0)
  6138. return ret;
  6139. av_dict_set(&st->metadata, "timecode",
  6140. av_timecode_make_string(&tc, buf, value), 0);
  6141. return 0;
  6142. }
  6143. static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
  6144. {
  6145. MOVStreamContext *sc = st->priv_data;
  6146. char buf[AV_TIMECODE_STR_SIZE];
  6147. int64_t cur_pos = avio_tell(sc->pb);
  6148. int hh, mm, ss, ff, drop;
  6149. if (!st->nb_index_entries)
  6150. return -1;
  6151. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  6152. avio_skip(s->pb, 13);
  6153. hh = avio_r8(s->pb);
  6154. mm = avio_r8(s->pb);
  6155. ss = avio_r8(s->pb);
  6156. drop = avio_r8(s->pb);
  6157. ff = avio_r8(s->pb);
  6158. snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
  6159. hh, mm, ss, drop ? ';' : ':', ff);
  6160. av_dict_set(&st->metadata, "timecode", buf, 0);
  6161. avio_seek(sc->pb, cur_pos, SEEK_SET);
  6162. return 0;
  6163. }
  6164. static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
  6165. {
  6166. MOVStreamContext *sc = st->priv_data;
  6167. int flags = 0;
  6168. int64_t cur_pos = avio_tell(sc->pb);
  6169. uint32_t value;
  6170. if (!st->nb_index_entries)
  6171. return -1;
  6172. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  6173. value = avio_rb32(s->pb);
  6174. if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
  6175. if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  6176. if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
  6177. /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
  6178. * not the case) and thus assume "frame number format" instead of QT one.
  6179. * No sample with tmcd track can be found with a QT timecode at the moment,
  6180. * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
  6181. * format). */
  6182. parse_timecode_in_framenum_format(s, st, value, flags);
  6183. avio_seek(sc->pb, cur_pos, SEEK_SET);
  6184. return 0;
  6185. }
  6186. static void mov_free_encryption_index(MOVEncryptionIndex **index) {
  6187. int i;
  6188. if (!index || !*index) return;
  6189. for (i = 0; i < (*index)->nb_encrypted_samples; i++) {
  6190. av_encryption_info_free((*index)->encrypted_samples[i]);
  6191. }
  6192. av_freep(&(*index)->encrypted_samples);
  6193. av_freep(&(*index)->auxiliary_info_sizes);
  6194. av_freep(&(*index)->auxiliary_offsets);
  6195. av_freep(index);
  6196. }
  6197. static int mov_read_close(AVFormatContext *s)
  6198. {
  6199. MOVContext *mov = s->priv_data;
  6200. int i, j;
  6201. for (i = 0; i < s->nb_streams; i++) {
  6202. AVStream *st = s->streams[i];
  6203. MOVStreamContext *sc = st->priv_data;
  6204. if (!sc)
  6205. continue;
  6206. av_freep(&sc->ctts_data);
  6207. for (j = 0; j < sc->drefs_count; j++) {
  6208. av_freep(&sc->drefs[j].path);
  6209. av_freep(&sc->drefs[j].dir);
  6210. }
  6211. av_freep(&sc->drefs);
  6212. sc->drefs_count = 0;
  6213. if (!sc->pb_is_copied)
  6214. ff_format_io_close(s, &sc->pb);
  6215. sc->pb = NULL;
  6216. av_freep(&sc->chunk_offsets);
  6217. av_freep(&sc->stsc_data);
  6218. av_freep(&sc->sample_sizes);
  6219. av_freep(&sc->keyframes);
  6220. av_freep(&sc->stts_data);
  6221. av_freep(&sc->stps_data);
  6222. av_freep(&sc->elst_data);
  6223. av_freep(&sc->rap_group);
  6224. av_freep(&sc->display_matrix);
  6225. av_freep(&sc->index_ranges);
  6226. if (sc->extradata)
  6227. for (j = 0; j < sc->stsd_count; j++)
  6228. av_free(sc->extradata[j]);
  6229. av_freep(&sc->extradata);
  6230. av_freep(&sc->extradata_size);
  6231. mov_free_encryption_index(&sc->cenc.encryption_index);
  6232. av_encryption_info_free(sc->cenc.default_encrypted_sample);
  6233. av_aes_ctr_free(sc->cenc.aes_ctr);
  6234. av_freep(&sc->stereo3d);
  6235. av_freep(&sc->spherical);
  6236. av_freep(&sc->mastering);
  6237. av_freep(&sc->coll);
  6238. }
  6239. if (mov->dv_demux) {
  6240. avformat_free_context(mov->dv_fctx);
  6241. mov->dv_fctx = NULL;
  6242. }
  6243. if (mov->meta_keys) {
  6244. for (i = 1; i < mov->meta_keys_count; i++) {
  6245. av_freep(&mov->meta_keys[i]);
  6246. }
  6247. av_freep(&mov->meta_keys);
  6248. }
  6249. av_freep(&mov->trex_data);
  6250. av_freep(&mov->bitrates);
  6251. for (i = 0; i < mov->frag_index.nb_items; i++) {
  6252. MOVFragmentStreamInfo *frag = mov->frag_index.item[i].stream_info;
  6253. for (j = 0; j < mov->frag_index.item[i].nb_stream_info; j++) {
  6254. mov_free_encryption_index(&frag[j].encryption_index);
  6255. }
  6256. av_freep(&mov->frag_index.item[i].stream_info);
  6257. }
  6258. av_freep(&mov->frag_index.item);
  6259. av_freep(&mov->aes_decrypt);
  6260. av_freep(&mov->chapter_tracks);
  6261. return 0;
  6262. }
  6263. static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
  6264. {
  6265. int i;
  6266. for (i = 0; i < s->nb_streams; i++) {
  6267. AVStream *st = s->streams[i];
  6268. MOVStreamContext *sc = st->priv_data;
  6269. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  6270. sc->timecode_track == tmcd_id)
  6271. return 1;
  6272. }
  6273. return 0;
  6274. }
  6275. /* look for a tmcd track not referenced by any video track, and export it globally */
  6276. static void export_orphan_timecode(AVFormatContext *s)
  6277. {
  6278. int i;
  6279. for (i = 0; i < s->nb_streams; i++) {
  6280. AVStream *st = s->streams[i];
  6281. if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
  6282. !tmcd_is_referenced(s, i + 1)) {
  6283. AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
  6284. if (tcr) {
  6285. av_dict_set(&s->metadata, "timecode", tcr->value, 0);
  6286. break;
  6287. }
  6288. }
  6289. }
  6290. }
  6291. static int read_tfra(MOVContext *mov, AVIOContext *f)
  6292. {
  6293. int version, fieldlength, i, j;
  6294. int64_t pos = avio_tell(f);
  6295. uint32_t size = avio_rb32(f);
  6296. unsigned track_id, item_count;
  6297. if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
  6298. return 1;
  6299. }
  6300. av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
  6301. version = avio_r8(f);
  6302. avio_rb24(f);
  6303. track_id = avio_rb32(f);
  6304. fieldlength = avio_rb32(f);
  6305. item_count = avio_rb32(f);
  6306. for (i = 0; i < item_count; i++) {
  6307. int64_t time, offset;
  6308. int index;
  6309. MOVFragmentStreamInfo * frag_stream_info;
  6310. if (avio_feof(f)) {
  6311. return AVERROR_INVALIDDATA;
  6312. }
  6313. if (version == 1) {
  6314. time = avio_rb64(f);
  6315. offset = avio_rb64(f);
  6316. } else {
  6317. time = avio_rb32(f);
  6318. offset = avio_rb32(f);
  6319. }
  6320. // The first sample of each stream in a fragment is always a random
  6321. // access sample. So it's entry in the tfra can be used as the
  6322. // initial PTS of the fragment.
  6323. index = update_frag_index(mov, offset);
  6324. frag_stream_info = get_frag_stream_info(&mov->frag_index, index, track_id);
  6325. if (frag_stream_info &&
  6326. frag_stream_info->first_tfra_pts == AV_NOPTS_VALUE)
  6327. frag_stream_info->first_tfra_pts = time;
  6328. for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
  6329. avio_r8(f);
  6330. for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
  6331. avio_r8(f);
  6332. for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
  6333. avio_r8(f);
  6334. }
  6335. avio_seek(f, pos + size, SEEK_SET);
  6336. return 0;
  6337. }
  6338. static int mov_read_mfra(MOVContext *c, AVIOContext *f)
  6339. {
  6340. int64_t stream_size = avio_size(f);
  6341. int64_t original_pos = avio_tell(f);
  6342. int64_t seek_ret;
  6343. int32_t mfra_size;
  6344. int ret = -1;
  6345. if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
  6346. ret = seek_ret;
  6347. goto fail;
  6348. }
  6349. mfra_size = avio_rb32(f);
  6350. if (mfra_size < 0 || mfra_size > stream_size) {
  6351. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
  6352. goto fail;
  6353. }
  6354. if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
  6355. ret = seek_ret;
  6356. goto fail;
  6357. }
  6358. if (avio_rb32(f) != mfra_size) {
  6359. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
  6360. goto fail;
  6361. }
  6362. if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
  6363. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
  6364. goto fail;
  6365. }
  6366. av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
  6367. do {
  6368. ret = read_tfra(c, f);
  6369. if (ret < 0)
  6370. goto fail;
  6371. } while (!ret);
  6372. ret = 0;
  6373. fail:
  6374. seek_ret = avio_seek(f, original_pos, SEEK_SET);
  6375. if (seek_ret < 0) {
  6376. av_log(c->fc, AV_LOG_ERROR,
  6377. "failed to seek back after looking for mfra\n");
  6378. ret = seek_ret;
  6379. }
  6380. return ret;
  6381. }
  6382. static int mov_read_header(AVFormatContext *s)
  6383. {
  6384. MOVContext *mov = s->priv_data;
  6385. AVIOContext *pb = s->pb;
  6386. int j, err;
  6387. MOVAtom atom = { AV_RL32("root") };
  6388. int i;
  6389. if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
  6390. av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
  6391. mov->decryption_key_len, AES_CTR_KEY_SIZE);
  6392. return AVERROR(EINVAL);
  6393. }
  6394. mov->fc = s;
  6395. mov->trak_index = -1;
  6396. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  6397. if (pb->seekable & AVIO_SEEKABLE_NORMAL)
  6398. atom.size = avio_size(pb);
  6399. else
  6400. atom.size = INT64_MAX;
  6401. /* check MOV header */
  6402. do {
  6403. if (mov->moov_retry)
  6404. avio_seek(pb, 0, SEEK_SET);
  6405. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  6406. av_log(s, AV_LOG_ERROR, "error reading header\n");
  6407. mov_read_close(s);
  6408. return err;
  6409. }
  6410. } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++);
  6411. if (!mov->found_moov) {
  6412. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  6413. mov_read_close(s);
  6414. return AVERROR_INVALIDDATA;
  6415. }
  6416. av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  6417. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  6418. if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
  6419. mov_read_chapters(s);
  6420. for (i = 0; i < s->nb_streams; i++)
  6421. if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
  6422. mov_read_timecode_track(s, s->streams[i]);
  6423. } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
  6424. mov_read_rtmd_track(s, s->streams[i]);
  6425. }
  6426. }
  6427. /* copy timecode metadata from tmcd tracks to the related video streams */
  6428. for (i = 0; i < s->nb_streams; i++) {
  6429. AVStream *st = s->streams[i];
  6430. MOVStreamContext *sc = st->priv_data;
  6431. if (sc->timecode_track > 0) {
  6432. AVDictionaryEntry *tcr;
  6433. int tmcd_st_id = -1;
  6434. for (j = 0; j < s->nb_streams; j++)
  6435. if (s->streams[j]->id == sc->timecode_track)
  6436. tmcd_st_id = j;
  6437. if (tmcd_st_id < 0 || tmcd_st_id == i)
  6438. continue;
  6439. tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
  6440. if (tcr)
  6441. av_dict_set(&st->metadata, "timecode", tcr->value, 0);
  6442. }
  6443. }
  6444. export_orphan_timecode(s);
  6445. for (i = 0; i < s->nb_streams; i++) {
  6446. AVStream *st = s->streams[i];
  6447. MOVStreamContext *sc = st->priv_data;
  6448. fix_timescale(mov, sc);
  6449. if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
  6450. st->skip_samples = sc->start_pad;
  6451. }
  6452. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
  6453. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  6454. sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
  6455. if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  6456. if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
  6457. st->codecpar->width = sc->width;
  6458. st->codecpar->height = sc->height;
  6459. }
  6460. if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
  6461. if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
  6462. return err;
  6463. }
  6464. }
  6465. if (mov->handbrake_version &&
  6466. mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
  6467. st->codecpar->codec_id == AV_CODEC_ID_MP3
  6468. ) {
  6469. av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
  6470. st->need_parsing = AVSTREAM_PARSE_FULL;
  6471. }
  6472. }
  6473. if (mov->trex_data) {
  6474. for (i = 0; i < s->nb_streams; i++) {
  6475. AVStream *st = s->streams[i];
  6476. MOVStreamContext *sc = st->priv_data;
  6477. if (st->duration > 0) {
  6478. if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
  6479. av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
  6480. sc->data_size, sc->time_scale);
  6481. mov_read_close(s);
  6482. return AVERROR_INVALIDDATA;
  6483. }
  6484. st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  6485. }
  6486. }
  6487. }
  6488. if (mov->use_mfra_for > 0) {
  6489. for (i = 0; i < s->nb_streams; i++) {
  6490. AVStream *st = s->streams[i];
  6491. MOVStreamContext *sc = st->priv_data;
  6492. if (sc->duration_for_fps > 0) {
  6493. if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
  6494. av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
  6495. sc->data_size, sc->time_scale);
  6496. mov_read_close(s);
  6497. return AVERROR_INVALIDDATA;
  6498. }
  6499. st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
  6500. sc->duration_for_fps;
  6501. }
  6502. }
  6503. }
  6504. for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
  6505. if (mov->bitrates[i]) {
  6506. s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
  6507. }
  6508. }
  6509. ff_rfps_calculate(s);
  6510. for (i = 0; i < s->nb_streams; i++) {
  6511. AVStream *st = s->streams[i];
  6512. MOVStreamContext *sc = st->priv_data;
  6513. switch (st->codecpar->codec_type) {
  6514. case AVMEDIA_TYPE_AUDIO:
  6515. err = ff_replaygain_export(st, s->metadata);
  6516. if (err < 0) {
  6517. mov_read_close(s);
  6518. return err;
  6519. }
  6520. break;
  6521. case AVMEDIA_TYPE_VIDEO:
  6522. if (sc->display_matrix) {
  6523. err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, (uint8_t*)sc->display_matrix,
  6524. sizeof(int32_t) * 9);
  6525. if (err < 0)
  6526. return err;
  6527. sc->display_matrix = NULL;
  6528. }
  6529. if (sc->stereo3d) {
  6530. err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D,
  6531. (uint8_t *)sc->stereo3d,
  6532. sizeof(*sc->stereo3d));
  6533. if (err < 0)
  6534. return err;
  6535. sc->stereo3d = NULL;
  6536. }
  6537. if (sc->spherical) {
  6538. err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL,
  6539. (uint8_t *)sc->spherical,
  6540. sc->spherical_size);
  6541. if (err < 0)
  6542. return err;
  6543. sc->spherical = NULL;
  6544. }
  6545. if (sc->mastering) {
  6546. err = av_stream_add_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  6547. (uint8_t *)sc->mastering,
  6548. sizeof(*sc->mastering));
  6549. if (err < 0)
  6550. return err;
  6551. sc->mastering = NULL;
  6552. }
  6553. if (sc->coll) {
  6554. err = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
  6555. (uint8_t *)sc->coll,
  6556. sc->coll_size);
  6557. if (err < 0)
  6558. return err;
  6559. sc->coll = NULL;
  6560. }
  6561. break;
  6562. }
  6563. }
  6564. ff_configure_buffers_for_index(s, AV_TIME_BASE);
  6565. for (i = 0; i < mov->frag_index.nb_items; i++)
  6566. if (mov->frag_index.item[i].moof_offset <= mov->fragment.moof_offset)
  6567. mov->frag_index.item[i].headers_read = 1;
  6568. return 0;
  6569. }
  6570. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  6571. {
  6572. AVIndexEntry *sample = NULL;
  6573. int64_t best_dts = INT64_MAX;
  6574. int i;
  6575. for (i = 0; i < s->nb_streams; i++) {
  6576. AVStream *avst = s->streams[i];
  6577. MOVStreamContext *msc = avst->priv_data;
  6578. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  6579. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  6580. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  6581. av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  6582. if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
  6583. ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
  6584. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  6585. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  6586. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  6587. sample = current_sample;
  6588. best_dts = dts;
  6589. *st = avst;
  6590. }
  6591. }
  6592. }
  6593. return sample;
  6594. }
  6595. static int should_retry(AVIOContext *pb, int error_code) {
  6596. if (error_code == AVERROR_EOF || avio_feof(pb))
  6597. return 0;
  6598. return 1;
  6599. }
  6600. static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
  6601. {
  6602. int ret;
  6603. MOVContext *mov = s->priv_data;
  6604. if (index >= 0 && index < mov->frag_index.nb_items)
  6605. target = mov->frag_index.item[index].moof_offset;
  6606. if (avio_seek(s->pb, target, SEEK_SET) != target) {
  6607. av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
  6608. return AVERROR_INVALIDDATA;
  6609. }
  6610. mov->next_root_atom = 0;
  6611. if (index < 0 || index >= mov->frag_index.nb_items)
  6612. index = search_frag_moof_offset(&mov->frag_index, target);
  6613. if (index < mov->frag_index.nb_items) {
  6614. if (index + 1 < mov->frag_index.nb_items)
  6615. mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
  6616. if (mov->frag_index.item[index].headers_read)
  6617. return 0;
  6618. mov->frag_index.item[index].headers_read = 1;
  6619. }
  6620. mov->found_mdat = 0;
  6621. ret = mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX });
  6622. if (ret < 0)
  6623. return ret;
  6624. if (avio_feof(s->pb))
  6625. return AVERROR_EOF;
  6626. av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  6627. return 1;
  6628. }
  6629. static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
  6630. {
  6631. uint8_t *side, *extradata;
  6632. int extradata_size;
  6633. /* Save the current index. */
  6634. sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
  6635. /* Notify the decoder that extradata changed. */
  6636. extradata_size = sc->extradata_size[sc->last_stsd_index];
  6637. extradata = sc->extradata[sc->last_stsd_index];
  6638. if (extradata_size > 0 && extradata) {
  6639. side = av_packet_new_side_data(pkt,
  6640. AV_PKT_DATA_NEW_EXTRADATA,
  6641. extradata_size);
  6642. if (!side)
  6643. return AVERROR(ENOMEM);
  6644. memcpy(side, extradata, extradata_size);
  6645. }
  6646. return 0;
  6647. }
  6648. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  6649. {
  6650. MOVContext *mov = s->priv_data;
  6651. MOVStreamContext *sc;
  6652. AVIndexEntry *sample;
  6653. AVStream *st = NULL;
  6654. int64_t current_index;
  6655. int ret;
  6656. mov->fc = s;
  6657. retry:
  6658. sample = mov_find_next_sample(s, &st);
  6659. if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
  6660. if (!mov->next_root_atom)
  6661. return AVERROR_EOF;
  6662. if ((ret = mov_switch_root(s, mov->next_root_atom, -1)) < 0)
  6663. return ret;
  6664. goto retry;
  6665. }
  6666. sc = st->priv_data;
  6667. /* must be done just before reading, to avoid infinite loop on sample */
  6668. current_index = sc->current_index;
  6669. mov_current_sample_inc(sc);
  6670. if (mov->next_root_atom) {
  6671. sample->pos = FFMIN(sample->pos, mov->next_root_atom);
  6672. sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
  6673. }
  6674. if (st->discard != AVDISCARD_ALL) {
  6675. int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
  6676. if (ret64 != sample->pos) {
  6677. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  6678. sc->ffindex, sample->pos);
  6679. if (should_retry(sc->pb, ret64)) {
  6680. mov_current_sample_dec(sc);
  6681. }
  6682. return AVERROR_INVALIDDATA;
  6683. }
  6684. if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
  6685. av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
  6686. goto retry;
  6687. }
  6688. ret = av_get_packet(sc->pb, pkt, sample->size);
  6689. if (ret < 0) {
  6690. if (should_retry(sc->pb, ret)) {
  6691. mov_current_sample_dec(sc);
  6692. }
  6693. return ret;
  6694. }
  6695. if (sc->has_palette) {
  6696. uint8_t *pal;
  6697. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  6698. if (!pal) {
  6699. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  6700. } else {
  6701. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  6702. sc->has_palette = 0;
  6703. }
  6704. }
  6705. #if CONFIG_DV_DEMUXER
  6706. if (mov->dv_demux && sc->dv_audio_container) {
  6707. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  6708. av_freep(&pkt->data);
  6709. pkt->size = 0;
  6710. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  6711. if (ret < 0)
  6712. return ret;
  6713. }
  6714. #endif
  6715. if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
  6716. if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
  6717. st->need_parsing = AVSTREAM_PARSE_FULL;
  6718. }
  6719. }
  6720. pkt->stream_index = sc->ffindex;
  6721. pkt->dts = sample->timestamp;
  6722. if (sample->flags & AVINDEX_DISCARD_FRAME) {
  6723. pkt->flags |= AV_PKT_FLAG_DISCARD;
  6724. }
  6725. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  6726. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  6727. /* update ctts context */
  6728. sc->ctts_sample++;
  6729. if (sc->ctts_index < sc->ctts_count &&
  6730. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  6731. sc->ctts_index++;
  6732. sc->ctts_sample = 0;
  6733. }
  6734. } else {
  6735. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  6736. st->index_entries[sc->current_sample].timestamp : st->duration;
  6737. if (next_dts >= pkt->dts)
  6738. pkt->duration = next_dts - pkt->dts;
  6739. pkt->pts = pkt->dts;
  6740. }
  6741. if (st->discard == AVDISCARD_ALL)
  6742. goto retry;
  6743. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  6744. pkt->pos = sample->pos;
  6745. /* Multiple stsd handling. */
  6746. if (sc->stsc_data) {
  6747. /* Keep track of the stsc index for the given sample, then check
  6748. * if the stsd index is different from the last used one. */
  6749. sc->stsc_sample++;
  6750. if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
  6751. mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
  6752. sc->stsc_index++;
  6753. sc->stsc_sample = 0;
  6754. /* Do not check indexes after a switch. */
  6755. } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
  6756. sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
  6757. sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
  6758. ret = mov_change_extradata(sc, pkt);
  6759. if (ret < 0)
  6760. return ret;
  6761. }
  6762. }
  6763. if (mov->aax_mode)
  6764. aax_filter(pkt->data, pkt->size, mov);
  6765. ret = cenc_filter(mov, sc, pkt, current_index);
  6766. if (ret < 0)
  6767. return ret;
  6768. return 0;
  6769. }
  6770. static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
  6771. {
  6772. MOVContext *mov = s->priv_data;
  6773. int index;
  6774. if (!mov->frag_index.complete)
  6775. return 0;
  6776. index = search_frag_timestamp(&mov->frag_index, st, timestamp);
  6777. if (index < 0)
  6778. index = 0;
  6779. if (!mov->frag_index.item[index].headers_read)
  6780. return mov_switch_root(s, -1, index);
  6781. if (index + 1 < mov->frag_index.nb_items)
  6782. mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
  6783. return 0;
  6784. }
  6785. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  6786. {
  6787. MOVStreamContext *sc = st->priv_data;
  6788. int sample, time_sample, ret;
  6789. unsigned int i;
  6790. // Here we consider timestamp to be PTS, hence try to offset it so that we
  6791. // can search over the DTS timeline.
  6792. timestamp -= (sc->min_corrected_pts + sc->dts_shift);
  6793. ret = mov_seek_fragment(s, st, timestamp);
  6794. if (ret < 0)
  6795. return ret;
  6796. sample = av_index_search_timestamp(st, timestamp, flags);
  6797. av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  6798. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  6799. sample = 0;
  6800. if (sample < 0) /* not sure what to do */
  6801. return AVERROR_INVALIDDATA;
  6802. mov_current_sample_set(sc, sample);
  6803. av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
  6804. /* adjust ctts index */
  6805. if (sc->ctts_data) {
  6806. time_sample = 0;
  6807. for (i = 0; i < sc->ctts_count; i++) {
  6808. int next = time_sample + sc->ctts_data[i].count;
  6809. if (next > sc->current_sample) {
  6810. sc->ctts_index = i;
  6811. sc->ctts_sample = sc->current_sample - time_sample;
  6812. break;
  6813. }
  6814. time_sample = next;
  6815. }
  6816. }
  6817. /* adjust stsd index */
  6818. time_sample = 0;
  6819. for (i = 0; i < sc->stsc_count; i++) {
  6820. int64_t next = time_sample + mov_get_stsc_samples(sc, i);
  6821. if (next > sc->current_sample) {
  6822. sc->stsc_index = i;
  6823. sc->stsc_sample = sc->current_sample - time_sample;
  6824. break;
  6825. }
  6826. av_assert0(next == (int)next);
  6827. time_sample = next;
  6828. }
  6829. return sample;
  6830. }
  6831. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  6832. {
  6833. MOVContext *mc = s->priv_data;
  6834. AVStream *st;
  6835. int sample;
  6836. int i;
  6837. if (stream_index >= s->nb_streams)
  6838. return AVERROR_INVALIDDATA;
  6839. st = s->streams[stream_index];
  6840. sample = mov_seek_stream(s, st, sample_time, flags);
  6841. if (sample < 0)
  6842. return sample;
  6843. if (mc->seek_individually) {
  6844. /* adjust seek timestamp to found sample timestamp */
  6845. int64_t seek_timestamp = st->index_entries[sample].timestamp;
  6846. for (i = 0; i < s->nb_streams; i++) {
  6847. int64_t timestamp;
  6848. MOVStreamContext *sc = s->streams[i]->priv_data;
  6849. st = s->streams[i];
  6850. st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
  6851. if (stream_index == i)
  6852. continue;
  6853. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  6854. mov_seek_stream(s, st, timestamp, flags);
  6855. }
  6856. } else {
  6857. for (i = 0; i < s->nb_streams; i++) {
  6858. MOVStreamContext *sc;
  6859. st = s->streams[i];
  6860. sc = st->priv_data;
  6861. mov_current_sample_set(sc, 0);
  6862. }
  6863. while (1) {
  6864. MOVStreamContext *sc;
  6865. AVIndexEntry *entry = mov_find_next_sample(s, &st);
  6866. if (!entry)
  6867. return AVERROR_INVALIDDATA;
  6868. sc = st->priv_data;
  6869. if (sc->ffindex == stream_index && sc->current_sample == sample)
  6870. break;
  6871. mov_current_sample_inc(sc);
  6872. }
  6873. }
  6874. return 0;
  6875. }
  6876. #define OFFSET(x) offsetof(MOVContext, x)
  6877. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  6878. static const AVOption mov_options[] = {
  6879. {"use_absolute_path",
  6880. "allow using absolute path when opening alias, this is a possible security issue",
  6881. OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
  6882. 0, 1, FLAGS},
  6883. {"seek_streams_individually",
  6884. "Seek each stream individually to the to the closest point",
  6885. OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
  6886. 0, 1, FLAGS},
  6887. {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
  6888. 0, 1, FLAGS},
  6889. {"advanced_editlist",
  6890. "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.",
  6891. OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1},
  6892. 0, 1, FLAGS},
  6893. {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
  6894. 0, 1, FLAGS},
  6895. {"use_mfra_for",
  6896. "use mfra for fragment timestamps",
  6897. OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
  6898. -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
  6899. "use_mfra_for"},
  6900. {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
  6901. FLAGS, "use_mfra_for" },
  6902. {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
  6903. FLAGS, "use_mfra_for" },
  6904. {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
  6905. FLAGS, "use_mfra_for" },
  6906. { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
  6907. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  6908. { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
  6909. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  6910. { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
  6911. AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  6912. { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
  6913. "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
  6914. AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
  6915. .flags = AV_OPT_FLAG_DECODING_PARAM },
  6916. { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  6917. { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
  6918. {.i64 = 0}, 0, 1, FLAGS },
  6919. { NULL },
  6920. };
  6921. static const AVClass mov_class = {
  6922. .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
  6923. .item_name = av_default_item_name,
  6924. .option = mov_options,
  6925. .version = LIBAVUTIL_VERSION_INT,
  6926. };
  6927. AVInputFormat ff_mov_demuxer = {
  6928. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  6929. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  6930. .priv_class = &mov_class,
  6931. .priv_data_size = sizeof(MOVContext),
  6932. .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
  6933. .read_probe = mov_probe,
  6934. .read_header = mov_read_header,
  6935. .read_packet = mov_read_packet,
  6936. .read_close = mov_read_close,
  6937. .read_seek = mov_read_seek,
  6938. .flags = AVFMT_NO_BYTE_SEEK,
  6939. };