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.

4177 lines
138KB

  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. //#define MOV_EXPORT_ALL_METADATA
  29. #include "libavutil/attributes.h"
  30. #include "libavutil/channel_layout.h"
  31. #include "libavutil/display.h"
  32. #include "libavutil/intreadwrite.h"
  33. #include "libavutil/intfloat.h"
  34. #include "libavutil/mathematics.h"
  35. #include "libavutil/avstring.h"
  36. #include "libavutil/dict.h"
  37. #include "libavutil/opt.h"
  38. #include "libavutil/timecode.h"
  39. #include "libavcodec/ac3tab.h"
  40. #include "avformat.h"
  41. #include "internal.h"
  42. #include "avio_internal.h"
  43. #include "riff.h"
  44. #include "isom.h"
  45. #include "libavcodec/get_bits.h"
  46. #include "id3v1.h"
  47. #include "mov_chan.h"
  48. #include "replaygain.h"
  49. #if CONFIG_ZLIB
  50. #include <zlib.h>
  51. #endif
  52. #include "qtpalette.h"
  53. #undef NDEBUG
  54. #include <assert.h>
  55. /* those functions parse an atom */
  56. /* links atom IDs to parse functions */
  57. typedef struct MOVParseTableEntry {
  58. uint32_t type;
  59. int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
  60. } MOVParseTableEntry;
  61. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
  62. static int mov_read_mfra(MOVContext *c, AVIOContext *f);
  63. static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
  64. unsigned len, const char *key)
  65. {
  66. char buf[16];
  67. short current, total = 0;
  68. avio_rb16(pb); // unknown
  69. current = avio_rb16(pb);
  70. if (len >= 6)
  71. total = avio_rb16(pb);
  72. if (!total)
  73. snprintf(buf, sizeof(buf), "%d", current);
  74. else
  75. snprintf(buf, sizeof(buf), "%d/%d", current, total);
  76. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  77. av_dict_set(&c->fc->metadata, key, buf, 0);
  78. return 0;
  79. }
  80. static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
  81. unsigned len, const char *key)
  82. {
  83. /* bypass padding bytes */
  84. avio_r8(pb);
  85. avio_r8(pb);
  86. avio_r8(pb);
  87. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  88. av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  89. return 0;
  90. }
  91. static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
  92. unsigned len, const char *key)
  93. {
  94. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  95. av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  96. return 0;
  97. }
  98. static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
  99. unsigned len, const char *key)
  100. {
  101. short genre;
  102. avio_r8(pb); // unknown
  103. genre = avio_r8(pb);
  104. if (genre < 1 || genre > ID3v1_GENRE_MAX)
  105. return 0;
  106. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  107. av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
  108. return 0;
  109. }
  110. static const uint32_t mac_to_unicode[128] = {
  111. 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
  112. 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
  113. 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
  114. 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
  115. 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
  116. 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
  117. 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
  118. 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
  119. 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
  120. 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
  121. 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
  122. 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
  123. 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
  124. 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
  125. 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
  126. 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
  127. };
  128. static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
  129. char *dst, int dstlen)
  130. {
  131. char *p = dst;
  132. char *end = dst+dstlen-1;
  133. int i;
  134. for (i = 0; i < len; i++) {
  135. uint8_t t, c = avio_r8(pb);
  136. if (c < 0x80 && p < end)
  137. *p++ = c;
  138. else if (p < end)
  139. PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
  140. }
  141. *p = 0;
  142. return p - dst;
  143. }
  144. static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
  145. {
  146. AVPacket pkt;
  147. AVStream *st;
  148. MOVStreamContext *sc;
  149. enum AVCodecID id;
  150. int ret;
  151. switch (type) {
  152. case 0xd: id = AV_CODEC_ID_MJPEG; break;
  153. case 0xe: id = AV_CODEC_ID_PNG; break;
  154. case 0x1b: id = AV_CODEC_ID_BMP; break;
  155. default:
  156. av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
  157. avio_skip(pb, len);
  158. return 0;
  159. }
  160. st = avformat_new_stream(c->fc, NULL);
  161. if (!st)
  162. return AVERROR(ENOMEM);
  163. sc = av_mallocz(sizeof(*sc));
  164. if (!sc)
  165. return AVERROR(ENOMEM);
  166. st->priv_data = sc;
  167. ret = av_get_packet(pb, &pkt, len);
  168. if (ret < 0)
  169. return ret;
  170. st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
  171. st->attached_pic = pkt;
  172. st->attached_pic.stream_index = st->index;
  173. st->attached_pic.flags |= AV_PKT_FLAG_KEY;
  174. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  175. st->codec->codec_id = id;
  176. return 0;
  177. }
  178. static int mov_metadata_raw(MOVContext *c, AVIOContext *pb,
  179. unsigned len, const char *key)
  180. {
  181. char *value = av_malloc(len + 1);
  182. if (!value)
  183. return AVERROR(ENOMEM);
  184. avio_read(pb, value, len);
  185. value[len] = 0;
  186. return av_dict_set(&c->fc->metadata, key, value, AV_DICT_DONT_STRDUP_VAL);
  187. }
  188. static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
  189. {
  190. char language[4] = { 0 };
  191. char buf[100];
  192. uint16_t langcode = 0;
  193. double longitude, latitude;
  194. const char *key = "location";
  195. if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4)
  196. return AVERROR_INVALIDDATA;
  197. avio_skip(pb, 4); // version+flags
  198. langcode = avio_rb16(pb);
  199. ff_mov_lang_to_iso639(langcode, language);
  200. len -= 6;
  201. len -= avio_get_str(pb, len, buf, sizeof(buf)); // place name
  202. if (len < 1)
  203. return AVERROR_INVALIDDATA;
  204. avio_skip(pb, 1); // role
  205. len -= 1;
  206. if (len < 14)
  207. return AVERROR_INVALIDDATA;
  208. longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  209. latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  210. // Try to output in the same format as the ?xyz field
  211. snprintf(buf, sizeof(buf), "%+08.4f%+09.4f/", latitude, longitude);
  212. if (*language && strcmp(language, "und")) {
  213. char key2[16];
  214. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  215. av_dict_set(&c->fc->metadata, key2, buf, 0);
  216. }
  217. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  218. return av_dict_set(&c->fc->metadata, key, buf, 0);
  219. }
  220. static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  221. {
  222. #ifdef MOV_EXPORT_ALL_METADATA
  223. char tmp_key[5];
  224. #endif
  225. char str[1024], key2[16], language[4] = {0};
  226. const char *key = NULL;
  227. uint16_t langcode = 0;
  228. uint32_t data_type = 0, str_size;
  229. int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
  230. switch (atom.type) {
  231. case MKTAG(0xa9,'n','a','m'): key = "title"; break;
  232. case MKTAG(0xa9,'a','u','t'):
  233. case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
  234. case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
  235. case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
  236. case MKTAG( 'c','p','i','l'): key = "compilation";
  237. parse = mov_metadata_int8_no_padding; break;
  238. case MKTAG( 'c','p','r','t'):
  239. case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
  240. case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
  241. case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
  242. case MKTAG(0xa9,'c','m','t'):
  243. case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
  244. case MKTAG(0xa9,'a','l','b'): key = "album"; break;
  245. case MKTAG(0xa9,'d','a','y'): key = "date"; break;
  246. case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
  247. case MKTAG( 'g','n','r','e'): key = "genre";
  248. parse = mov_metadata_gnre; break;
  249. case MKTAG(0xa9,'t','o','o'):
  250. case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
  251. case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
  252. case MKTAG(0xa9,'m','a','k'): key = "make"; break;
  253. case MKTAG(0xa9,'m','o','d'): key = "model"; break;
  254. case MKTAG(0xa9,'x','y','z'): key = "location"; break;
  255. case MKTAG( 'd','e','s','c'): key = "description";break;
  256. case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
  257. case MKTAG( 't','v','s','h'): key = "show"; break;
  258. case MKTAG( 't','v','e','n'): key = "episode_id";break;
  259. case MKTAG( 't','v','n','n'): key = "network"; break;
  260. case MKTAG( 't','r','k','n'): key = "track";
  261. parse = mov_metadata_track_or_disc_number; break;
  262. case MKTAG( 'd','i','s','k'): key = "disc";
  263. parse = mov_metadata_track_or_disc_number; break;
  264. case MKTAG( 't','v','e','s'): key = "episode_sort";
  265. parse = mov_metadata_int8_bypass_padding; break;
  266. case MKTAG( 't','v','s','n'): key = "season_number";
  267. parse = mov_metadata_int8_bypass_padding; break;
  268. case MKTAG( 's','t','i','k'): key = "media_type";
  269. parse = mov_metadata_int8_no_padding; break;
  270. case MKTAG( 'h','d','v','d'): key = "hd_video";
  271. parse = mov_metadata_int8_no_padding; break;
  272. case MKTAG( 'p','g','a','p'): key = "gapless_playback";
  273. parse = mov_metadata_int8_no_padding; break;
  274. case MKTAG( '@','P','R','M'):
  275. return mov_metadata_raw(c, pb, atom.size, "premiere_version");
  276. case MKTAG( '@','P','R','Q'):
  277. return mov_metadata_raw(c, pb, atom.size, "quicktime_version");
  278. case MKTAG( 'l','o','c','i'):
  279. return mov_metadata_loci(c, pb, atom.size);
  280. case MKTAG( 'X','M','P','_'):
  281. return mov_metadata_raw(c, pb, atom.size, "xmp");
  282. }
  283. if (c->itunes_metadata && atom.size > 8) {
  284. int data_size = avio_rb32(pb);
  285. int tag = avio_rl32(pb);
  286. if (tag == MKTAG('d','a','t','a')) {
  287. data_type = avio_rb32(pb); // type
  288. avio_rb32(pb); // unknown
  289. str_size = data_size - 16;
  290. atom.size -= 16;
  291. if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
  292. int ret = mov_read_covr(c, pb, data_type, str_size);
  293. if (ret < 0) {
  294. av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
  295. }
  296. return ret;
  297. }
  298. } else return 0;
  299. } else if (atom.size > 4 && key && !c->itunes_metadata) {
  300. str_size = avio_rb16(pb); // string length
  301. langcode = avio_rb16(pb);
  302. ff_mov_lang_to_iso639(langcode, language);
  303. atom.size -= 4;
  304. } else
  305. str_size = atom.size;
  306. #ifdef MOV_EXPORT_ALL_METADATA
  307. if (!key) {
  308. snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
  309. key = tmp_key;
  310. }
  311. #endif
  312. if (!key)
  313. return 0;
  314. if (atom.size < 0)
  315. return AVERROR_INVALIDDATA;
  316. str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
  317. if (parse)
  318. parse(c, pb, str_size, key);
  319. else {
  320. if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
  321. mov_read_mac_string(c, pb, str_size, str, sizeof(str));
  322. } else {
  323. int ret = avio_read(pb, str, str_size);
  324. if (ret != str_size)
  325. return ret < 0 ? ret : AVERROR_INVALIDDATA;
  326. str[str_size] = 0;
  327. }
  328. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  329. av_dict_set(&c->fc->metadata, key, str, 0);
  330. if (*language && strcmp(language, "und")) {
  331. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  332. av_dict_set(&c->fc->metadata, key2, str, 0);
  333. }
  334. }
  335. av_dlog(c->fc, "lang \"%3s\" ", language);
  336. av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
  337. key, str, (char*)&atom.type, str_size, atom.size);
  338. return 0;
  339. }
  340. static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  341. {
  342. int64_t start;
  343. int i, nb_chapters, str_len, version;
  344. char str[256+1];
  345. if ((atom.size -= 5) < 0)
  346. return 0;
  347. version = avio_r8(pb);
  348. avio_rb24(pb);
  349. if (version)
  350. avio_rb32(pb); // ???
  351. nb_chapters = avio_r8(pb);
  352. for (i = 0; i < nb_chapters; i++) {
  353. if (atom.size < 9)
  354. return 0;
  355. start = avio_rb64(pb);
  356. str_len = avio_r8(pb);
  357. if ((atom.size -= 9+str_len) < 0)
  358. return 0;
  359. avio_read(pb, str, str_len);
  360. str[str_len] = 0;
  361. avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
  362. }
  363. return 0;
  364. }
  365. #define MIN_DATA_ENTRY_BOX_SIZE 12
  366. static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  367. {
  368. AVStream *st;
  369. MOVStreamContext *sc;
  370. int entries, i, j;
  371. if (c->fc->nb_streams < 1)
  372. return 0;
  373. st = c->fc->streams[c->fc->nb_streams-1];
  374. sc = st->priv_data;
  375. avio_rb32(pb); // version + flags
  376. entries = avio_rb32(pb);
  377. if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
  378. entries >= UINT_MAX / sizeof(*sc->drefs))
  379. return AVERROR_INVALIDDATA;
  380. av_free(sc->drefs);
  381. sc->drefs_count = 0;
  382. sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
  383. if (!sc->drefs)
  384. return AVERROR(ENOMEM);
  385. sc->drefs_count = entries;
  386. for (i = 0; i < sc->drefs_count; i++) {
  387. MOVDref *dref = &sc->drefs[i];
  388. uint32_t size = avio_rb32(pb);
  389. int64_t next = avio_tell(pb) + size - 4;
  390. if (size < 12)
  391. return AVERROR_INVALIDDATA;
  392. dref->type = avio_rl32(pb);
  393. avio_rb32(pb); // version + flags
  394. av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
  395. if (dref->type == MKTAG('a','l','i','s') && size > 150) {
  396. /* macintosh alias record */
  397. uint16_t volume_len, len;
  398. int16_t type;
  399. avio_skip(pb, 10);
  400. volume_len = avio_r8(pb);
  401. volume_len = FFMIN(volume_len, 27);
  402. avio_read(pb, dref->volume, 27);
  403. dref->volume[volume_len] = 0;
  404. av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
  405. avio_skip(pb, 12);
  406. len = avio_r8(pb);
  407. len = FFMIN(len, 63);
  408. avio_read(pb, dref->filename, 63);
  409. dref->filename[len] = 0;
  410. av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
  411. avio_skip(pb, 16);
  412. /* read next level up_from_alias/down_to_target */
  413. dref->nlvl_from = avio_rb16(pb);
  414. dref->nlvl_to = avio_rb16(pb);
  415. av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
  416. dref->nlvl_from, dref->nlvl_to);
  417. avio_skip(pb, 16);
  418. for (type = 0; type != -1 && avio_tell(pb) < next; ) {
  419. if(avio_feof(pb))
  420. return AVERROR_EOF;
  421. type = avio_rb16(pb);
  422. len = avio_rb16(pb);
  423. av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
  424. if (len&1)
  425. len += 1;
  426. if (type == 2) { // absolute path
  427. av_free(dref->path);
  428. dref->path = av_mallocz(len+1);
  429. if (!dref->path)
  430. return AVERROR(ENOMEM);
  431. avio_read(pb, dref->path, len);
  432. if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
  433. len -= volume_len;
  434. memmove(dref->path, dref->path+volume_len, len);
  435. dref->path[len] = 0;
  436. }
  437. for (j = 0; j < len; j++)
  438. if (dref->path[j] == ':')
  439. dref->path[j] = '/';
  440. av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
  441. } else if (type == 0) { // directory name
  442. av_free(dref->dir);
  443. dref->dir = av_malloc(len+1);
  444. if (!dref->dir)
  445. return AVERROR(ENOMEM);
  446. if (avio_read(pb, dref->dir, len) != len)
  447. return AVERROR_INVALIDDATA;
  448. dref->dir[len] = 0;
  449. for (j = 0; j < len; j++)
  450. if (dref->dir[j] == ':')
  451. dref->dir[j] = '/';
  452. av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
  453. } else
  454. avio_skip(pb, len);
  455. }
  456. }
  457. avio_seek(pb, next, SEEK_SET);
  458. }
  459. return 0;
  460. }
  461. static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  462. {
  463. AVStream *st;
  464. uint32_t type;
  465. uint32_t av_unused ctype;
  466. int title_size;
  467. char *title_str;
  468. if (c->fc->nb_streams < 1) // meta before first trak
  469. return 0;
  470. st = c->fc->streams[c->fc->nb_streams-1];
  471. avio_r8(pb); /* version */
  472. avio_rb24(pb); /* flags */
  473. /* component type */
  474. ctype = avio_rl32(pb);
  475. type = avio_rl32(pb); /* component subtype */
  476. av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
  477. av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
  478. if (type == MKTAG('v','i','d','e'))
  479. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  480. else if (type == MKTAG('s','o','u','n'))
  481. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  482. else if (type == MKTAG('m','1','a',' '))
  483. st->codec->codec_id = AV_CODEC_ID_MP2;
  484. else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
  485. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  486. avio_rb32(pb); /* component manufacture */
  487. avio_rb32(pb); /* component flags */
  488. avio_rb32(pb); /* component flags mask */
  489. title_size = atom.size - 24;
  490. if (title_size > 0) {
  491. title_str = av_malloc(title_size + 1); /* Add null terminator */
  492. if (!title_str)
  493. return AVERROR(ENOMEM);
  494. avio_read(pb, title_str, title_size);
  495. title_str[title_size] = 0;
  496. if (title_str[0])
  497. av_dict_set(&st->metadata, "handler_name", title_str +
  498. (!c->isom && title_str[0] == title_size - 1), 0);
  499. av_freep(&title_str);
  500. }
  501. return 0;
  502. }
  503. int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
  504. {
  505. AVStream *st;
  506. int tag;
  507. if (fc->nb_streams < 1)
  508. return 0;
  509. st = fc->streams[fc->nb_streams-1];
  510. avio_rb32(pb); /* version + flags */
  511. ff_mp4_read_descr(fc, pb, &tag);
  512. if (tag == MP4ESDescrTag) {
  513. ff_mp4_parse_es_descr(pb, NULL);
  514. } else
  515. avio_rb16(pb); /* ID */
  516. ff_mp4_read_descr(fc, pb, &tag);
  517. if (tag == MP4DecConfigDescrTag)
  518. ff_mp4_read_dec_config_descr(fc, st, pb);
  519. return 0;
  520. }
  521. static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  522. {
  523. return ff_mov_read_esds(c->fc, pb);
  524. }
  525. static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  526. {
  527. AVStream *st;
  528. int ac3info, acmod, lfeon, bsmod;
  529. if (c->fc->nb_streams < 1)
  530. return 0;
  531. st = c->fc->streams[c->fc->nb_streams-1];
  532. ac3info = avio_rb24(pb);
  533. bsmod = (ac3info >> 14) & 0x7;
  534. acmod = (ac3info >> 11) & 0x7;
  535. lfeon = (ac3info >> 10) & 0x1;
  536. st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
  537. st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  538. if (lfeon)
  539. st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
  540. st->codec->audio_service_type = bsmod;
  541. if (st->codec->channels > 1 && bsmod == 0x7)
  542. st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  543. return 0;
  544. }
  545. static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  546. {
  547. AVStream *st;
  548. int eac3info, acmod, lfeon, bsmod;
  549. if (c->fc->nb_streams < 1)
  550. return 0;
  551. st = c->fc->streams[c->fc->nb_streams-1];
  552. /* No need to parse fields for additional independent substreams and its
  553. * associated dependent substreams since libavcodec's E-AC-3 decoder
  554. * does not support them yet. */
  555. avio_rb16(pb); /* data_rate and num_ind_sub */
  556. eac3info = avio_rb24(pb);
  557. bsmod = (eac3info >> 12) & 0x1f;
  558. acmod = (eac3info >> 9) & 0x7;
  559. lfeon = (eac3info >> 8) & 0x1;
  560. st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  561. if (lfeon)
  562. st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
  563. st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
  564. st->codec->audio_service_type = bsmod;
  565. if (st->codec->channels > 1 && bsmod == 0x7)
  566. st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  567. return 0;
  568. }
  569. static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  570. {
  571. AVStream *st;
  572. if (c->fc->nb_streams < 1)
  573. return 0;
  574. st = c->fc->streams[c->fc->nb_streams-1];
  575. if (atom.size < 16)
  576. return 0;
  577. /* skip version and flags */
  578. avio_skip(pb, 4);
  579. ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
  580. return 0;
  581. }
  582. static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  583. {
  584. AVStream *st;
  585. if (c->fc->nb_streams < 1)
  586. return 0;
  587. st = c->fc->streams[c->fc->nb_streams-1];
  588. if (ff_get_wav_header(pb, st->codec, atom.size) < 0) {
  589. av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
  590. }
  591. return 0;
  592. }
  593. static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  594. {
  595. const int num = avio_rb32(pb);
  596. const int den = avio_rb32(pb);
  597. AVStream *st;
  598. if (c->fc->nb_streams < 1)
  599. return 0;
  600. st = c->fc->streams[c->fc->nb_streams-1];
  601. if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
  602. (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
  603. av_log(c->fc, AV_LOG_WARNING,
  604. "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
  605. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  606. num, den);
  607. } else if (den != 0) {
  608. st->sample_aspect_ratio.num = num;
  609. st->sample_aspect_ratio.den = den;
  610. }
  611. return 0;
  612. }
  613. /* this atom contains actual media data */
  614. static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  615. {
  616. if (atom.size == 0) /* wrong one (MP4) */
  617. return 0;
  618. c->found_mdat=1;
  619. return 0; /* now go for moov */
  620. }
  621. /* read major brand, minor version and compatible brands and store them as metadata */
  622. static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  623. {
  624. uint32_t minor_ver;
  625. int comp_brand_size;
  626. char* comp_brands_str;
  627. uint8_t type[5] = {0};
  628. avio_read(pb, type, 4);
  629. if (strcmp(type, "qt "))
  630. c->isom = 1;
  631. av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
  632. av_dict_set(&c->fc->metadata, "major_brand", type, 0);
  633. minor_ver = avio_rb32(pb); /* minor version */
  634. av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
  635. comp_brand_size = atom.size - 8;
  636. if (comp_brand_size < 0)
  637. return AVERROR_INVALIDDATA;
  638. comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
  639. if (!comp_brands_str)
  640. return AVERROR(ENOMEM);
  641. avio_read(pb, comp_brands_str, comp_brand_size);
  642. comp_brands_str[comp_brand_size] = 0;
  643. av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
  644. av_freep(&comp_brands_str);
  645. return 0;
  646. }
  647. /* this atom should contain all header atoms */
  648. static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  649. {
  650. int ret;
  651. if (c->found_moov) {
  652. av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
  653. avio_skip(pb, atom.size);
  654. return 0;
  655. }
  656. if ((ret = mov_read_default(c, pb, atom)) < 0)
  657. return ret;
  658. /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
  659. /* so we don't parse the whole file if over a network */
  660. c->found_moov=1;
  661. return 0; /* now go for mdat */
  662. }
  663. static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  664. {
  665. if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
  666. c->has_looked_for_mfra = 1;
  667. if (pb->seekable) {
  668. int ret;
  669. av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
  670. "for a mfra\n");
  671. if ((ret = mov_read_mfra(c, pb)) < 0) {
  672. av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
  673. "read the mfra (may be a live ismv)\n");
  674. }
  675. } else {
  676. av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
  677. "seekable, can not look for mfra\n");
  678. }
  679. }
  680. c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
  681. av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
  682. return mov_read_default(c, pb, atom);
  683. }
  684. static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
  685. {
  686. char buffer[32];
  687. if (time) {
  688. struct tm *ptm;
  689. time_t timet;
  690. if(time >= 2082844800)
  691. time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
  692. timet = time;
  693. ptm = gmtime(&timet);
  694. if (!ptm) return;
  695. strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
  696. av_dict_set(metadata, "creation_time", buffer, 0);
  697. }
  698. }
  699. static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  700. {
  701. AVStream *st;
  702. MOVStreamContext *sc;
  703. int version;
  704. char language[4] = {0};
  705. unsigned lang;
  706. int64_t creation_time;
  707. if (c->fc->nb_streams < 1)
  708. return 0;
  709. st = c->fc->streams[c->fc->nb_streams-1];
  710. sc = st->priv_data;
  711. if (sc->time_scale) {
  712. av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
  713. return AVERROR_INVALIDDATA;
  714. }
  715. version = avio_r8(pb);
  716. if (version > 1) {
  717. avpriv_request_sample(c->fc, "Version %d", version);
  718. return AVERROR_PATCHWELCOME;
  719. }
  720. avio_rb24(pb); /* flags */
  721. if (version == 1) {
  722. creation_time = avio_rb64(pb);
  723. avio_rb64(pb);
  724. } else {
  725. creation_time = avio_rb32(pb);
  726. avio_rb32(pb); /* modification time */
  727. }
  728. mov_metadata_creation_time(&st->metadata, creation_time);
  729. sc->time_scale = avio_rb32(pb);
  730. st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  731. lang = avio_rb16(pb); /* language */
  732. if (ff_mov_lang_to_iso639(lang, language))
  733. av_dict_set(&st->metadata, "language", language, 0);
  734. avio_rb16(pb); /* quality */
  735. return 0;
  736. }
  737. static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  738. {
  739. int64_t creation_time;
  740. int version = avio_r8(pb); /* version */
  741. avio_rb24(pb); /* flags */
  742. if (version == 1) {
  743. creation_time = avio_rb64(pb);
  744. avio_rb64(pb);
  745. } else {
  746. creation_time = avio_rb32(pb);
  747. avio_rb32(pb); /* modification time */
  748. }
  749. mov_metadata_creation_time(&c->fc->metadata, creation_time);
  750. c->time_scale = avio_rb32(pb); /* time scale */
  751. av_dlog(c->fc, "time scale = %i\n", c->time_scale);
  752. c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  753. // set the AVCodecContext duration because the duration of individual tracks
  754. // may be inaccurate
  755. if (c->time_scale > 0 && !c->trex_data)
  756. c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
  757. avio_rb32(pb); /* preferred scale */
  758. avio_rb16(pb); /* preferred volume */
  759. avio_skip(pb, 10); /* reserved */
  760. avio_skip(pb, 36); /* display matrix */
  761. avio_rb32(pb); /* preview time */
  762. avio_rb32(pb); /* preview duration */
  763. avio_rb32(pb); /* poster time */
  764. avio_rb32(pb); /* selection time */
  765. avio_rb32(pb); /* selection duration */
  766. avio_rb32(pb); /* current time */
  767. avio_rb32(pb); /* next track ID */
  768. return 0;
  769. }
  770. static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  771. {
  772. AVStream *st;
  773. int little_endian;
  774. if (c->fc->nb_streams < 1)
  775. return 0;
  776. st = c->fc->streams[c->fc->nb_streams-1];
  777. little_endian = avio_rb16(pb) & 0xFF;
  778. av_dlog(c->fc, "enda %d\n", little_endian);
  779. if (little_endian == 1) {
  780. switch (st->codec->codec_id) {
  781. case AV_CODEC_ID_PCM_S24BE:
  782. st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
  783. break;
  784. case AV_CODEC_ID_PCM_S32BE:
  785. st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
  786. break;
  787. case AV_CODEC_ID_PCM_F32BE:
  788. st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
  789. break;
  790. case AV_CODEC_ID_PCM_F64BE:
  791. st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
  792. break;
  793. default:
  794. break;
  795. }
  796. }
  797. return 0;
  798. }
  799. static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  800. {
  801. AVStream *st;
  802. char color_parameter_type[5] = { 0 };
  803. int color_primaries, color_trc, color_matrix;
  804. if (c->fc->nb_streams < 1)
  805. return 0;
  806. st = c->fc->streams[c->fc->nb_streams - 1];
  807. avio_read(pb, color_parameter_type, 4);
  808. if (strncmp(color_parameter_type, "nclx", 4) &&
  809. strncmp(color_parameter_type, "nclc", 4)) {
  810. av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
  811. color_parameter_type);
  812. return 0;
  813. }
  814. color_primaries = avio_rb16(pb);
  815. color_trc = avio_rb16(pb);
  816. color_matrix = avio_rb16(pb);
  817. av_dlog(c->fc, "%s: pri %d trc %d matrix %d",
  818. color_parameter_type, color_primaries, color_trc, color_matrix);
  819. if (c->isom) {
  820. uint8_t color_range = avio_r8(pb) >> 7;
  821. av_dlog(c->fc, " full %"PRIu8"", color_range);
  822. if (color_range)
  823. st->codec->color_range = AVCOL_RANGE_JPEG;
  824. else
  825. st->codec->color_range = AVCOL_RANGE_MPEG;
  826. /* 14496-12 references JPEG XR specs (rather than the more complete
  827. * 23001-8) so some adjusting is required */
  828. if (color_primaries >= AVCOL_PRI_FILM)
  829. color_primaries = AVCOL_PRI_UNSPECIFIED;
  830. if (color_trc >= AVCOL_TRC_LINEAR || color_trc <= AVCOL_TRC_LOG_SQRT ||
  831. color_trc >= AVCOL_TRC_BT2020_10)
  832. color_trc = AVCOL_TRC_UNSPECIFIED;
  833. if (color_matrix >= AVCOL_SPC_BT2020_NCL)
  834. color_matrix = AVCOL_SPC_UNSPECIFIED;
  835. st->codec->color_primaries = color_primaries;
  836. st->codec->color_trc = color_trc;
  837. st->codec->colorspace = color_matrix;
  838. } else {
  839. /* color primaries, Table 4-4 */
  840. switch (color_primaries) {
  841. case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
  842. case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
  843. case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
  844. }
  845. /* color transfer, Table 4-5 */
  846. switch (color_trc) {
  847. case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
  848. case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
  849. }
  850. /* color matrix, Table 4-6 */
  851. switch (color_matrix) {
  852. case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
  853. case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
  854. case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
  855. }
  856. }
  857. av_dlog(c->fc, "\n");
  858. return 0;
  859. }
  860. static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  861. {
  862. AVStream *st;
  863. unsigned mov_field_order;
  864. enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
  865. if (c->fc->nb_streams < 1) // will happen with jp2 files
  866. return 0;
  867. st = c->fc->streams[c->fc->nb_streams-1];
  868. if (atom.size < 2)
  869. return AVERROR_INVALIDDATA;
  870. mov_field_order = avio_rb16(pb);
  871. if ((mov_field_order & 0xFF00) == 0x0100)
  872. decoded_field_order = AV_FIELD_PROGRESSIVE;
  873. else if ((mov_field_order & 0xFF00) == 0x0200) {
  874. switch (mov_field_order & 0xFF) {
  875. case 0x01: decoded_field_order = AV_FIELD_TT;
  876. break;
  877. case 0x06: decoded_field_order = AV_FIELD_BB;
  878. break;
  879. case 0x09: decoded_field_order = AV_FIELD_TB;
  880. break;
  881. case 0x0E: decoded_field_order = AV_FIELD_BT;
  882. break;
  883. }
  884. }
  885. if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
  886. av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
  887. }
  888. st->codec->field_order = decoded_field_order;
  889. return 0;
  890. }
  891. /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
  892. static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  893. enum AVCodecID codec_id)
  894. {
  895. AVStream *st;
  896. uint64_t size;
  897. uint8_t *buf;
  898. int err;
  899. if (c->fc->nb_streams < 1) // will happen with jp2 files
  900. return 0;
  901. st= c->fc->streams[c->fc->nb_streams-1];
  902. if (st->codec->codec_id != codec_id)
  903. return 0; /* unexpected codec_id - don't mess with extradata */
  904. size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
  905. if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
  906. return AVERROR_INVALIDDATA;
  907. if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
  908. st->codec->extradata_size = 0;
  909. return err;
  910. }
  911. buf = st->codec->extradata + st->codec->extradata_size;
  912. st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
  913. AV_WB32( buf , atom.size + 8);
  914. AV_WL32( buf + 4, atom.type);
  915. err = avio_read(pb, buf + 8, atom.size);
  916. if (err < 0) {
  917. return err;
  918. } else if (err < atom.size) {
  919. av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
  920. st->codec->extradata_size -= atom.size - err;
  921. }
  922. memset(buf + 8 + err, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  923. return 0;
  924. }
  925. /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
  926. static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  927. {
  928. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
  929. }
  930. static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  931. {
  932. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
  933. }
  934. static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  935. {
  936. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
  937. }
  938. static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  939. {
  940. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
  941. if(ret == 0)
  942. ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
  943. return ret;
  944. }
  945. static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  946. {
  947. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
  948. if (!ret && c->fc->nb_streams >= 1) {
  949. AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
  950. if (avctx->extradata_size >= 40) {
  951. avctx->height = AV_RB16(&avctx->extradata[36]);
  952. avctx->width = AV_RB16(&avctx->extradata[38]);
  953. }
  954. }
  955. return ret;
  956. }
  957. static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  958. {
  959. if (c->fc->nb_streams >= 1) {
  960. AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
  961. if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
  962. codec->codec_id == AV_CODEC_ID_H264 &&
  963. atom.size > 11) {
  964. avio_skip(pb, 10);
  965. /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
  966. if (avio_rb16(pb) == 0xd4d)
  967. codec->width = 1440;
  968. return 0;
  969. }
  970. }
  971. return mov_read_avid(c, pb, atom);
  972. }
  973. static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  974. {
  975. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
  976. }
  977. static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  978. {
  979. AVStream *st;
  980. if (c->fc->nb_streams < 1)
  981. return 0;
  982. st = c->fc->streams[c->fc->nb_streams-1];
  983. if ((uint64_t)atom.size > (1<<30))
  984. return AVERROR_INVALIDDATA;
  985. if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
  986. st->codec->codec_id == AV_CODEC_ID_QDMC ||
  987. st->codec->codec_id == AV_CODEC_ID_SPEEX) {
  988. // pass all frma atom to codec, needed at least for QDMC and QDM2
  989. av_free(st->codec->extradata);
  990. if (ff_get_extradata(st->codec, pb, atom.size) < 0)
  991. return AVERROR(ENOMEM);
  992. } else if (atom.size > 8) { /* to read frma, esds atoms */
  993. int ret;
  994. if ((ret = mov_read_default(c, pb, atom)) < 0)
  995. return ret;
  996. } else
  997. avio_skip(pb, atom.size);
  998. return 0;
  999. }
  1000. /**
  1001. * This function reads atom content and puts data in extradata without tag
  1002. * nor size unlike mov_read_extradata.
  1003. */
  1004. static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1005. {
  1006. AVStream *st;
  1007. if (c->fc->nb_streams < 1)
  1008. return 0;
  1009. st = c->fc->streams[c->fc->nb_streams-1];
  1010. if ((uint64_t)atom.size > (1<<30))
  1011. return AVERROR_INVALIDDATA;
  1012. if (atom.size >= 10) {
  1013. // Broken files created by legacy versions of libavformat will
  1014. // wrap a whole fiel atom inside of a glbl atom.
  1015. unsigned size = avio_rb32(pb);
  1016. unsigned type = avio_rl32(pb);
  1017. avio_seek(pb, -8, SEEK_CUR);
  1018. if (type == MKTAG('f','i','e','l') && size == atom.size)
  1019. return mov_read_default(c, pb, atom);
  1020. }
  1021. if (st->codec->extradata_size > 1 && st->codec->extradata) {
  1022. av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
  1023. return 0;
  1024. }
  1025. av_free(st->codec->extradata);
  1026. if (ff_get_extradata(st->codec, pb, atom.size) < 0)
  1027. return AVERROR(ENOMEM);
  1028. return 0;
  1029. }
  1030. static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1031. {
  1032. AVStream *st;
  1033. uint8_t profile_level;
  1034. int ret;
  1035. if (c->fc->nb_streams < 1)
  1036. return 0;
  1037. st = c->fc->streams[c->fc->nb_streams-1];
  1038. if (atom.size >= (1<<28) || atom.size < 7)
  1039. return AVERROR_INVALIDDATA;
  1040. profile_level = avio_r8(pb);
  1041. if ((profile_level & 0xf0) != 0xc0)
  1042. return 0;
  1043. avio_seek(pb, 6, SEEK_CUR);
  1044. av_free(st->codec->extradata);
  1045. if ((ret = ff_get_extradata(st->codec, pb, atom.size - 7)) < 0)
  1046. return ret;
  1047. return 0;
  1048. }
  1049. /**
  1050. * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
  1051. * but can have extradata appended at the end after the 40 bytes belonging
  1052. * to the struct.
  1053. */
  1054. static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1055. {
  1056. AVStream *st;
  1057. if (c->fc->nb_streams < 1)
  1058. return 0;
  1059. if (atom.size <= 40)
  1060. return 0;
  1061. st = c->fc->streams[c->fc->nb_streams-1];
  1062. if ((uint64_t)atom.size > (1<<30))
  1063. return AVERROR_INVALIDDATA;
  1064. avio_skip(pb, 40);
  1065. av_free(st->codec->extradata);
  1066. if (ff_get_extradata(st->codec, pb, atom.size - 40) < 0)
  1067. return AVERROR(ENOMEM);
  1068. return 0;
  1069. }
  1070. static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1071. {
  1072. AVStream *st;
  1073. MOVStreamContext *sc;
  1074. unsigned int i, entries;
  1075. if (c->fc->nb_streams < 1)
  1076. return 0;
  1077. st = c->fc->streams[c->fc->nb_streams-1];
  1078. sc = st->priv_data;
  1079. avio_r8(pb); /* version */
  1080. avio_rb24(pb); /* flags */
  1081. entries = avio_rb32(pb);
  1082. if (!entries)
  1083. return 0;
  1084. if (entries >= UINT_MAX/sizeof(int64_t))
  1085. return AVERROR_INVALIDDATA;
  1086. sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
  1087. if (!sc->chunk_offsets)
  1088. return AVERROR(ENOMEM);
  1089. sc->chunk_count = entries;
  1090. if (atom.type == MKTAG('s','t','c','o'))
  1091. for (i = 0; i < entries && !pb->eof_reached; i++)
  1092. sc->chunk_offsets[i] = avio_rb32(pb);
  1093. else if (atom.type == MKTAG('c','o','6','4'))
  1094. for (i = 0; i < entries && !pb->eof_reached; i++)
  1095. sc->chunk_offsets[i] = avio_rb64(pb);
  1096. else
  1097. return AVERROR_INVALIDDATA;
  1098. sc->chunk_count = i;
  1099. if (pb->eof_reached)
  1100. return AVERROR_EOF;
  1101. return 0;
  1102. }
  1103. /**
  1104. * Compute codec id for 'lpcm' tag.
  1105. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  1106. */
  1107. enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
  1108. {
  1109. /* lpcm flags:
  1110. * 0x1 = float
  1111. * 0x2 = big-endian
  1112. * 0x4 = signed
  1113. */
  1114. return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
  1115. }
  1116. static int mov_codec_id(AVStream *st, uint32_t format)
  1117. {
  1118. int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
  1119. if (id <= 0 &&
  1120. ((format & 0xFFFF) == 'm' + ('s' << 8) ||
  1121. (format & 0xFFFF) == 'T' + ('S' << 8)))
  1122. id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
  1123. if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
  1124. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1125. } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
  1126. /* skip old asf mpeg4 tag */
  1127. format && format != MKTAG('m','p','4','s')) {
  1128. id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1129. if (id <= 0)
  1130. id = ff_codec_get_id(ff_codec_bmp_tags, format);
  1131. if (id > 0)
  1132. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1133. else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
  1134. (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1135. st->codec->codec_id == AV_CODEC_ID_NONE)) {
  1136. id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
  1137. if (id > 0)
  1138. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1139. }
  1140. }
  1141. st->codec->codec_tag = format;
  1142. return id;
  1143. }
  1144. static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
  1145. AVStream *st, MOVStreamContext *sc)
  1146. {
  1147. uint8_t codec_name[32];
  1148. unsigned int color_depth, len, j;
  1149. int color_greyscale;
  1150. int color_table_id;
  1151. avio_rb16(pb); /* version */
  1152. avio_rb16(pb); /* revision level */
  1153. avio_rb32(pb); /* vendor */
  1154. avio_rb32(pb); /* temporal quality */
  1155. avio_rb32(pb); /* spatial quality */
  1156. st->codec->width = avio_rb16(pb); /* width */
  1157. st->codec->height = avio_rb16(pb); /* height */
  1158. avio_rb32(pb); /* horiz resolution */
  1159. avio_rb32(pb); /* vert resolution */
  1160. avio_rb32(pb); /* data size, always 0 */
  1161. avio_rb16(pb); /* frames per samples */
  1162. len = avio_r8(pb); /* codec name, pascal string */
  1163. if (len > 31)
  1164. len = 31;
  1165. mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
  1166. if (len < 31)
  1167. avio_skip(pb, 31 - len);
  1168. if (codec_name[0])
  1169. av_dict_set(&st->metadata, "encoder", codec_name, 0);
  1170. /* codec_tag YV12 triggers an UV swap in rawdec.c */
  1171. if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
  1172. st->codec->codec_tag = MKTAG('I', '4', '2', '0');
  1173. st->codec->width &= ~1;
  1174. st->codec->height &= ~1;
  1175. }
  1176. /* Flash Media Server uses tag H263 with Sorenson Spark */
  1177. if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
  1178. !memcmp(codec_name, "Sorenson H263", 13))
  1179. st->codec->codec_id = AV_CODEC_ID_FLV1;
  1180. st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
  1181. color_table_id = avio_rb16(pb); /* colortable id */
  1182. av_dlog(c->fc, "depth %d, ctab id %d\n",
  1183. st->codec->bits_per_coded_sample, color_table_id);
  1184. /* figure out the palette situation */
  1185. color_depth = st->codec->bits_per_coded_sample & 0x1F;
  1186. color_greyscale = st->codec->bits_per_coded_sample & 0x20;
  1187. /* Do not create a greyscale palette for cinepak */
  1188. if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
  1189. return;
  1190. /* if the depth is 2, 4, or 8 bpp, file is palettized */
  1191. if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
  1192. /* for palette traversal */
  1193. unsigned int color_start, color_count, color_end;
  1194. unsigned char a, r, g, b;
  1195. if (color_greyscale) {
  1196. int color_index, color_dec;
  1197. /* compute the greyscale palette */
  1198. st->codec->bits_per_coded_sample = color_depth;
  1199. color_count = 1 << color_depth;
  1200. color_index = 255;
  1201. color_dec = 256 / (color_count - 1);
  1202. for (j = 0; j < color_count; j++) {
  1203. r = g = b = color_index;
  1204. sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
  1205. color_index -= color_dec;
  1206. if (color_index < 0)
  1207. color_index = 0;
  1208. }
  1209. } else if (color_table_id) {
  1210. const uint8_t *color_table;
  1211. /* if flag bit 3 is set, use the default palette */
  1212. color_count = 1 << color_depth;
  1213. if (color_depth == 2)
  1214. color_table = ff_qt_default_palette_4;
  1215. else if (color_depth == 4)
  1216. color_table = ff_qt_default_palette_16;
  1217. else
  1218. color_table = ff_qt_default_palette_256;
  1219. for (j = 0; j < color_count; j++) {
  1220. r = color_table[j * 3 + 0];
  1221. g = color_table[j * 3 + 1];
  1222. b = color_table[j * 3 + 2];
  1223. sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
  1224. }
  1225. } else {
  1226. /* load the palette from the file */
  1227. color_start = avio_rb32(pb);
  1228. color_count = avio_rb16(pb);
  1229. color_end = avio_rb16(pb);
  1230. if ((color_start <= 255) && (color_end <= 255)) {
  1231. for (j = color_start; j <= color_end; j++) {
  1232. /* each A, R, G, or B component is 16 bits;
  1233. * only use the top 8 bits */
  1234. a = avio_r8(pb);
  1235. avio_r8(pb);
  1236. r = avio_r8(pb);
  1237. avio_r8(pb);
  1238. g = avio_r8(pb);
  1239. avio_r8(pb);
  1240. b = avio_r8(pb);
  1241. avio_r8(pb);
  1242. sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
  1243. }
  1244. }
  1245. }
  1246. sc->has_palette = 1;
  1247. }
  1248. }
  1249. static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
  1250. AVStream *st, MOVStreamContext *sc)
  1251. {
  1252. int bits_per_sample, flags;
  1253. uint16_t version = avio_rb16(pb);
  1254. AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
  1255. avio_rb16(pb); /* revision level */
  1256. avio_rb32(pb); /* vendor */
  1257. st->codec->channels = avio_rb16(pb); /* channel count */
  1258. st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  1259. av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
  1260. sc->audio_cid = avio_rb16(pb);
  1261. avio_rb16(pb); /* packet size = 0 */
  1262. st->codec->sample_rate = ((avio_rb32(pb) >> 16));
  1263. // Read QT version 1 fields. In version 0 these do not exist.
  1264. av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
  1265. if (!c->isom ||
  1266. (compatible_brands && strstr(compatible_brands->value, "qt "))) {
  1267. if (version == 1) {
  1268. sc->samples_per_frame = avio_rb32(pb);
  1269. avio_rb32(pb); /* bytes per packet */
  1270. sc->bytes_per_frame = avio_rb32(pb);
  1271. avio_rb32(pb); /* bytes per sample */
  1272. } else if (version == 2) {
  1273. avio_rb32(pb); /* sizeof struct only */
  1274. st->codec->sample_rate = av_int2double(avio_rb64(pb));
  1275. st->codec->channels = avio_rb32(pb);
  1276. avio_rb32(pb); /* always 0x7F000000 */
  1277. st->codec->bits_per_coded_sample = avio_rb32(pb);
  1278. flags = avio_rb32(pb); /* lpcm format specific flag */
  1279. sc->bytes_per_frame = avio_rb32(pb);
  1280. sc->samples_per_frame = avio_rb32(pb);
  1281. if (st->codec->codec_tag == MKTAG('l','p','c','m'))
  1282. st->codec->codec_id =
  1283. ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
  1284. flags);
  1285. }
  1286. }
  1287. switch (st->codec->codec_id) {
  1288. case AV_CODEC_ID_PCM_S8:
  1289. case AV_CODEC_ID_PCM_U8:
  1290. if (st->codec->bits_per_coded_sample == 16)
  1291. st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
  1292. break;
  1293. case AV_CODEC_ID_PCM_S16LE:
  1294. case AV_CODEC_ID_PCM_S16BE:
  1295. if (st->codec->bits_per_coded_sample == 8)
  1296. st->codec->codec_id = AV_CODEC_ID_PCM_S8;
  1297. else if (st->codec->bits_per_coded_sample == 24)
  1298. st->codec->codec_id =
  1299. st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1300. AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  1301. else if (st->codec->bits_per_coded_sample == 32)
  1302. st->codec->codec_id =
  1303. st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1304. AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
  1305. break;
  1306. /* set values for old format before stsd version 1 appeared */
  1307. case AV_CODEC_ID_MACE3:
  1308. sc->samples_per_frame = 6;
  1309. sc->bytes_per_frame = 2 * st->codec->channels;
  1310. break;
  1311. case AV_CODEC_ID_MACE6:
  1312. sc->samples_per_frame = 6;
  1313. sc->bytes_per_frame = 1 * st->codec->channels;
  1314. break;
  1315. case AV_CODEC_ID_ADPCM_IMA_QT:
  1316. sc->samples_per_frame = 64;
  1317. sc->bytes_per_frame = 34 * st->codec->channels;
  1318. break;
  1319. case AV_CODEC_ID_GSM:
  1320. sc->samples_per_frame = 160;
  1321. sc->bytes_per_frame = 33;
  1322. break;
  1323. default:
  1324. break;
  1325. }
  1326. bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
  1327. if (bits_per_sample) {
  1328. st->codec->bits_per_coded_sample = bits_per_sample;
  1329. sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
  1330. }
  1331. }
  1332. static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
  1333. AVStream *st, MOVStreamContext *sc,
  1334. int size)
  1335. {
  1336. // ttxt stsd contains display flags, justification, background
  1337. // color, fonts, and default styles, so fake an atom to read it
  1338. MOVAtom fake_atom = { .size = size };
  1339. // mp4s contains a regular esds atom
  1340. if (st->codec->codec_tag != AV_RL32("mp4s"))
  1341. mov_read_glbl(c, pb, fake_atom);
  1342. st->codec->width = sc->width;
  1343. st->codec->height = sc->height;
  1344. }
  1345. static uint32_t yuv_to_rgba(uint32_t ycbcr)
  1346. {
  1347. uint8_t r, g, b;
  1348. int y, cb, cr;
  1349. y = (ycbcr >> 16) & 0xFF;
  1350. cr = (ycbcr >> 8) & 0xFF;
  1351. cb = ycbcr & 0xFF;
  1352. b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
  1353. g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
  1354. r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
  1355. return (r << 16) | (g << 8) | b;
  1356. }
  1357. static int mov_rewrite_dvd_sub_extradata(AVStream *st)
  1358. {
  1359. char buf[256] = {0};
  1360. uint8_t *src = st->codec->extradata;
  1361. int i;
  1362. if (st->codec->extradata_size != 64)
  1363. return 0;
  1364. if (st->codec->width > 0 && st->codec->height > 0)
  1365. snprintf(buf, sizeof(buf), "size: %dx%d\n",
  1366. st->codec->width, st->codec->height);
  1367. av_strlcat(buf, "palette: ", sizeof(buf));
  1368. for (i = 0; i < 16; i++) {
  1369. uint32_t yuv = AV_RB32(src + i * 4);
  1370. uint32_t rgba = yuv_to_rgba(yuv);
  1371. av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
  1372. }
  1373. if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
  1374. return 0;
  1375. av_freep(&st->codec->extradata);
  1376. st->codec->extradata_size = 0;
  1377. st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
  1378. if (!st->codec->extradata)
  1379. return AVERROR(ENOMEM);
  1380. st->codec->extradata_size = strlen(buf);
  1381. memcpy(st->codec->extradata, buf, st->codec->extradata_size);
  1382. return 0;
  1383. }
  1384. static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
  1385. AVStream *st, MOVStreamContext *sc,
  1386. int size)
  1387. {
  1388. if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
  1389. if (ff_get_extradata(st->codec, pb, size) < 0)
  1390. return AVERROR(ENOMEM);
  1391. if (size > 16) {
  1392. MOVStreamContext *tmcd_ctx = st->priv_data;
  1393. int val;
  1394. val = AV_RB32(st->codec->extradata + 4);
  1395. tmcd_ctx->tmcd_flags = val;
  1396. if (val & 1)
  1397. st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
  1398. st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
  1399. st->codec->time_base.num = 1;
  1400. if (size > 30) {
  1401. uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
  1402. uint32_t format = AV_RB32(st->codec->extradata + 22);
  1403. if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
  1404. uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
  1405. if (str_size > 0 && size >= (int)str_size + 26) {
  1406. char *reel_name = av_malloc(str_size + 1);
  1407. if (!reel_name)
  1408. return AVERROR(ENOMEM);
  1409. memcpy(reel_name, st->codec->extradata + 30, str_size);
  1410. reel_name[str_size] = 0; /* Add null terminator */
  1411. /* don't add reel_name if emtpy string */
  1412. if (*reel_name == 0) {
  1413. av_free(reel_name);
  1414. } else {
  1415. av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
  1416. }
  1417. }
  1418. }
  1419. }
  1420. }
  1421. } else {
  1422. /* other codec type, just skip (rtp, mp4s ...) */
  1423. avio_skip(pb, size);
  1424. }
  1425. return 0;
  1426. }
  1427. static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
  1428. AVStream *st, MOVStreamContext *sc)
  1429. {
  1430. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1431. !st->codec->sample_rate && sc->time_scale > 1)
  1432. st->codec->sample_rate = sc->time_scale;
  1433. /* special codec parameters handling */
  1434. switch (st->codec->codec_id) {
  1435. #if CONFIG_DV_DEMUXER
  1436. case AV_CODEC_ID_DVAUDIO:
  1437. c->dv_fctx = avformat_alloc_context();
  1438. c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
  1439. if (!c->dv_demux) {
  1440. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  1441. return AVERROR(ENOMEM);
  1442. }
  1443. sc->dv_audio_container = 1;
  1444. st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
  1445. break;
  1446. #endif
  1447. /* no ifdef since parameters are always those */
  1448. case AV_CODEC_ID_QCELP:
  1449. st->codec->channels = 1;
  1450. // force sample rate for qcelp when not stored in mov
  1451. if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
  1452. st->codec->sample_rate = 8000;
  1453. // FIXME: Why is the following needed for some files?
  1454. sc->samples_per_frame = 160;
  1455. if (!sc->bytes_per_frame)
  1456. sc->bytes_per_frame = 35;
  1457. break;
  1458. case AV_CODEC_ID_AMR_NB:
  1459. st->codec->channels = 1;
  1460. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  1461. st->codec->sample_rate = 8000;
  1462. break;
  1463. case AV_CODEC_ID_AMR_WB:
  1464. st->codec->channels = 1;
  1465. st->codec->sample_rate = 16000;
  1466. break;
  1467. case AV_CODEC_ID_MP2:
  1468. case AV_CODEC_ID_MP3:
  1469. /* force type after stsd for m1a hdlr */
  1470. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1471. st->need_parsing = AVSTREAM_PARSE_FULL;
  1472. break;
  1473. case AV_CODEC_ID_GSM:
  1474. case AV_CODEC_ID_ADPCM_MS:
  1475. case AV_CODEC_ID_ADPCM_IMA_WAV:
  1476. case AV_CODEC_ID_ILBC:
  1477. case AV_CODEC_ID_MACE3:
  1478. case AV_CODEC_ID_MACE6:
  1479. case AV_CODEC_ID_QDM2:
  1480. st->codec->block_align = sc->bytes_per_frame;
  1481. break;
  1482. case AV_CODEC_ID_ALAC:
  1483. if (st->codec->extradata_size == 36) {
  1484. st->codec->channels = AV_RB8 (st->codec->extradata + 21);
  1485. st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
  1486. }
  1487. break;
  1488. case AV_CODEC_ID_AC3:
  1489. case AV_CODEC_ID_EAC3:
  1490. case AV_CODEC_ID_MPEG1VIDEO:
  1491. case AV_CODEC_ID_VC1:
  1492. st->need_parsing = AVSTREAM_PARSE_FULL;
  1493. break;
  1494. default:
  1495. break;
  1496. }
  1497. return 0;
  1498. }
  1499. static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
  1500. int codec_tag, int format,
  1501. int64_t size)
  1502. {
  1503. int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1504. if (codec_tag &&
  1505. (codec_tag != format &&
  1506. (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
  1507. : codec_tag != MKTAG('j','p','e','g')))) {
  1508. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  1509. * export it as a separate AVStream but this needs a few changes
  1510. * in the MOV demuxer, patch welcome. */
  1511. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  1512. avio_skip(pb, size);
  1513. return 1;
  1514. }
  1515. if ( codec_tag == AV_RL32("avc1") ||
  1516. codec_tag == AV_RL32("hvc1") ||
  1517. codec_tag == AV_RL32("hev1")
  1518. )
  1519. av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
  1520. return 0;
  1521. }
  1522. int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
  1523. {
  1524. AVStream *st;
  1525. MOVStreamContext *sc;
  1526. int pseudo_stream_id;
  1527. if (c->fc->nb_streams < 1)
  1528. return 0;
  1529. st = c->fc->streams[c->fc->nb_streams-1];
  1530. sc = st->priv_data;
  1531. for (pseudo_stream_id = 0;
  1532. pseudo_stream_id < entries && !pb->eof_reached;
  1533. pseudo_stream_id++) {
  1534. //Parsing Sample description table
  1535. enum AVCodecID id;
  1536. int ret, dref_id = 1;
  1537. MOVAtom a = { AV_RL32("stsd") };
  1538. int64_t start_pos = avio_tell(pb);
  1539. int64_t size = avio_rb32(pb); /* size */
  1540. uint32_t format = avio_rl32(pb); /* data format */
  1541. if (size >= 16) {
  1542. avio_rb32(pb); /* reserved */
  1543. avio_rb16(pb); /* reserved */
  1544. dref_id = avio_rb16(pb);
  1545. }else if (size <= 7){
  1546. av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
  1547. return AVERROR_INVALIDDATA;
  1548. }
  1549. if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
  1550. size - (avio_tell(pb) - start_pos)))
  1551. continue;
  1552. sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
  1553. sc->dref_id= dref_id;
  1554. id = mov_codec_id(st, format);
  1555. av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
  1556. (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  1557. (format >> 24) & 0xff, st->codec->codec_type);
  1558. if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
  1559. st->codec->codec_id = id;
  1560. mov_parse_stsd_video(c, pb, st, sc);
  1561. } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
  1562. st->codec->codec_id = id;
  1563. mov_parse_stsd_audio(c, pb, st, sc);
  1564. } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
  1565. st->codec->codec_id = id;
  1566. mov_parse_stsd_subtitle(c, pb, st, sc,
  1567. size - (avio_tell(pb) - start_pos));
  1568. } else {
  1569. ret = mov_parse_stsd_data(c, pb, st, sc,
  1570. size - (avio_tell(pb) - start_pos));
  1571. if (ret < 0)
  1572. return ret;
  1573. }
  1574. /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
  1575. a.size = size - (avio_tell(pb) - start_pos);
  1576. if (a.size > 8) {
  1577. if ((ret = mov_read_default(c, pb, a)) < 0)
  1578. return ret;
  1579. } else if (a.size > 0)
  1580. avio_skip(pb, a.size);
  1581. }
  1582. if (pb->eof_reached)
  1583. return AVERROR_EOF;
  1584. return mov_finalize_stsd_codec(c, pb, st, sc);
  1585. }
  1586. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1587. {
  1588. int entries;
  1589. avio_r8(pb); /* version */
  1590. avio_rb24(pb); /* flags */
  1591. entries = avio_rb32(pb);
  1592. return ff_mov_read_stsd_entries(c, pb, entries);
  1593. }
  1594. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1595. {
  1596. AVStream *st;
  1597. MOVStreamContext *sc;
  1598. unsigned int i, entries;
  1599. if (c->fc->nb_streams < 1)
  1600. return 0;
  1601. st = c->fc->streams[c->fc->nb_streams-1];
  1602. sc = st->priv_data;
  1603. avio_r8(pb); /* version */
  1604. avio_rb24(pb); /* flags */
  1605. entries = avio_rb32(pb);
  1606. av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1607. if (!entries)
  1608. return 0;
  1609. if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
  1610. return AVERROR_INVALIDDATA;
  1611. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  1612. if (!sc->stsc_data)
  1613. return AVERROR(ENOMEM);
  1614. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1615. sc->stsc_data[i].first = avio_rb32(pb);
  1616. sc->stsc_data[i].count = avio_rb32(pb);
  1617. sc->stsc_data[i].id = avio_rb32(pb);
  1618. }
  1619. sc->stsc_count = i;
  1620. if (pb->eof_reached)
  1621. return AVERROR_EOF;
  1622. return 0;
  1623. }
  1624. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1625. {
  1626. AVStream *st;
  1627. MOVStreamContext *sc;
  1628. unsigned i, entries;
  1629. if (c->fc->nb_streams < 1)
  1630. return 0;
  1631. st = c->fc->streams[c->fc->nb_streams-1];
  1632. sc = st->priv_data;
  1633. avio_rb32(pb); // version + flags
  1634. entries = avio_rb32(pb);
  1635. if (entries >= UINT_MAX / sizeof(*sc->stps_data))
  1636. return AVERROR_INVALIDDATA;
  1637. sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
  1638. if (!sc->stps_data)
  1639. return AVERROR(ENOMEM);
  1640. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1641. sc->stps_data[i] = avio_rb32(pb);
  1642. //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
  1643. }
  1644. sc->stps_count = i;
  1645. if (pb->eof_reached)
  1646. return AVERROR_EOF;
  1647. return 0;
  1648. }
  1649. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1650. {
  1651. AVStream *st;
  1652. MOVStreamContext *sc;
  1653. unsigned int i, entries;
  1654. if (c->fc->nb_streams < 1)
  1655. return 0;
  1656. st = c->fc->streams[c->fc->nb_streams-1];
  1657. sc = st->priv_data;
  1658. avio_r8(pb); /* version */
  1659. avio_rb24(pb); /* flags */
  1660. entries = avio_rb32(pb);
  1661. av_dlog(c->fc, "keyframe_count = %d\n", entries);
  1662. if (!entries)
  1663. {
  1664. sc->keyframe_absent = 1;
  1665. if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  1666. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1667. return 0;
  1668. }
  1669. if (entries >= UINT_MAX / sizeof(int))
  1670. return AVERROR_INVALIDDATA;
  1671. sc->keyframes = av_malloc(entries * sizeof(int));
  1672. if (!sc->keyframes)
  1673. return AVERROR(ENOMEM);
  1674. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1675. sc->keyframes[i] = avio_rb32(pb);
  1676. //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
  1677. }
  1678. sc->keyframe_count = i;
  1679. if (pb->eof_reached)
  1680. return AVERROR_EOF;
  1681. return 0;
  1682. }
  1683. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1684. {
  1685. AVStream *st;
  1686. MOVStreamContext *sc;
  1687. unsigned int i, entries, sample_size, field_size, num_bytes;
  1688. GetBitContext gb;
  1689. unsigned char* buf;
  1690. if (c->fc->nb_streams < 1)
  1691. return 0;
  1692. st = c->fc->streams[c->fc->nb_streams-1];
  1693. sc = st->priv_data;
  1694. avio_r8(pb); /* version */
  1695. avio_rb24(pb); /* flags */
  1696. if (atom.type == MKTAG('s','t','s','z')) {
  1697. sample_size = avio_rb32(pb);
  1698. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  1699. sc->sample_size = sample_size;
  1700. sc->stsz_sample_size = sample_size;
  1701. field_size = 32;
  1702. } else {
  1703. sample_size = 0;
  1704. avio_rb24(pb); /* reserved */
  1705. field_size = avio_r8(pb);
  1706. }
  1707. entries = avio_rb32(pb);
  1708. av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  1709. sc->sample_count = entries;
  1710. if (sample_size)
  1711. return 0;
  1712. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  1713. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  1714. return AVERROR_INVALIDDATA;
  1715. }
  1716. if (!entries)
  1717. return 0;
  1718. if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
  1719. return AVERROR_INVALIDDATA;
  1720. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1721. if (!sc->sample_sizes)
  1722. return AVERROR(ENOMEM);
  1723. num_bytes = (entries*field_size+4)>>3;
  1724. buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
  1725. if (!buf) {
  1726. av_freep(&sc->sample_sizes);
  1727. return AVERROR(ENOMEM);
  1728. }
  1729. if (avio_read(pb, buf, num_bytes) < num_bytes) {
  1730. av_freep(&sc->sample_sizes);
  1731. av_free(buf);
  1732. return AVERROR_INVALIDDATA;
  1733. }
  1734. init_get_bits(&gb, buf, 8*num_bytes);
  1735. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1736. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  1737. sc->data_size += sc->sample_sizes[i];
  1738. }
  1739. sc->sample_count = i;
  1740. if (pb->eof_reached)
  1741. return AVERROR_EOF;
  1742. av_free(buf);
  1743. return 0;
  1744. }
  1745. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1746. {
  1747. AVStream *st;
  1748. MOVStreamContext *sc;
  1749. unsigned int i, entries;
  1750. int64_t duration=0;
  1751. int64_t total_sample_count=0;
  1752. if (c->fc->nb_streams < 1)
  1753. return 0;
  1754. st = c->fc->streams[c->fc->nb_streams-1];
  1755. sc = st->priv_data;
  1756. avio_r8(pb); /* version */
  1757. avio_rb24(pb); /* flags */
  1758. entries = avio_rb32(pb);
  1759. av_dlog(c->fc, "track[%i].stts.entries = %i\n",
  1760. c->fc->nb_streams-1, entries);
  1761. if (entries >= UINT_MAX / sizeof(*sc->stts_data))
  1762. return -1;
  1763. av_free(sc->stts_data);
  1764. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1765. if (!sc->stts_data)
  1766. return AVERROR(ENOMEM);
  1767. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1768. int sample_duration;
  1769. int sample_count;
  1770. sample_count=avio_rb32(pb);
  1771. sample_duration = avio_rb32(pb);
  1772. /* sample_duration < 0 is invalid based on the spec */
  1773. if (sample_duration < 0) {
  1774. av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta %d in STTS, at %d st:%d\n",
  1775. sample_duration, i, c->fc->nb_streams-1);
  1776. sample_duration = 1;
  1777. }
  1778. if (sample_count < 0) {
  1779. av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
  1780. return AVERROR_INVALIDDATA;
  1781. }
  1782. sc->stts_data[i].count= sample_count;
  1783. sc->stts_data[i].duration= sample_duration;
  1784. av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
  1785. sample_count, sample_duration);
  1786. if ( i+1 == entries
  1787. && i
  1788. && sample_count == 1
  1789. && total_sample_count > 100
  1790. && sample_duration/10 > duration / total_sample_count)
  1791. sample_duration = duration / total_sample_count;
  1792. duration+=(int64_t)sample_duration*sample_count;
  1793. total_sample_count+=sample_count;
  1794. }
  1795. sc->stts_count = i;
  1796. sc->duration_for_fps += duration;
  1797. sc->nb_frames_for_fps += total_sample_count;
  1798. if (pb->eof_reached)
  1799. return AVERROR_EOF;
  1800. st->nb_frames= total_sample_count;
  1801. if (duration)
  1802. st->duration= duration;
  1803. sc->track_end = duration;
  1804. return 0;
  1805. }
  1806. static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
  1807. {
  1808. if (duration < 0) {
  1809. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  1810. }
  1811. }
  1812. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1813. {
  1814. AVStream *st;
  1815. MOVStreamContext *sc;
  1816. unsigned int i, entries;
  1817. if (c->fc->nb_streams < 1)
  1818. return 0;
  1819. st = c->fc->streams[c->fc->nb_streams-1];
  1820. sc = st->priv_data;
  1821. avio_r8(pb); /* version */
  1822. avio_rb24(pb); /* flags */
  1823. entries = avio_rb32(pb);
  1824. av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  1825. if (!entries)
  1826. return 0;
  1827. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1828. return AVERROR_INVALIDDATA;
  1829. sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
  1830. if (!sc->ctts_data)
  1831. return AVERROR(ENOMEM);
  1832. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1833. int count =avio_rb32(pb);
  1834. int duration =avio_rb32(pb);
  1835. sc->ctts_data[i].count = count;
  1836. sc->ctts_data[i].duration= duration;
  1837. av_dlog(c->fc, "count=%d, duration=%d\n",
  1838. count, duration);
  1839. if (FFABS(duration) > (1<<28) && i+2<entries) {
  1840. av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
  1841. av_freep(&sc->ctts_data);
  1842. sc->ctts_count = 0;
  1843. return 0;
  1844. }
  1845. if (i+2<entries)
  1846. mov_update_dts_shift(sc, duration);
  1847. }
  1848. sc->ctts_count = i;
  1849. if (pb->eof_reached)
  1850. return AVERROR_EOF;
  1851. av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
  1852. return 0;
  1853. }
  1854. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1855. {
  1856. AVStream *st;
  1857. MOVStreamContext *sc;
  1858. unsigned int i, entries;
  1859. uint8_t version;
  1860. uint32_t grouping_type;
  1861. if (c->fc->nb_streams < 1)
  1862. return 0;
  1863. st = c->fc->streams[c->fc->nb_streams-1];
  1864. sc = st->priv_data;
  1865. version = avio_r8(pb); /* version */
  1866. avio_rb24(pb); /* flags */
  1867. grouping_type = avio_rl32(pb);
  1868. if (grouping_type != MKTAG( 'r','a','p',' '))
  1869. return 0; /* only support 'rap ' grouping */
  1870. if (version == 1)
  1871. avio_rb32(pb); /* grouping_type_parameter */
  1872. entries = avio_rb32(pb);
  1873. if (!entries)
  1874. return 0;
  1875. if (entries >= UINT_MAX / sizeof(*sc->rap_group))
  1876. return AVERROR_INVALIDDATA;
  1877. sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
  1878. if (!sc->rap_group)
  1879. return AVERROR(ENOMEM);
  1880. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1881. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  1882. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  1883. }
  1884. sc->rap_group_count = i;
  1885. return pb->eof_reached ? AVERROR_EOF : 0;
  1886. }
  1887. static void mov_build_index(MOVContext *mov, AVStream *st)
  1888. {
  1889. MOVStreamContext *sc = st->priv_data;
  1890. int64_t current_offset;
  1891. int64_t current_dts = 0;
  1892. unsigned int stts_index = 0;
  1893. unsigned int stsc_index = 0;
  1894. unsigned int stss_index = 0;
  1895. unsigned int stps_index = 0;
  1896. unsigned int i, j;
  1897. uint64_t stream_size = 0;
  1898. /* adjust first dts according to edit list */
  1899. if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
  1900. if (sc->empty_duration)
  1901. sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
  1902. sc->time_offset = sc->start_time - sc->empty_duration;
  1903. current_dts = -sc->time_offset;
  1904. if (sc->ctts_count>0 && sc->stts_count>0 &&
  1905. sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
  1906. /* more than 16 frames delay, dts are likely wrong
  1907. this happens with files created by iMovie */
  1908. sc->wrong_dts = 1;
  1909. st->codec->has_b_frames = 1;
  1910. }
  1911. }
  1912. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1913. if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1914. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1915. unsigned int current_sample = 0;
  1916. unsigned int stts_sample = 0;
  1917. unsigned int sample_size;
  1918. unsigned int distance = 0;
  1919. unsigned int rap_group_index = 0;
  1920. unsigned int rap_group_sample = 0;
  1921. int rap_group_present = sc->rap_group_count && sc->rap_group;
  1922. int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
  1923. current_dts -= sc->dts_shift;
  1924. if (!sc->sample_count || st->nb_index_entries)
  1925. return;
  1926. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  1927. return;
  1928. if (av_reallocp_array(&st->index_entries,
  1929. st->nb_index_entries + sc->sample_count,
  1930. sizeof(*st->index_entries)) < 0) {
  1931. st->nb_index_entries = 0;
  1932. return;
  1933. }
  1934. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  1935. for (i = 0; i < sc->chunk_count; i++) {
  1936. int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
  1937. current_offset = sc->chunk_offsets[i];
  1938. while (stsc_index + 1 < sc->stsc_count &&
  1939. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1940. stsc_index++;
  1941. if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
  1942. sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
  1943. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
  1944. sc->stsz_sample_size = sc->sample_size;
  1945. }
  1946. if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
  1947. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
  1948. sc->stsz_sample_size = sc->sample_size;
  1949. }
  1950. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1951. int keyframe = 0;
  1952. if (current_sample >= sc->sample_count) {
  1953. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1954. return;
  1955. }
  1956. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  1957. keyframe = 1;
  1958. if (stss_index + 1 < sc->keyframe_count)
  1959. stss_index++;
  1960. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  1961. keyframe = 1;
  1962. if (stps_index + 1 < sc->stps_count)
  1963. stps_index++;
  1964. }
  1965. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  1966. if (sc->rap_group[rap_group_index].index > 0)
  1967. keyframe = 1;
  1968. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  1969. rap_group_sample = 0;
  1970. rap_group_index++;
  1971. }
  1972. }
  1973. if (sc->keyframe_absent
  1974. && !sc->stps_count
  1975. && !rap_group_present
  1976. && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
  1977. keyframe = 1;
  1978. if (keyframe)
  1979. distance = 0;
  1980. sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
  1981. if (sc->pseudo_stream_id == -1 ||
  1982. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  1983. AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  1984. e->pos = current_offset;
  1985. e->timestamp = current_dts;
  1986. e->size = sample_size;
  1987. e->min_distance = distance;
  1988. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  1989. av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1990. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  1991. current_offset, current_dts, sample_size, distance, keyframe);
  1992. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
  1993. ff_rfps_add_frame(mov->fc, st, current_dts);
  1994. }
  1995. current_offset += sample_size;
  1996. stream_size += sample_size;
  1997. current_dts += sc->stts_data[stts_index].duration;
  1998. distance++;
  1999. stts_sample++;
  2000. current_sample++;
  2001. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  2002. stts_sample = 0;
  2003. stts_index++;
  2004. }
  2005. }
  2006. }
  2007. if (st->duration > 0)
  2008. st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
  2009. } else {
  2010. unsigned chunk_samples, total = 0;
  2011. // compute total chunk count
  2012. for (i = 0; i < sc->stsc_count; i++) {
  2013. unsigned count, chunk_count;
  2014. chunk_samples = sc->stsc_data[i].count;
  2015. if (i != sc->stsc_count - 1 &&
  2016. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  2017. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  2018. return;
  2019. }
  2020. if (sc->samples_per_frame >= 160) { // gsm
  2021. count = chunk_samples / sc->samples_per_frame;
  2022. } else if (sc->samples_per_frame > 1) {
  2023. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  2024. count = (chunk_samples+samples-1) / samples;
  2025. } else {
  2026. count = (chunk_samples+1023) / 1024;
  2027. }
  2028. if (i < sc->stsc_count - 1)
  2029. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  2030. else
  2031. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  2032. total += chunk_count * count;
  2033. }
  2034. av_dlog(mov->fc, "chunk count %d\n", total);
  2035. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2036. return;
  2037. if (av_reallocp_array(&st->index_entries,
  2038. st->nb_index_entries + total,
  2039. sizeof(*st->index_entries)) < 0) {
  2040. st->nb_index_entries = 0;
  2041. return;
  2042. }
  2043. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  2044. // populate index
  2045. for (i = 0; i < sc->chunk_count; i++) {
  2046. current_offset = sc->chunk_offsets[i];
  2047. if (stsc_index + 1 < sc->stsc_count &&
  2048. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2049. stsc_index++;
  2050. chunk_samples = sc->stsc_data[stsc_index].count;
  2051. while (chunk_samples > 0) {
  2052. AVIndexEntry *e;
  2053. unsigned size, samples;
  2054. if (sc->samples_per_frame >= 160) { // gsm
  2055. samples = sc->samples_per_frame;
  2056. size = sc->bytes_per_frame;
  2057. } else {
  2058. if (sc->samples_per_frame > 1) {
  2059. samples = FFMIN((1024 / sc->samples_per_frame)*
  2060. sc->samples_per_frame, chunk_samples);
  2061. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  2062. } else {
  2063. samples = FFMIN(1024, chunk_samples);
  2064. size = samples * sc->sample_size;
  2065. }
  2066. }
  2067. if (st->nb_index_entries >= total) {
  2068. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  2069. return;
  2070. }
  2071. e = &st->index_entries[st->nb_index_entries++];
  2072. e->pos = current_offset;
  2073. e->timestamp = current_dts;
  2074. e->size = size;
  2075. e->min_distance = 0;
  2076. e->flags = AVINDEX_KEYFRAME;
  2077. av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  2078. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  2079. size, samples);
  2080. current_offset += size;
  2081. current_dts += samples;
  2082. chunk_samples -= samples;
  2083. }
  2084. }
  2085. }
  2086. }
  2087. static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
  2088. AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
  2089. {
  2090. /* try relative path, we do not try the absolute because it can leak information about our
  2091. system to an attacker */
  2092. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  2093. char filename[1024];
  2094. const char *src_path;
  2095. int i, l;
  2096. /* find a source dir */
  2097. src_path = strrchr(src, '/');
  2098. if (src_path)
  2099. src_path++;
  2100. else
  2101. src_path = src;
  2102. /* find a next level down to target */
  2103. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  2104. if (ref->path[l] == '/') {
  2105. if (i == ref->nlvl_to - 1)
  2106. break;
  2107. else
  2108. i++;
  2109. }
  2110. /* compose filename if next level down to target was found */
  2111. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  2112. memcpy(filename, src, src_path - src);
  2113. filename[src_path - src] = 0;
  2114. for (i = 1; i < ref->nlvl_from; i++)
  2115. av_strlcat(filename, "../", 1024);
  2116. av_strlcat(filename, ref->path + l + 1, 1024);
  2117. if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
  2118. return 0;
  2119. }
  2120. } else if (use_absolute_path) {
  2121. av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
  2122. "this is a possible security issue\n");
  2123. if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
  2124. return 0;
  2125. }
  2126. return AVERROR(ENOENT);
  2127. }
  2128. static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
  2129. {
  2130. if (sc->time_scale <= 0) {
  2131. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
  2132. sc->time_scale = c->time_scale;
  2133. if (sc->time_scale <= 0)
  2134. sc->time_scale = 1;
  2135. }
  2136. }
  2137. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2138. {
  2139. AVStream *st;
  2140. MOVStreamContext *sc;
  2141. int ret;
  2142. st = avformat_new_stream(c->fc, NULL);
  2143. if (!st) return AVERROR(ENOMEM);
  2144. st->id = c->fc->nb_streams;
  2145. sc = av_mallocz(sizeof(MOVStreamContext));
  2146. if (!sc) return AVERROR(ENOMEM);
  2147. st->priv_data = sc;
  2148. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  2149. sc->ffindex = st->index;
  2150. if ((ret = mov_read_default(c, pb, atom)) < 0)
  2151. return ret;
  2152. /* sanity checks */
  2153. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  2154. (!sc->sample_size && !sc->sample_count))) {
  2155. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  2156. st->index);
  2157. return 0;
  2158. }
  2159. fix_timescale(c, sc);
  2160. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  2161. mov_build_index(c, st);
  2162. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  2163. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  2164. if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
  2165. c->use_absolute_path, c->fc) < 0)
  2166. av_log(c->fc, AV_LOG_ERROR,
  2167. "stream %d, error opening alias: path='%s', dir='%s', "
  2168. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  2169. st->index, dref->path, dref->dir, dref->filename,
  2170. dref->volume, dref->nlvl_from, dref->nlvl_to);
  2171. } else {
  2172. sc->pb = c->fc->pb;
  2173. sc->pb_is_copied = 1;
  2174. }
  2175. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  2176. if (!st->sample_aspect_ratio.num &&
  2177. (st->codec->width != sc->width || st->codec->height != sc->height)) {
  2178. st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
  2179. ((double)st->codec->width * sc->height), INT_MAX);
  2180. }
  2181. #if FF_API_R_FRAME_RATE
  2182. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  2183. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  2184. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  2185. #endif
  2186. }
  2187. // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  2188. if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
  2189. TAG_IS_AVCI(st->codec->codec_tag)) {
  2190. ret = ff_generate_avci_extradata(st);
  2191. if (ret < 0)
  2192. return ret;
  2193. }
  2194. switch (st->codec->codec_id) {
  2195. #if CONFIG_H261_DECODER
  2196. case AV_CODEC_ID_H261:
  2197. #endif
  2198. #if CONFIG_H263_DECODER
  2199. case AV_CODEC_ID_H263:
  2200. #endif
  2201. #if CONFIG_MPEG4_DECODER
  2202. case AV_CODEC_ID_MPEG4:
  2203. #endif
  2204. st->codec->width = 0; /* let decoder init width/height */
  2205. st->codec->height= 0;
  2206. break;
  2207. }
  2208. /* Do not need those anymore. */
  2209. av_freep(&sc->chunk_offsets);
  2210. av_freep(&sc->stsc_data);
  2211. av_freep(&sc->sample_sizes);
  2212. av_freep(&sc->keyframes);
  2213. av_freep(&sc->stts_data);
  2214. av_freep(&sc->stps_data);
  2215. av_freep(&sc->rap_group);
  2216. return 0;
  2217. }
  2218. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2219. {
  2220. int ret;
  2221. c->itunes_metadata = 1;
  2222. ret = mov_read_default(c, pb, atom);
  2223. c->itunes_metadata = 0;
  2224. return ret;
  2225. }
  2226. static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
  2227. {
  2228. int64_t end = avio_tell(pb) + size;
  2229. uint8_t *key = NULL, *val = NULL;
  2230. int i;
  2231. AVStream *st;
  2232. MOVStreamContext *sc;
  2233. if (c->fc->nb_streams < 1)
  2234. return 0;
  2235. st = c->fc->streams[c->fc->nb_streams-1];
  2236. sc = st->priv_data;
  2237. for (i = 0; i < 2; i++) {
  2238. uint8_t **p;
  2239. uint32_t len, tag;
  2240. if (end - avio_tell(pb) <= 12)
  2241. break;
  2242. len = avio_rb32(pb);
  2243. tag = avio_rl32(pb);
  2244. avio_skip(pb, 4); // flags
  2245. if (len < 12 || len - 12 > end - avio_tell(pb))
  2246. break;
  2247. len -= 12;
  2248. if (tag == MKTAG('n', 'a', 'm', 'e'))
  2249. p = &key;
  2250. else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
  2251. avio_skip(pb, 4);
  2252. len -= 4;
  2253. p = &val;
  2254. } else
  2255. break;
  2256. *p = av_malloc(len + 1);
  2257. if (!*p)
  2258. break;
  2259. avio_read(pb, *p, len);
  2260. (*p)[len] = 0;
  2261. }
  2262. if (key && val) {
  2263. if (strcmp(key, "iTunSMPB") == 0) {
  2264. int priming, remainder, samples;
  2265. if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
  2266. if(priming>0 && priming<16384)
  2267. sc->start_pad = priming;
  2268. }
  2269. }
  2270. if (strcmp(key, "cdec") != 0) {
  2271. av_dict_set(&c->fc->metadata, key, val,
  2272. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  2273. key = val = NULL;
  2274. }
  2275. }
  2276. avio_seek(pb, end, SEEK_SET);
  2277. av_freep(&key);
  2278. av_freep(&val);
  2279. return 0;
  2280. }
  2281. static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2282. {
  2283. int64_t end = avio_tell(pb) + atom.size;
  2284. uint32_t tag, len;
  2285. if (atom.size < 8)
  2286. goto fail;
  2287. len = avio_rb32(pb);
  2288. tag = avio_rl32(pb);
  2289. if (len > atom.size)
  2290. goto fail;
  2291. if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
  2292. uint8_t domain[128];
  2293. int domain_len;
  2294. avio_skip(pb, 4); // flags
  2295. len -= 12;
  2296. domain_len = avio_get_str(pb, len, domain, sizeof(domain));
  2297. avio_skip(pb, len - domain_len);
  2298. return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
  2299. }
  2300. fail:
  2301. av_log(c->fc, AV_LOG_VERBOSE,
  2302. "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
  2303. return 0;
  2304. }
  2305. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2306. {
  2307. while (atom.size > 8) {
  2308. uint32_t tag = avio_rl32(pb);
  2309. atom.size -= 4;
  2310. if (tag == MKTAG('h','d','l','r')) {
  2311. avio_seek(pb, -8, SEEK_CUR);
  2312. atom.size += 8;
  2313. return mov_read_default(c, pb, atom);
  2314. }
  2315. }
  2316. return 0;
  2317. }
  2318. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2319. {
  2320. int i;
  2321. int width;
  2322. int height;
  2323. int64_t disp_transform[2];
  2324. int display_matrix[3][3];
  2325. AVStream *st;
  2326. MOVStreamContext *sc;
  2327. int version;
  2328. int flags;
  2329. if (c->fc->nb_streams < 1)
  2330. return 0;
  2331. st = c->fc->streams[c->fc->nb_streams-1];
  2332. sc = st->priv_data;
  2333. version = avio_r8(pb);
  2334. flags = avio_rb24(pb);
  2335. st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  2336. if (version == 1) {
  2337. avio_rb64(pb);
  2338. avio_rb64(pb);
  2339. } else {
  2340. avio_rb32(pb); /* creation time */
  2341. avio_rb32(pb); /* modification time */
  2342. }
  2343. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  2344. avio_rb32(pb); /* reserved */
  2345. /* highlevel (considering edits) duration in movie timebase */
  2346. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  2347. avio_rb32(pb); /* reserved */
  2348. avio_rb32(pb); /* reserved */
  2349. avio_rb16(pb); /* layer */
  2350. avio_rb16(pb); /* alternate group */
  2351. avio_rb16(pb); /* volume */
  2352. avio_rb16(pb); /* reserved */
  2353. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  2354. // they're kept in fixed point format through all calculations
  2355. // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
  2356. // side data, but the scale factor is not needed to calculate aspect ratio
  2357. for (i = 0; i < 3; i++) {
  2358. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  2359. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  2360. display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  2361. }
  2362. width = avio_rb32(pb); // 16.16 fixed point track width
  2363. height = avio_rb32(pb); // 16.16 fixed point track height
  2364. sc->width = width >> 16;
  2365. sc->height = height >> 16;
  2366. // save the matrix and add rotate metadata when it is not the default
  2367. // identity
  2368. if (display_matrix[0][0] != (1 << 16) ||
  2369. display_matrix[1][1] != (1 << 16) ||
  2370. display_matrix[2][2] != (1 << 30) ||
  2371. display_matrix[0][1] || display_matrix[0][2] ||
  2372. display_matrix[1][0] || display_matrix[1][2] ||
  2373. display_matrix[2][0] || display_matrix[2][1]) {
  2374. int i, j;
  2375. double rotate;
  2376. av_freep(&sc->display_matrix);
  2377. sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
  2378. if (!sc->display_matrix)
  2379. return AVERROR(ENOMEM);
  2380. for (i = 0; i < 3; i++)
  2381. for (j = 0; j < 3; j++)
  2382. sc->display_matrix[i * 3 + j] = display_matrix[j][i];
  2383. rotate = av_display_rotation_get(sc->display_matrix);
  2384. if (!isnan(rotate)) {
  2385. char rotate_buf[64];
  2386. rotate = -rotate;
  2387. if (rotate < 0) // for backward compatibility
  2388. rotate += 360;
  2389. snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
  2390. av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
  2391. }
  2392. }
  2393. // transform the display width/height according to the matrix
  2394. // skip this if the display matrix is the default identity matrix
  2395. // or if it is rotating the picture, ex iPhone 3GS
  2396. // to keep the same scale, use [width height 1<<16]
  2397. if (width && height &&
  2398. ((display_matrix[0][0] != 65536 ||
  2399. display_matrix[1][1] != 65536) &&
  2400. !display_matrix[0][1] &&
  2401. !display_matrix[1][0] &&
  2402. !display_matrix[2][0] && !display_matrix[2][1])) {
  2403. for (i = 0; i < 2; i++)
  2404. disp_transform[i] =
  2405. (int64_t) width * display_matrix[0][i] +
  2406. (int64_t) height * display_matrix[1][i] +
  2407. ((int64_t) display_matrix[2][i] << 16);
  2408. //sample aspect ratio is new width/height divided by old width/height
  2409. st->sample_aspect_ratio = av_d2q(
  2410. ((double) disp_transform[0] * height) /
  2411. ((double) disp_transform[1] * width), INT_MAX);
  2412. }
  2413. return 0;
  2414. }
  2415. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2416. {
  2417. MOVFragment *frag = &c->fragment;
  2418. MOVTrackExt *trex = NULL;
  2419. MOVFragmentIndex* index = NULL;
  2420. int flags, track_id, i;
  2421. avio_r8(pb); /* version */
  2422. flags = avio_rb24(pb);
  2423. track_id = avio_rb32(pb);
  2424. if (!track_id)
  2425. return AVERROR_INVALIDDATA;
  2426. frag->track_id = track_id;
  2427. for (i = 0; i < c->trex_count; i++)
  2428. if (c->trex_data[i].track_id == frag->track_id) {
  2429. trex = &c->trex_data[i];
  2430. break;
  2431. }
  2432. if (!trex) {
  2433. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  2434. return AVERROR_INVALIDDATA;
  2435. }
  2436. for (i = 0; i < c->fragment_index_count; i++) {
  2437. MOVFragmentIndex* candidate = c->fragment_index_data[i];
  2438. if (candidate->track_id == frag->track_id) {
  2439. av_log(c->fc, AV_LOG_DEBUG,
  2440. "found fragment index for track %u\n", frag->track_id);
  2441. index = candidate;
  2442. break;
  2443. }
  2444. }
  2445. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  2446. avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
  2447. frag->moof_offset : frag->implicit_offset;
  2448. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  2449. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  2450. avio_rb32(pb) : trex->duration;
  2451. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  2452. avio_rb32(pb) : trex->size;
  2453. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  2454. avio_rb32(pb) : trex->flags;
  2455. frag->time = AV_NOPTS_VALUE;
  2456. if (index) {
  2457. int i, found = 0;
  2458. for (i = index->current_item; i < index->item_count; i++) {
  2459. if (frag->implicit_offset == index->items[i].moof_offset) {
  2460. av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
  2461. "for track %u and moof_offset %"PRId64"\n",
  2462. frag->track_id, index->items[i].moof_offset);
  2463. frag->time = index->items[i].time;
  2464. index->current_item = i + 1;
  2465. found = 1;
  2466. }
  2467. }
  2468. if (!found) {
  2469. av_log(c->fc, AV_LOG_WARNING, "track %u has a fragment index "
  2470. "but it doesn't have an (in-order) entry for moof_offset "
  2471. "%"PRId64"\n", frag->track_id, frag->implicit_offset);
  2472. }
  2473. }
  2474. av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
  2475. return 0;
  2476. }
  2477. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2478. {
  2479. c->chapter_track = avio_rb32(pb);
  2480. return 0;
  2481. }
  2482. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2483. {
  2484. MOVTrackExt *trex;
  2485. int err;
  2486. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  2487. return AVERROR_INVALIDDATA;
  2488. if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  2489. sizeof(*c->trex_data))) < 0) {
  2490. c->trex_count = 0;
  2491. return err;
  2492. }
  2493. c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
  2494. trex = &c->trex_data[c->trex_count++];
  2495. avio_r8(pb); /* version */
  2496. avio_rb24(pb); /* flags */
  2497. trex->track_id = avio_rb32(pb);
  2498. trex->stsd_id = avio_rb32(pb);
  2499. trex->duration = avio_rb32(pb);
  2500. trex->size = avio_rb32(pb);
  2501. trex->flags = avio_rb32(pb);
  2502. return 0;
  2503. }
  2504. static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2505. {
  2506. MOVFragment *frag = &c->fragment;
  2507. AVStream *st = NULL;
  2508. MOVStreamContext *sc;
  2509. int version, i;
  2510. for (i = 0; i < c->fc->nb_streams; i++) {
  2511. if (c->fc->streams[i]->id == frag->track_id) {
  2512. st = c->fc->streams[i];
  2513. break;
  2514. }
  2515. }
  2516. if (!st) {
  2517. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  2518. return AVERROR_INVALIDDATA;
  2519. }
  2520. sc = st->priv_data;
  2521. if (sc->pseudo_stream_id + 1 != frag->stsd_id)
  2522. return 0;
  2523. version = avio_r8(pb);
  2524. avio_rb24(pb); /* flags */
  2525. if (version) {
  2526. sc->track_end = avio_rb64(pb);
  2527. } else {
  2528. sc->track_end = avio_rb32(pb);
  2529. }
  2530. return 0;
  2531. }
  2532. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2533. {
  2534. MOVFragment *frag = &c->fragment;
  2535. AVStream *st = NULL;
  2536. MOVStreamContext *sc;
  2537. MOVStts *ctts_data;
  2538. uint64_t offset;
  2539. int64_t dts;
  2540. int data_offset = 0;
  2541. unsigned entries, first_sample_flags = frag->flags;
  2542. int flags, distance, i, found_keyframe = 0, err;
  2543. for (i = 0; i < c->fc->nb_streams; i++) {
  2544. if (c->fc->streams[i]->id == frag->track_id) {
  2545. st = c->fc->streams[i];
  2546. break;
  2547. }
  2548. }
  2549. if (!st) {
  2550. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  2551. return AVERROR_INVALIDDATA;
  2552. }
  2553. sc = st->priv_data;
  2554. if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
  2555. return 0;
  2556. avio_r8(pb); /* version */
  2557. flags = avio_rb24(pb);
  2558. entries = avio_rb32(pb);
  2559. av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
  2560. /* Always assume the presence of composition time offsets.
  2561. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  2562. * 1) in the initial movie, there are no samples.
  2563. * 2) in the first movie fragment, there is only one sample without composition time offset.
  2564. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  2565. if (!sc->ctts_count && sc->sample_count)
  2566. {
  2567. /* Complement ctts table if moov atom doesn't have ctts atom. */
  2568. ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
  2569. if (!ctts_data)
  2570. return AVERROR(ENOMEM);
  2571. sc->ctts_data = ctts_data;
  2572. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  2573. sc->ctts_data[sc->ctts_count].duration = 0;
  2574. sc->ctts_count++;
  2575. }
  2576. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  2577. return AVERROR_INVALIDDATA;
  2578. if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
  2579. sizeof(*sc->ctts_data))) < 0) {
  2580. sc->ctts_count = 0;
  2581. return err;
  2582. }
  2583. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  2584. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  2585. dts = sc->track_end - sc->time_offset;
  2586. offset = frag->base_data_offset + data_offset;
  2587. distance = 0;
  2588. av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
  2589. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2590. unsigned sample_size = frag->size;
  2591. int sample_flags = i ? frag->flags : first_sample_flags;
  2592. unsigned sample_duration = frag->duration;
  2593. int keyframe = 0;
  2594. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  2595. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  2596. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  2597. sc->ctts_data[sc->ctts_count].count = 1;
  2598. sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
  2599. avio_rb32(pb) : 0;
  2600. mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
  2601. if (frag->time != AV_NOPTS_VALUE) {
  2602. if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
  2603. int64_t pts = frag->time;
  2604. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  2605. " sc->dts_shift %d ctts.duration %d"
  2606. " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
  2607. sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
  2608. sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
  2609. dts = pts - sc->dts_shift;
  2610. if (flags & MOV_TRUN_SAMPLE_CTS) {
  2611. dts -= sc->ctts_data[sc->ctts_count].duration;
  2612. } else {
  2613. dts -= sc->time_offset;
  2614. }
  2615. av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
  2616. } else {
  2617. dts = frag->time;
  2618. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  2619. ", using it for dts\n", dts);
  2620. }
  2621. frag->time = AV_NOPTS_VALUE;
  2622. }
  2623. sc->ctts_count++;
  2624. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  2625. keyframe = 1;
  2626. else if (!found_keyframe)
  2627. keyframe = found_keyframe =
  2628. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  2629. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  2630. if (keyframe)
  2631. distance = 0;
  2632. av_add_index_entry(st, offset, dts, sample_size, distance,
  2633. keyframe ? AVINDEX_KEYFRAME : 0);
  2634. av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  2635. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  2636. offset, dts, sample_size, distance, keyframe);
  2637. distance++;
  2638. dts += sample_duration;
  2639. offset += sample_size;
  2640. sc->data_size += sample_size;
  2641. sc->duration_for_fps += sample_duration;
  2642. sc->nb_frames_for_fps ++;
  2643. }
  2644. if (pb->eof_reached)
  2645. return AVERROR_EOF;
  2646. frag->implicit_offset = offset;
  2647. st->duration = sc->track_end = dts + sc->time_offset;
  2648. return 0;
  2649. }
  2650. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  2651. /* like the files created with Adobe Premiere 5.0, for samples see */
  2652. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  2653. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2654. {
  2655. int err;
  2656. if (atom.size < 8)
  2657. return 0; /* continue */
  2658. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  2659. avio_skip(pb, atom.size - 4);
  2660. return 0;
  2661. }
  2662. atom.type = avio_rl32(pb);
  2663. atom.size -= 8;
  2664. if (atom.type != MKTAG('m','d','a','t')) {
  2665. avio_skip(pb, atom.size);
  2666. return 0;
  2667. }
  2668. err = mov_read_mdat(c, pb, atom);
  2669. return err;
  2670. }
  2671. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2672. {
  2673. #if CONFIG_ZLIB
  2674. AVIOContext ctx;
  2675. uint8_t *cmov_data;
  2676. uint8_t *moov_data; /* uncompressed data */
  2677. long cmov_len, moov_len;
  2678. int ret = -1;
  2679. avio_rb32(pb); /* dcom atom */
  2680. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  2681. return AVERROR_INVALIDDATA;
  2682. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  2683. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
  2684. return AVERROR_INVALIDDATA;
  2685. }
  2686. avio_rb32(pb); /* cmvd atom */
  2687. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  2688. return AVERROR_INVALIDDATA;
  2689. moov_len = avio_rb32(pb); /* uncompressed size */
  2690. cmov_len = atom.size - 6 * 4;
  2691. cmov_data = av_malloc(cmov_len);
  2692. if (!cmov_data)
  2693. return AVERROR(ENOMEM);
  2694. moov_data = av_malloc(moov_len);
  2695. if (!moov_data) {
  2696. av_free(cmov_data);
  2697. return AVERROR(ENOMEM);
  2698. }
  2699. avio_read(pb, cmov_data, cmov_len);
  2700. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  2701. goto free_and_return;
  2702. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  2703. goto free_and_return;
  2704. atom.type = MKTAG('m','o','o','v');
  2705. atom.size = moov_len;
  2706. ret = mov_read_default(c, &ctx, atom);
  2707. free_and_return:
  2708. av_free(moov_data);
  2709. av_free(cmov_data);
  2710. return ret;
  2711. #else
  2712. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  2713. return AVERROR(ENOSYS);
  2714. #endif
  2715. }
  2716. /* edit list atom */
  2717. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2718. {
  2719. MOVStreamContext *sc;
  2720. int i, edit_count, version, edit_start_index = 0;
  2721. int unsupported = 0;
  2722. if (c->fc->nb_streams < 1 || c->ignore_editlist)
  2723. return 0;
  2724. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  2725. version = avio_r8(pb); /* version */
  2726. avio_rb24(pb); /* flags */
  2727. edit_count = avio_rb32(pb); /* entries */
  2728. if ((uint64_t)edit_count*12+8 > atom.size)
  2729. return AVERROR_INVALIDDATA;
  2730. av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  2731. for (i=0; i<edit_count; i++){
  2732. int64_t time;
  2733. int64_t duration;
  2734. int rate;
  2735. if (version == 1) {
  2736. duration = avio_rb64(pb);
  2737. time = avio_rb64(pb);
  2738. } else {
  2739. duration = avio_rb32(pb); /* segment duration */
  2740. time = (int32_t)avio_rb32(pb); /* media time */
  2741. }
  2742. rate = avio_rb32(pb);
  2743. if (i == 0 && time == -1) {
  2744. sc->empty_duration = duration;
  2745. edit_start_index = 1;
  2746. } else if (i == edit_start_index && time >= 0)
  2747. sc->start_time = time;
  2748. else
  2749. unsupported = 1;
  2750. av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
  2751. duration, time, rate / 65536.0);
  2752. }
  2753. if (unsupported)
  2754. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  2755. "a/v desync might occur, patch welcome\n");
  2756. return 0;
  2757. }
  2758. static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2759. {
  2760. MOVStreamContext *sc;
  2761. if (c->fc->nb_streams < 1)
  2762. return AVERROR_INVALIDDATA;
  2763. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  2764. sc->timecode_track = avio_rb32(pb);
  2765. return 0;
  2766. }
  2767. static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2768. {
  2769. int ret;
  2770. uint8_t uuid[16];
  2771. static const uint8_t uuid_isml_manifest[] = {
  2772. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  2773. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  2774. };
  2775. if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
  2776. return AVERROR_INVALIDDATA;
  2777. ret = avio_read(pb, uuid, sizeof(uuid));
  2778. if (ret < 0) {
  2779. return ret;
  2780. } else if (ret != sizeof(uuid)) {
  2781. return AVERROR_INVALIDDATA;
  2782. }
  2783. if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
  2784. uint8_t *buffer, *ptr;
  2785. char *endptr;
  2786. size_t len = atom.size - sizeof(uuid);
  2787. if (len < 4) {
  2788. return AVERROR_INVALIDDATA;
  2789. }
  2790. ret = avio_skip(pb, 4); // zeroes
  2791. len -= 4;
  2792. buffer = av_mallocz(len + 1);
  2793. if (!buffer) {
  2794. return AVERROR(ENOMEM);
  2795. }
  2796. ret = avio_read(pb, buffer, len);
  2797. if (ret < 0) {
  2798. av_free(buffer);
  2799. return ret;
  2800. } else if (ret != len) {
  2801. av_free(buffer);
  2802. return AVERROR_INVALIDDATA;
  2803. }
  2804. ptr = buffer;
  2805. while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
  2806. ptr += sizeof("systemBitrate=\"") - 1;
  2807. c->bitrates_count++;
  2808. c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
  2809. if (!c->bitrates) {
  2810. c->bitrates_count = 0;
  2811. av_free(buffer);
  2812. return AVERROR(ENOMEM);
  2813. }
  2814. errno = 0;
  2815. ret = strtol(ptr, &endptr, 10);
  2816. if (ret < 0 || errno || *endptr != '"') {
  2817. c->bitrates[c->bitrates_count - 1] = 0;
  2818. } else {
  2819. c->bitrates[c->bitrates_count - 1] = ret;
  2820. }
  2821. }
  2822. av_free(buffer);
  2823. }
  2824. return 0;
  2825. }
  2826. static const MOVParseTableEntry mov_default_parse_table[] = {
  2827. { MKTAG('A','C','L','R'), mov_read_avid },
  2828. { MKTAG('A','P','R','G'), mov_read_avid },
  2829. { MKTAG('A','A','L','P'), mov_read_avid },
  2830. { MKTAG('A','R','E','S'), mov_read_ares },
  2831. { MKTAG('a','v','s','s'), mov_read_avss },
  2832. { MKTAG('c','h','p','l'), mov_read_chpl },
  2833. { MKTAG('c','o','6','4'), mov_read_stco },
  2834. { MKTAG('c','o','l','r'), mov_read_colr },
  2835. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  2836. { MKTAG('d','i','n','f'), mov_read_default },
  2837. { MKTAG('d','r','e','f'), mov_read_dref },
  2838. { MKTAG('e','d','t','s'), mov_read_default },
  2839. { MKTAG('e','l','s','t'), mov_read_elst },
  2840. { MKTAG('e','n','d','a'), mov_read_enda },
  2841. { MKTAG('f','i','e','l'), mov_read_fiel },
  2842. { MKTAG('f','t','y','p'), mov_read_ftyp },
  2843. { MKTAG('g','l','b','l'), mov_read_glbl },
  2844. { MKTAG('h','d','l','r'), mov_read_hdlr },
  2845. { MKTAG('i','l','s','t'), mov_read_ilst },
  2846. { MKTAG('j','p','2','h'), mov_read_jp2h },
  2847. { MKTAG('m','d','a','t'), mov_read_mdat },
  2848. { MKTAG('m','d','h','d'), mov_read_mdhd },
  2849. { MKTAG('m','d','i','a'), mov_read_default },
  2850. { MKTAG('m','e','t','a'), mov_read_meta },
  2851. { MKTAG('m','i','n','f'), mov_read_default },
  2852. { MKTAG('m','o','o','f'), mov_read_moof },
  2853. { MKTAG('m','o','o','v'), mov_read_moov },
  2854. { MKTAG('m','v','e','x'), mov_read_default },
  2855. { MKTAG('m','v','h','d'), mov_read_mvhd },
  2856. { MKTAG('S','M','I',' '), mov_read_svq3 },
  2857. { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
  2858. { MKTAG('a','v','c','C'), mov_read_glbl },
  2859. { MKTAG('p','a','s','p'), mov_read_pasp },
  2860. { MKTAG('s','t','b','l'), mov_read_default },
  2861. { MKTAG('s','t','c','o'), mov_read_stco },
  2862. { MKTAG('s','t','p','s'), mov_read_stps },
  2863. { MKTAG('s','t','r','f'), mov_read_strf },
  2864. { MKTAG('s','t','s','c'), mov_read_stsc },
  2865. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  2866. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  2867. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  2868. { MKTAG('s','t','t','s'), mov_read_stts },
  2869. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  2870. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  2871. { MKTAG('t','f','d','t'), mov_read_tfdt },
  2872. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  2873. { MKTAG('t','r','a','k'), mov_read_trak },
  2874. { MKTAG('t','r','a','f'), mov_read_default },
  2875. { MKTAG('t','r','e','f'), mov_read_default },
  2876. { MKTAG('t','m','c','d'), mov_read_tmcd },
  2877. { MKTAG('c','h','a','p'), mov_read_chap },
  2878. { MKTAG('t','r','e','x'), mov_read_trex },
  2879. { MKTAG('t','r','u','n'), mov_read_trun },
  2880. { MKTAG('u','d','t','a'), mov_read_default },
  2881. { MKTAG('w','a','v','e'), mov_read_wave },
  2882. { MKTAG('e','s','d','s'), mov_read_esds },
  2883. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  2884. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  2885. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  2886. { MKTAG('w','f','e','x'), mov_read_wfex },
  2887. { MKTAG('c','m','o','v'), mov_read_cmov },
  2888. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  2889. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  2890. { MKTAG('s','b','g','p'), mov_read_sbgp },
  2891. { MKTAG('h','v','c','C'), mov_read_glbl },
  2892. { MKTAG('u','u','i','d'), mov_read_uuid },
  2893. { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
  2894. { MKTAG('-','-','-','-'), mov_read_custom },
  2895. { 0, NULL }
  2896. };
  2897. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2898. {
  2899. int64_t total_size = 0;
  2900. MOVAtom a;
  2901. int i;
  2902. if (atom.size < 0)
  2903. atom.size = INT64_MAX;
  2904. while (total_size + 8 <= atom.size && !avio_feof(pb)) {
  2905. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  2906. a.size = atom.size;
  2907. a.type=0;
  2908. if (atom.size >= 8) {
  2909. a.size = avio_rb32(pb);
  2910. a.type = avio_rl32(pb);
  2911. if (a.type == MKTAG('f','r','e','e') &&
  2912. a.size >= 8 &&
  2913. c->moov_retry) {
  2914. uint8_t buf[8];
  2915. uint32_t *type = (uint32_t *)buf + 1;
  2916. avio_read(pb, buf, 8);
  2917. avio_seek(pb, -8, SEEK_CUR);
  2918. if (*type == MKTAG('m','v','h','d') ||
  2919. *type == MKTAG('c','m','o','v')) {
  2920. av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
  2921. a.type = MKTAG('m','o','o','v');
  2922. }
  2923. }
  2924. if (atom.type != MKTAG('r','o','o','t') &&
  2925. atom.type != MKTAG('m','o','o','v'))
  2926. {
  2927. if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
  2928. {
  2929. av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
  2930. avio_skip(pb, -8);
  2931. return 0;
  2932. }
  2933. }
  2934. total_size += 8;
  2935. if (a.size == 1) { /* 64 bit extended size */
  2936. a.size = avio_rb64(pb) - 8;
  2937. total_size += 8;
  2938. }
  2939. }
  2940. av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  2941. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  2942. if (a.size == 0) {
  2943. a.size = atom.size - total_size + 8;
  2944. }
  2945. a.size -= 8;
  2946. if (a.size < 0)
  2947. break;
  2948. a.size = FFMIN(a.size, atom.size - total_size);
  2949. for (i = 0; mov_default_parse_table[i].type; i++)
  2950. if (mov_default_parse_table[i].type == a.type) {
  2951. parse = mov_default_parse_table[i].parse;
  2952. break;
  2953. }
  2954. // container is user data
  2955. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  2956. atom.type == MKTAG('i','l','s','t')))
  2957. parse = mov_read_udta_string;
  2958. if (!parse) { /* skip leaf atoms data */
  2959. avio_skip(pb, a.size);
  2960. } else {
  2961. int64_t start_pos = avio_tell(pb);
  2962. int64_t left;
  2963. int err = parse(c, pb, a);
  2964. if (err < 0)
  2965. return err;
  2966. if (c->found_moov && c->found_mdat &&
  2967. ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
  2968. start_pos + a.size == avio_size(pb))) {
  2969. if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
  2970. c->next_root_atom = start_pos + a.size;
  2971. return 0;
  2972. }
  2973. left = a.size - avio_tell(pb) + start_pos;
  2974. if (left > 0) /* skip garbage at atom end */
  2975. avio_skip(pb, left);
  2976. else if (left < 0) {
  2977. av_log(c->fc, AV_LOG_WARNING,
  2978. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  2979. (char*)&a.type, -left);
  2980. avio_seek(pb, left, SEEK_CUR);
  2981. }
  2982. }
  2983. total_size += a.size;
  2984. }
  2985. if (total_size < atom.size && atom.size < 0x7ffff)
  2986. avio_skip(pb, atom.size - total_size);
  2987. return 0;
  2988. }
  2989. static int mov_probe(AVProbeData *p)
  2990. {
  2991. int64_t offset;
  2992. uint32_t tag;
  2993. int score = 0;
  2994. int moov_offset = -1;
  2995. /* check file header */
  2996. offset = 0;
  2997. for (;;) {
  2998. /* ignore invalid offset */
  2999. if ((offset + 8) > (unsigned int)p->buf_size)
  3000. break;
  3001. tag = AV_RL32(p->buf + offset + 4);
  3002. switch(tag) {
  3003. /* check for obvious tags */
  3004. case MKTAG('m','o','o','v'):
  3005. moov_offset = offset + 4;
  3006. case MKTAG('m','d','a','t'):
  3007. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  3008. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  3009. case MKTAG('f','t','y','p'):
  3010. if (AV_RB32(p->buf+offset) < 8 &&
  3011. (AV_RB32(p->buf+offset) != 1 ||
  3012. offset + 12 > (unsigned int)p->buf_size ||
  3013. AV_RB64(p->buf+offset + 8) == 0)) {
  3014. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  3015. } else if (tag == MKTAG('f','t','y','p') &&
  3016. AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')) {
  3017. score = FFMAX(score, 5);
  3018. } else {
  3019. score = AVPROBE_SCORE_MAX;
  3020. }
  3021. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3022. break;
  3023. /* those are more common words, so rate then a bit less */
  3024. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  3025. case MKTAG('w','i','d','e'):
  3026. case MKTAG('f','r','e','e'):
  3027. case MKTAG('j','u','n','k'):
  3028. case MKTAG('p','i','c','t'):
  3029. score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
  3030. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3031. break;
  3032. case MKTAG(0x82,0x82,0x7f,0x7d):
  3033. case MKTAG('s','k','i','p'):
  3034. case MKTAG('u','u','i','d'):
  3035. case MKTAG('p','r','f','l'):
  3036. /* if we only find those cause probedata is too small at least rate them */
  3037. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  3038. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3039. break;
  3040. default:
  3041. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3042. }
  3043. }
  3044. if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
  3045. /* moov atom in the header - we should make sure that this is not a
  3046. * MOV-packed MPEG-PS */
  3047. offset = moov_offset;
  3048. while(offset < (p->buf_size - 16)){ /* Sufficient space */
  3049. /* We found an actual hdlr atom */
  3050. if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
  3051. AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
  3052. AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
  3053. av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
  3054. /* We found a media handler reference atom describing an
  3055. * MPEG-PS-in-MOV, return a
  3056. * low score to force expanding the probe window until
  3057. * mpegps_probe finds what it needs */
  3058. return 5;
  3059. }else
  3060. /* Keep looking */
  3061. offset+=2;
  3062. }
  3063. }
  3064. return score;
  3065. }
  3066. // must be done after parsing all trak because there's no order requirement
  3067. static void mov_read_chapters(AVFormatContext *s)
  3068. {
  3069. MOVContext *mov = s->priv_data;
  3070. AVStream *st = NULL;
  3071. MOVStreamContext *sc;
  3072. int64_t cur_pos;
  3073. int i;
  3074. for (i = 0; i < s->nb_streams; i++)
  3075. if (s->streams[i]->id == mov->chapter_track) {
  3076. st = s->streams[i];
  3077. break;
  3078. }
  3079. if (!st) {
  3080. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  3081. return;
  3082. }
  3083. st->discard = AVDISCARD_ALL;
  3084. sc = st->priv_data;
  3085. cur_pos = avio_tell(sc->pb);
  3086. for (i = 0; i < st->nb_index_entries; i++) {
  3087. AVIndexEntry *sample = &st->index_entries[i];
  3088. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  3089. uint8_t *title;
  3090. uint16_t ch;
  3091. int len, title_len;
  3092. if (end < sample->timestamp) {
  3093. av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
  3094. end = AV_NOPTS_VALUE;
  3095. }
  3096. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  3097. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  3098. goto finish;
  3099. }
  3100. // the first two bytes are the length of the title
  3101. len = avio_rb16(sc->pb);
  3102. if (len > sample->size-2)
  3103. continue;
  3104. title_len = 2*len + 1;
  3105. if (!(title = av_mallocz(title_len)))
  3106. goto finish;
  3107. // The samples could theoretically be in any encoding if there's an encd
  3108. // atom following, but in practice are only utf-8 or utf-16, distinguished
  3109. // instead by the presence of a BOM
  3110. if (!len) {
  3111. title[0] = 0;
  3112. } else {
  3113. ch = avio_rb16(sc->pb);
  3114. if (ch == 0xfeff)
  3115. avio_get_str16be(sc->pb, len, title, title_len);
  3116. else if (ch == 0xfffe)
  3117. avio_get_str16le(sc->pb, len, title, title_len);
  3118. else {
  3119. AV_WB16(title, ch);
  3120. if (len == 1 || len == 2)
  3121. title[len] = 0;
  3122. else
  3123. avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
  3124. }
  3125. }
  3126. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  3127. av_freep(&title);
  3128. }
  3129. finish:
  3130. avio_seek(sc->pb, cur_pos, SEEK_SET);
  3131. }
  3132. static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
  3133. uint32_t value, int flags)
  3134. {
  3135. AVTimecode tc;
  3136. char buf[AV_TIMECODE_STR_SIZE];
  3137. AVRational rate = {st->codec->time_base.den,
  3138. st->codec->time_base.num};
  3139. int ret = av_timecode_init(&tc, rate, flags, 0, s);
  3140. if (ret < 0)
  3141. return ret;
  3142. av_dict_set(&st->metadata, "timecode",
  3143. av_timecode_make_string(&tc, buf, value), 0);
  3144. return 0;
  3145. }
  3146. static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
  3147. {
  3148. MOVStreamContext *sc = st->priv_data;
  3149. int flags = 0;
  3150. int64_t cur_pos = avio_tell(sc->pb);
  3151. uint32_t value;
  3152. if (!st->nb_index_entries)
  3153. return -1;
  3154. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  3155. value = avio_rb32(s->pb);
  3156. if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
  3157. if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  3158. if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
  3159. /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
  3160. * not the case) and thus assume "frame number format" instead of QT one.
  3161. * No sample with tmcd track can be found with a QT timecode at the moment,
  3162. * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
  3163. * format). */
  3164. parse_timecode_in_framenum_format(s, st, value, flags);
  3165. avio_seek(sc->pb, cur_pos, SEEK_SET);
  3166. return 0;
  3167. }
  3168. static int mov_read_close(AVFormatContext *s)
  3169. {
  3170. MOVContext *mov = s->priv_data;
  3171. int i, j;
  3172. for (i = 0; i < s->nb_streams; i++) {
  3173. AVStream *st = s->streams[i];
  3174. MOVStreamContext *sc = st->priv_data;
  3175. av_freep(&sc->ctts_data);
  3176. for (j = 0; j < sc->drefs_count; j++) {
  3177. av_freep(&sc->drefs[j].path);
  3178. av_freep(&sc->drefs[j].dir);
  3179. }
  3180. av_freep(&sc->drefs);
  3181. sc->drefs_count = 0;
  3182. if (!sc->pb_is_copied)
  3183. avio_close(sc->pb);
  3184. sc->pb = NULL;
  3185. av_freep(&sc->chunk_offsets);
  3186. av_freep(&sc->stsc_data);
  3187. av_freep(&sc->sample_sizes);
  3188. av_freep(&sc->keyframes);
  3189. av_freep(&sc->stts_data);
  3190. av_freep(&sc->stps_data);
  3191. av_freep(&sc->rap_group);
  3192. av_freep(&sc->display_matrix);
  3193. }
  3194. if (mov->dv_demux) {
  3195. avformat_free_context(mov->dv_fctx);
  3196. mov->dv_fctx = NULL;
  3197. }
  3198. av_freep(&mov->trex_data);
  3199. av_freep(&mov->bitrates);
  3200. for (i = 0; i < mov->fragment_index_count; i++) {
  3201. MOVFragmentIndex* index = mov->fragment_index_data[i];
  3202. av_freep(&index->items);
  3203. av_freep(&mov->fragment_index_data[i]);
  3204. }
  3205. av_freep(&mov->fragment_index_data);
  3206. return 0;
  3207. }
  3208. static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
  3209. {
  3210. int i;
  3211. for (i = 0; i < s->nb_streams; i++) {
  3212. AVStream *st = s->streams[i];
  3213. MOVStreamContext *sc = st->priv_data;
  3214. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  3215. sc->timecode_track == tmcd_id)
  3216. return 1;
  3217. }
  3218. return 0;
  3219. }
  3220. /* look for a tmcd track not referenced by any video track, and export it globally */
  3221. static void export_orphan_timecode(AVFormatContext *s)
  3222. {
  3223. int i;
  3224. for (i = 0; i < s->nb_streams; i++) {
  3225. AVStream *st = s->streams[i];
  3226. if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
  3227. !tmcd_is_referenced(s, i + 1)) {
  3228. AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
  3229. if (tcr) {
  3230. av_dict_set(&s->metadata, "timecode", tcr->value, 0);
  3231. break;
  3232. }
  3233. }
  3234. }
  3235. }
  3236. static int read_tfra(MOVContext *mov, AVIOContext *f)
  3237. {
  3238. MOVFragmentIndex* index = NULL;
  3239. int version, fieldlength, i, j, err;
  3240. int64_t pos = avio_tell(f);
  3241. uint32_t size = avio_rb32(f);
  3242. if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
  3243. return -1;
  3244. }
  3245. av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
  3246. index = av_mallocz(sizeof(MOVFragmentIndex));
  3247. if (!index) {
  3248. return AVERROR(ENOMEM);
  3249. }
  3250. mov->fragment_index_count++;
  3251. if ((err = av_reallocp(&mov->fragment_index_data,
  3252. mov->fragment_index_count *
  3253. sizeof(MOVFragmentIndex*))) < 0) {
  3254. av_freep(&index);
  3255. return err;
  3256. }
  3257. mov->fragment_index_data[mov->fragment_index_count - 1] =
  3258. index;
  3259. version = avio_r8(f);
  3260. avio_rb24(f);
  3261. index->track_id = avio_rb32(f);
  3262. fieldlength = avio_rb32(f);
  3263. index->item_count = avio_rb32(f);
  3264. index->items = av_mallocz(
  3265. index->item_count * sizeof(MOVFragmentIndexItem));
  3266. if (!index->items) {
  3267. return AVERROR(ENOMEM);
  3268. }
  3269. for (i = 0; i < index->item_count; i++) {
  3270. int64_t time, offset;
  3271. if (version == 1) {
  3272. time = avio_rb64(f);
  3273. offset = avio_rb64(f);
  3274. } else {
  3275. time = avio_rb32(f);
  3276. offset = avio_rb32(f);
  3277. }
  3278. index->items[i].time = time;
  3279. index->items[i].moof_offset = offset;
  3280. for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
  3281. avio_r8(f);
  3282. for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
  3283. avio_r8(f);
  3284. for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
  3285. avio_r8(f);
  3286. }
  3287. avio_seek(f, pos + size, SEEK_SET);
  3288. return 0;
  3289. }
  3290. static int mov_read_mfra(MOVContext *c, AVIOContext *f)
  3291. {
  3292. int64_t stream_size = avio_size(f);
  3293. int64_t original_pos = avio_tell(f);
  3294. int32_t mfra_size;
  3295. int ret = -1;
  3296. if ((ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) goto fail;
  3297. mfra_size = avio_rb32(f);
  3298. if (mfra_size < 0 || mfra_size > stream_size) {
  3299. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
  3300. ret = -1;
  3301. goto fail;
  3302. }
  3303. if ((ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) goto fail;
  3304. if (avio_rb32(f) != mfra_size) {
  3305. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
  3306. ret = -1;
  3307. goto fail;
  3308. }
  3309. if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
  3310. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
  3311. goto fail;
  3312. }
  3313. av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
  3314. while (!read_tfra(c, f)) {
  3315. /* Empty */
  3316. }
  3317. fail:
  3318. ret = avio_seek(f, original_pos, SEEK_SET);
  3319. if (ret < 0)
  3320. av_log(c->fc, AV_LOG_ERROR,
  3321. "failed to seek back after looking for mfra\n");
  3322. else
  3323. ret = 0;
  3324. return ret;
  3325. }
  3326. static int mov_read_header(AVFormatContext *s)
  3327. {
  3328. MOVContext *mov = s->priv_data;
  3329. AVIOContext *pb = s->pb;
  3330. int j, err;
  3331. MOVAtom atom = { AV_RL32("root") };
  3332. int i;
  3333. mov->fc = s;
  3334. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  3335. if (pb->seekable)
  3336. atom.size = avio_size(pb);
  3337. else
  3338. atom.size = INT64_MAX;
  3339. /* check MOV header */
  3340. do {
  3341. if (mov->moov_retry)
  3342. avio_seek(pb, 0, SEEK_SET);
  3343. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  3344. av_log(s, AV_LOG_ERROR, "error reading header\n");
  3345. mov_read_close(s);
  3346. return err;
  3347. }
  3348. } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
  3349. if (!mov->found_moov) {
  3350. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  3351. mov_read_close(s);
  3352. return AVERROR_INVALIDDATA;
  3353. }
  3354. av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  3355. if (pb->seekable) {
  3356. if (mov->chapter_track > 0)
  3357. mov_read_chapters(s);
  3358. for (i = 0; i < s->nb_streams; i++)
  3359. if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
  3360. mov_read_timecode_track(s, s->streams[i]);
  3361. }
  3362. /* copy timecode metadata from tmcd tracks to the related video streams */
  3363. for (i = 0; i < s->nb_streams; i++) {
  3364. AVStream *st = s->streams[i];
  3365. MOVStreamContext *sc = st->priv_data;
  3366. if (sc->timecode_track > 0) {
  3367. AVDictionaryEntry *tcr;
  3368. int tmcd_st_id = -1;
  3369. for (j = 0; j < s->nb_streams; j++)
  3370. if (s->streams[j]->id == sc->timecode_track)
  3371. tmcd_st_id = j;
  3372. if (tmcd_st_id < 0 || tmcd_st_id == i)
  3373. continue;
  3374. tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
  3375. if (tcr)
  3376. av_dict_set(&st->metadata, "timecode", tcr->value, 0);
  3377. }
  3378. }
  3379. export_orphan_timecode(s);
  3380. for (i = 0; i < s->nb_streams; i++) {
  3381. AVStream *st = s->streams[i];
  3382. MOVStreamContext *sc = st->priv_data;
  3383. fix_timescale(mov, sc);
  3384. if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
  3385. st->skip_samples = sc->start_pad;
  3386. }
  3387. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
  3388. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  3389. sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
  3390. if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  3391. if (st->codec->width <= 0 && st->codec->height <= 0) {
  3392. st->codec->width = sc->width;
  3393. st->codec->height = sc->height;
  3394. }
  3395. if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
  3396. if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
  3397. return err;
  3398. }
  3399. }
  3400. }
  3401. if (mov->trex_data) {
  3402. for (i = 0; i < s->nb_streams; i++) {
  3403. AVStream *st = s->streams[i];
  3404. MOVStreamContext *sc = st->priv_data;
  3405. if (st->duration > 0)
  3406. st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  3407. }
  3408. }
  3409. for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
  3410. if (mov->bitrates[i]) {
  3411. s->streams[i]->codec->bit_rate = mov->bitrates[i];
  3412. }
  3413. }
  3414. ff_rfps_calculate(s);
  3415. for (i = 0; i < s->nb_streams; i++) {
  3416. AVStream *st = s->streams[i];
  3417. MOVStreamContext *sc = st->priv_data;
  3418. switch (st->codec->codec_type) {
  3419. case AVMEDIA_TYPE_AUDIO:
  3420. err = ff_replaygain_export(st, s->metadata);
  3421. if (err < 0) {
  3422. mov_read_close(s);
  3423. return err;
  3424. }
  3425. break;
  3426. case AVMEDIA_TYPE_VIDEO:
  3427. if (sc->display_matrix) {
  3428. AVPacketSideData *sd, *tmp;
  3429. tmp = av_realloc_array(st->side_data,
  3430. st->nb_side_data + 1, sizeof(*tmp));
  3431. if (!tmp)
  3432. return AVERROR(ENOMEM);
  3433. st->side_data = tmp;
  3434. st->nb_side_data++;
  3435. sd = &st->side_data[st->nb_side_data - 1];
  3436. sd->type = AV_PKT_DATA_DISPLAYMATRIX;
  3437. sd->size = sizeof(int32_t) * 9;
  3438. sd->data = (uint8_t*)sc->display_matrix;
  3439. sc->display_matrix = NULL;
  3440. }
  3441. break;
  3442. }
  3443. }
  3444. return 0;
  3445. }
  3446. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  3447. {
  3448. AVIndexEntry *sample = NULL;
  3449. int64_t best_dts = INT64_MAX;
  3450. int i;
  3451. for (i = 0; i < s->nb_streams; i++) {
  3452. AVStream *avst = s->streams[i];
  3453. MOVStreamContext *msc = avst->priv_data;
  3454. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  3455. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  3456. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  3457. av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  3458. if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  3459. (s->pb->seekable &&
  3460. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  3461. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  3462. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  3463. sample = current_sample;
  3464. best_dts = dts;
  3465. *st = avst;
  3466. }
  3467. }
  3468. }
  3469. return sample;
  3470. }
  3471. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  3472. {
  3473. MOVContext *mov = s->priv_data;
  3474. MOVStreamContext *sc;
  3475. AVIndexEntry *sample;
  3476. AVStream *st = NULL;
  3477. int ret;
  3478. mov->fc = s;
  3479. retry:
  3480. sample = mov_find_next_sample(s, &st);
  3481. if (!sample) {
  3482. mov->found_mdat = 0;
  3483. if (!mov->next_root_atom)
  3484. return AVERROR_EOF;
  3485. avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
  3486. mov->next_root_atom = 0;
  3487. if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  3488. avio_feof(s->pb))
  3489. return AVERROR_EOF;
  3490. av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  3491. goto retry;
  3492. }
  3493. sc = st->priv_data;
  3494. /* must be done just before reading, to avoid infinite loop on sample */
  3495. sc->current_sample++;
  3496. if (mov->next_root_atom) {
  3497. sample->pos = FFMIN(sample->pos, mov->next_root_atom);
  3498. sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
  3499. }
  3500. if (st->discard != AVDISCARD_ALL) {
  3501. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  3502. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  3503. sc->ffindex, sample->pos);
  3504. return AVERROR_INVALIDDATA;
  3505. }
  3506. ret = av_get_packet(sc->pb, pkt, sample->size);
  3507. if (ret < 0)
  3508. return ret;
  3509. if (sc->has_palette) {
  3510. uint8_t *pal;
  3511. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  3512. if (!pal) {
  3513. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  3514. } else {
  3515. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  3516. sc->has_palette = 0;
  3517. }
  3518. }
  3519. #if CONFIG_DV_DEMUXER
  3520. if (mov->dv_demux && sc->dv_audio_container) {
  3521. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  3522. av_free(pkt->data);
  3523. pkt->size = 0;
  3524. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  3525. if (ret < 0)
  3526. return ret;
  3527. }
  3528. #endif
  3529. }
  3530. pkt->stream_index = sc->ffindex;
  3531. pkt->dts = sample->timestamp;
  3532. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  3533. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  3534. /* update ctts context */
  3535. sc->ctts_sample++;
  3536. if (sc->ctts_index < sc->ctts_count &&
  3537. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  3538. sc->ctts_index++;
  3539. sc->ctts_sample = 0;
  3540. }
  3541. if (sc->wrong_dts)
  3542. pkt->dts = AV_NOPTS_VALUE;
  3543. } else {
  3544. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  3545. st->index_entries[sc->current_sample].timestamp : st->duration;
  3546. pkt->duration = next_dts - pkt->dts;
  3547. pkt->pts = pkt->dts;
  3548. }
  3549. if (st->discard == AVDISCARD_ALL)
  3550. goto retry;
  3551. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  3552. pkt->pos = sample->pos;
  3553. av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
  3554. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  3555. return 0;
  3556. }
  3557. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  3558. {
  3559. MOVStreamContext *sc = st->priv_data;
  3560. int sample, time_sample;
  3561. int i;
  3562. sample = av_index_search_timestamp(st, timestamp, flags);
  3563. av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  3564. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  3565. sample = 0;
  3566. if (sample < 0) /* not sure what to do */
  3567. return AVERROR_INVALIDDATA;
  3568. sc->current_sample = sample;
  3569. av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
  3570. /* adjust ctts index */
  3571. if (sc->ctts_data) {
  3572. time_sample = 0;
  3573. for (i = 0; i < sc->ctts_count; i++) {
  3574. int next = time_sample + sc->ctts_data[i].count;
  3575. if (next > sc->current_sample) {
  3576. sc->ctts_index = i;
  3577. sc->ctts_sample = sc->current_sample - time_sample;
  3578. break;
  3579. }
  3580. time_sample = next;
  3581. }
  3582. }
  3583. return sample;
  3584. }
  3585. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  3586. {
  3587. AVStream *st;
  3588. int64_t seek_timestamp, timestamp;
  3589. int sample;
  3590. int i;
  3591. if (stream_index >= s->nb_streams)
  3592. return AVERROR_INVALIDDATA;
  3593. st = s->streams[stream_index];
  3594. sample = mov_seek_stream(s, st, sample_time, flags);
  3595. if (sample < 0)
  3596. return sample;
  3597. /* adjust seek timestamp to found sample timestamp */
  3598. seek_timestamp = st->index_entries[sample].timestamp;
  3599. for (i = 0; i < s->nb_streams; i++) {
  3600. MOVStreamContext *sc = s->streams[i]->priv_data;
  3601. st = s->streams[i];
  3602. st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
  3603. if (stream_index == i)
  3604. continue;
  3605. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  3606. mov_seek_stream(s, st, timestamp, flags);
  3607. }
  3608. return 0;
  3609. }
  3610. static const AVOption options[] = {
  3611. {"use_absolute_path",
  3612. "allow using absolute path when opening alias, this is a possible security issue",
  3613. offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
  3614. 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
  3615. {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
  3616. 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
  3617. {"use_mfra_for",
  3618. "use mfra for fragment timestamps",
  3619. offsetof(MOVContext, use_mfra_for), FF_OPT_TYPE_INT, {.i64 = 0},
  3620. 0, FF_MOV_FLAG_MFRA_PTS, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM,
  3621. "use_mfra_for"},
  3622. {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
  3623. AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM, "use_mfra_for" },
  3624. {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
  3625. AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM, "use_mfra_for" },
  3626. {NULL}
  3627. };
  3628. static const AVClass mov_class = {
  3629. .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
  3630. .item_name = av_default_item_name,
  3631. .option = options,
  3632. .version = LIBAVUTIL_VERSION_INT,
  3633. };
  3634. AVInputFormat ff_mov_demuxer = {
  3635. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  3636. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  3637. .priv_data_size = sizeof(MOVContext),
  3638. .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
  3639. .read_probe = mov_probe,
  3640. .read_header = mov_read_header,
  3641. .read_packet = mov_read_packet,
  3642. .read_close = mov_read_close,
  3643. .read_seek = mov_read_seek,
  3644. .priv_class = &mov_class,
  3645. .flags = AVFMT_NO_BYTE_SEEK,
  3646. };