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.

6383 lines
216KB

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