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.

3634 lines
119KB

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