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.

6058 lines
206KB

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