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.

3624 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. avio_read(pb, buf + 8, atom.size);
  860. return 0;
  861. }
  862. /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
  863. static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  864. {
  865. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
  866. }
  867. static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  868. {
  869. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
  870. }
  871. static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  872. {
  873. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
  874. }
  875. static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  876. {
  877. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
  878. }
  879. static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  880. {
  881. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
  882. if (!ret && c->fc->nb_streams >= 1) {
  883. AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
  884. if (avctx->extradata_size >= 40) {
  885. avctx->height = AV_RB16(&avctx->extradata[36]);
  886. avctx->width = AV_RB16(&avctx->extradata[38]);
  887. }
  888. }
  889. return ret;
  890. }
  891. static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  892. {
  893. if (c->fc->nb_streams >= 1) {
  894. AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
  895. if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
  896. codec->codec_id == AV_CODEC_ID_H264 &&
  897. atom.size > 11) {
  898. avio_skip(pb, 10);
  899. /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
  900. if (avio_rb16(pb) == 0xd4d)
  901. codec->width = 1440;
  902. return 0;
  903. }
  904. }
  905. return mov_read_avid(c, pb, atom);
  906. }
  907. static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  908. {
  909. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
  910. }
  911. static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  912. {
  913. AVStream *st;
  914. if (c->fc->nb_streams < 1)
  915. return 0;
  916. st = c->fc->streams[c->fc->nb_streams-1];
  917. if ((uint64_t)atom.size > (1<<30))
  918. return AVERROR_INVALIDDATA;
  919. if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
  920. st->codec->codec_id == AV_CODEC_ID_QDMC ||
  921. st->codec->codec_id == AV_CODEC_ID_SPEEX) {
  922. // pass all frma atom to codec, needed at least for QDMC and QDM2
  923. av_free(st->codec->extradata);
  924. if (ff_alloc_extradata(st->codec, atom.size))
  925. return AVERROR(ENOMEM);
  926. avio_read(pb, st->codec->extradata, atom.size);
  927. } else if (atom.size > 8) { /* to read frma, esds atoms */
  928. int ret;
  929. if ((ret = mov_read_default(c, pb, atom)) < 0)
  930. return ret;
  931. } else
  932. avio_skip(pb, atom.size);
  933. return 0;
  934. }
  935. /**
  936. * This function reads atom content and puts data in extradata without tag
  937. * nor size unlike mov_read_extradata.
  938. */
  939. static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  940. {
  941. AVStream *st;
  942. if (c->fc->nb_streams < 1)
  943. return 0;
  944. st = c->fc->streams[c->fc->nb_streams-1];
  945. if ((uint64_t)atom.size > (1<<30))
  946. return AVERROR_INVALIDDATA;
  947. if (atom.size >= 10) {
  948. // Broken files created by legacy versions of libavformat will
  949. // wrap a whole fiel atom inside of a glbl atom.
  950. unsigned size = avio_rb32(pb);
  951. unsigned type = avio_rl32(pb);
  952. avio_seek(pb, -8, SEEK_CUR);
  953. if (type == MKTAG('f','i','e','l') && size == atom.size)
  954. return mov_read_default(c, pb, atom);
  955. }
  956. av_free(st->codec->extradata);
  957. if (ff_alloc_extradata(st->codec, atom.size))
  958. return AVERROR(ENOMEM);
  959. avio_read(pb, st->codec->extradata, atom.size);
  960. return 0;
  961. }
  962. static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  963. {
  964. AVStream *st;
  965. uint8_t profile_level;
  966. if (c->fc->nb_streams < 1)
  967. return 0;
  968. st = c->fc->streams[c->fc->nb_streams-1];
  969. if (atom.size >= (1<<28) || atom.size < 7)
  970. return AVERROR_INVALIDDATA;
  971. profile_level = avio_r8(pb);
  972. if ((profile_level & 0xf0) != 0xc0)
  973. return 0;
  974. av_free(st->codec->extradata);
  975. if (ff_alloc_extradata(st->codec, atom.size - 7))
  976. return AVERROR(ENOMEM);
  977. avio_seek(pb, 6, SEEK_CUR);
  978. avio_read(pb, st->codec->extradata, st->codec->extradata_size);
  979. return 0;
  980. }
  981. /**
  982. * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
  983. * but can have extradata appended at the end after the 40 bytes belonging
  984. * to the struct.
  985. */
  986. static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  987. {
  988. AVStream *st;
  989. if (c->fc->nb_streams < 1)
  990. return 0;
  991. if (atom.size <= 40)
  992. return 0;
  993. st = c->fc->streams[c->fc->nb_streams-1];
  994. if ((uint64_t)atom.size > (1<<30))
  995. return AVERROR_INVALIDDATA;
  996. av_free(st->codec->extradata);
  997. if (ff_alloc_extradata(st->codec, atom.size - 40))
  998. return AVERROR(ENOMEM);
  999. avio_skip(pb, 40);
  1000. avio_read(pb, st->codec->extradata, atom.size - 40);
  1001. return 0;
  1002. }
  1003. static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1004. {
  1005. AVStream *st;
  1006. MOVStreamContext *sc;
  1007. unsigned int i, entries;
  1008. if (c->fc->nb_streams < 1)
  1009. return 0;
  1010. st = c->fc->streams[c->fc->nb_streams-1];
  1011. sc = st->priv_data;
  1012. avio_r8(pb); /* version */
  1013. avio_rb24(pb); /* flags */
  1014. entries = avio_rb32(pb);
  1015. if (!entries)
  1016. return 0;
  1017. if (entries >= UINT_MAX/sizeof(int64_t))
  1018. return AVERROR_INVALIDDATA;
  1019. sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
  1020. if (!sc->chunk_offsets)
  1021. return AVERROR(ENOMEM);
  1022. sc->chunk_count = entries;
  1023. if (atom.type == MKTAG('s','t','c','o'))
  1024. for (i = 0; i < entries && !pb->eof_reached; i++)
  1025. sc->chunk_offsets[i] = avio_rb32(pb);
  1026. else if (atom.type == MKTAG('c','o','6','4'))
  1027. for (i = 0; i < entries && !pb->eof_reached; i++)
  1028. sc->chunk_offsets[i] = avio_rb64(pb);
  1029. else
  1030. return AVERROR_INVALIDDATA;
  1031. sc->chunk_count = i;
  1032. if (pb->eof_reached)
  1033. return AVERROR_EOF;
  1034. return 0;
  1035. }
  1036. /**
  1037. * Compute codec id for 'lpcm' tag.
  1038. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  1039. */
  1040. enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
  1041. {
  1042. /* lpcm flags:
  1043. * 0x1 = float
  1044. * 0x2 = big-endian
  1045. * 0x4 = signed
  1046. */
  1047. return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
  1048. }
  1049. static int mov_codec_id(AVStream *st, uint32_t format)
  1050. {
  1051. int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
  1052. if (id <= 0 &&
  1053. ((format & 0xFFFF) == 'm' + ('s' << 8) ||
  1054. (format & 0xFFFF) == 'T' + ('S' << 8)))
  1055. id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
  1056. if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
  1057. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1058. } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
  1059. /* skip old asf mpeg4 tag */
  1060. format && format != MKTAG('m','p','4','s')) {
  1061. id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1062. if (id <= 0)
  1063. id = ff_codec_get_id(ff_codec_bmp_tags, format);
  1064. if (id > 0)
  1065. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1066. else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
  1067. (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1068. st->codec->codec_id == AV_CODEC_ID_NONE)) {
  1069. id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
  1070. if (id > 0)
  1071. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1072. }
  1073. }
  1074. st->codec->codec_tag = format;
  1075. return id;
  1076. }
  1077. static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
  1078. AVStream *st, MOVStreamContext *sc)
  1079. {
  1080. unsigned int color_depth, len, j;
  1081. int color_greyscale;
  1082. int color_table_id;
  1083. avio_rb16(pb); /* version */
  1084. avio_rb16(pb); /* revision level */
  1085. avio_rb32(pb); /* vendor */
  1086. avio_rb32(pb); /* temporal quality */
  1087. avio_rb32(pb); /* spatial quality */
  1088. st->codec->width = avio_rb16(pb); /* width */
  1089. st->codec->height = avio_rb16(pb); /* height */
  1090. avio_rb32(pb); /* horiz resolution */
  1091. avio_rb32(pb); /* vert resolution */
  1092. avio_rb32(pb); /* data size, always 0 */
  1093. avio_rb16(pb); /* frames per samples */
  1094. len = avio_r8(pb); /* codec name, pascal string */
  1095. if (len > 31)
  1096. len = 31;
  1097. mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
  1098. if (len < 31)
  1099. avio_skip(pb, 31 - len);
  1100. /* codec_tag YV12 triggers an UV swap in rawdec.c */
  1101. if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
  1102. st->codec->codec_tag = MKTAG('I', '4', '2', '0');
  1103. st->codec->width &= ~1;
  1104. st->codec->height &= ~1;
  1105. }
  1106. /* Flash Media Server uses tag H263 with Sorenson Spark */
  1107. if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
  1108. !memcmp(st->codec->codec_name, "Sorenson H263", 13))
  1109. st->codec->codec_id = AV_CODEC_ID_FLV1;
  1110. st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
  1111. color_table_id = avio_rb16(pb); /* colortable id */
  1112. av_dlog(c->fc, "depth %d, ctab id %d\n",
  1113. st->codec->bits_per_coded_sample, color_table_id);
  1114. /* figure out the palette situation */
  1115. color_depth = st->codec->bits_per_coded_sample & 0x1F;
  1116. color_greyscale = st->codec->bits_per_coded_sample & 0x20;
  1117. /* if the depth is 2, 4, or 8 bpp, file is palettized */
  1118. if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
  1119. /* for palette traversal */
  1120. unsigned int color_start, color_count, color_end;
  1121. unsigned char a, r, g, b;
  1122. if (color_greyscale) {
  1123. int color_index, color_dec;
  1124. /* compute the greyscale palette */
  1125. st->codec->bits_per_coded_sample = color_depth;
  1126. color_count = 1 << color_depth;
  1127. color_index = 255;
  1128. color_dec = 256 / (color_count - 1);
  1129. for (j = 0; j < color_count; j++) {
  1130. if (st->codec->codec_id == AV_CODEC_ID_CINEPAK){
  1131. r = g = b = color_count - 1 - color_index;
  1132. } else
  1133. r = g = b = color_index;
  1134. sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
  1135. color_index -= color_dec;
  1136. if (color_index < 0)
  1137. color_index = 0;
  1138. }
  1139. } else if (color_table_id) {
  1140. const uint8_t *color_table;
  1141. /* if flag bit 3 is set, use the default palette */
  1142. color_count = 1 << color_depth;
  1143. if (color_depth == 2)
  1144. color_table = ff_qt_default_palette_4;
  1145. else if (color_depth == 4)
  1146. color_table = ff_qt_default_palette_16;
  1147. else
  1148. color_table = ff_qt_default_palette_256;
  1149. for (j = 0; j < color_count; j++) {
  1150. r = color_table[j * 3 + 0];
  1151. g = color_table[j * 3 + 1];
  1152. b = color_table[j * 3 + 2];
  1153. sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
  1154. }
  1155. } else {
  1156. /* load the palette from the file */
  1157. color_start = avio_rb32(pb);
  1158. color_count = avio_rb16(pb);
  1159. color_end = avio_rb16(pb);
  1160. if ((color_start <= 255) && (color_end <= 255)) {
  1161. for (j = color_start; j <= color_end; j++) {
  1162. /* each A, R, G, or B component is 16 bits;
  1163. * only use the top 8 bits */
  1164. a = avio_r8(pb);
  1165. avio_r8(pb);
  1166. r = avio_r8(pb);
  1167. avio_r8(pb);
  1168. g = avio_r8(pb);
  1169. avio_r8(pb);
  1170. b = avio_r8(pb);
  1171. avio_r8(pb);
  1172. sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
  1173. }
  1174. }
  1175. }
  1176. sc->has_palette = 1;
  1177. }
  1178. }
  1179. static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
  1180. AVStream *st, MOVStreamContext *sc)
  1181. {
  1182. int bits_per_sample, flags;
  1183. uint16_t version = avio_rb16(pb);
  1184. AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
  1185. avio_rb16(pb); /* revision level */
  1186. avio_rb32(pb); /* vendor */
  1187. st->codec->channels = avio_rb16(pb); /* channel count */
  1188. st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  1189. av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
  1190. sc->audio_cid = avio_rb16(pb);
  1191. avio_rb16(pb); /* packet size = 0 */
  1192. st->codec->sample_rate = ((avio_rb32(pb) >> 16));
  1193. // Read QT version 1 fields. In version 0 these do not exist.
  1194. av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
  1195. if (!c->isom ||
  1196. (compatible_brands && strstr(compatible_brands->value, "qt "))) {
  1197. if (version == 1) {
  1198. sc->samples_per_frame = avio_rb32(pb);
  1199. avio_rb32(pb); /* bytes per packet */
  1200. sc->bytes_per_frame = avio_rb32(pb);
  1201. avio_rb32(pb); /* bytes per sample */
  1202. } else if (version == 2) {
  1203. avio_rb32(pb); /* sizeof struct only */
  1204. st->codec->sample_rate = av_int2double(avio_rb64(pb));
  1205. st->codec->channels = avio_rb32(pb);
  1206. avio_rb32(pb); /* always 0x7F000000 */
  1207. st->codec->bits_per_coded_sample = avio_rb32(pb);
  1208. flags = avio_rb32(pb); /* lpcm format specific flag */
  1209. sc->bytes_per_frame = avio_rb32(pb);
  1210. sc->samples_per_frame = avio_rb32(pb);
  1211. if (st->codec->codec_tag == MKTAG('l','p','c','m'))
  1212. st->codec->codec_id =
  1213. ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
  1214. flags);
  1215. }
  1216. }
  1217. switch (st->codec->codec_id) {
  1218. case AV_CODEC_ID_PCM_S8:
  1219. case AV_CODEC_ID_PCM_U8:
  1220. if (st->codec->bits_per_coded_sample == 16)
  1221. st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
  1222. break;
  1223. case AV_CODEC_ID_PCM_S16LE:
  1224. case AV_CODEC_ID_PCM_S16BE:
  1225. if (st->codec->bits_per_coded_sample == 8)
  1226. st->codec->codec_id = AV_CODEC_ID_PCM_S8;
  1227. else if (st->codec->bits_per_coded_sample == 24)
  1228. st->codec->codec_id =
  1229. st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1230. AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  1231. break;
  1232. /* set values for old format before stsd version 1 appeared */
  1233. case AV_CODEC_ID_MACE3:
  1234. sc->samples_per_frame = 6;
  1235. sc->bytes_per_frame = 2 * st->codec->channels;
  1236. break;
  1237. case AV_CODEC_ID_MACE6:
  1238. sc->samples_per_frame = 6;
  1239. sc->bytes_per_frame = 1 * st->codec->channels;
  1240. break;
  1241. case AV_CODEC_ID_ADPCM_IMA_QT:
  1242. sc->samples_per_frame = 64;
  1243. sc->bytes_per_frame = 34 * st->codec->channels;
  1244. break;
  1245. case AV_CODEC_ID_GSM:
  1246. sc->samples_per_frame = 160;
  1247. sc->bytes_per_frame = 33;
  1248. break;
  1249. default:
  1250. break;
  1251. }
  1252. bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
  1253. if (bits_per_sample) {
  1254. st->codec->bits_per_coded_sample = bits_per_sample;
  1255. sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
  1256. }
  1257. }
  1258. static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
  1259. AVStream *st, MOVStreamContext *sc,
  1260. int size)
  1261. {
  1262. // ttxt stsd contains display flags, justification, background
  1263. // color, fonts, and default styles, so fake an atom to read it
  1264. MOVAtom fake_atom = { .size = size };
  1265. // mp4s contains a regular esds atom
  1266. if (st->codec->codec_tag != AV_RL32("mp4s"))
  1267. mov_read_glbl(c, pb, fake_atom);
  1268. st->codec->width = sc->width;
  1269. st->codec->height = sc->height;
  1270. }
  1271. static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
  1272. AVStream *st, MOVStreamContext *sc,
  1273. int size)
  1274. {
  1275. if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
  1276. if (ff_alloc_extradata(st->codec, size))
  1277. return AVERROR(ENOMEM);
  1278. avio_read(pb, st->codec->extradata, size);
  1279. if (size > 16) {
  1280. MOVStreamContext *tmcd_ctx = st->priv_data;
  1281. int val;
  1282. val = AV_RB32(st->codec->extradata + 4);
  1283. tmcd_ctx->tmcd_flags = val;
  1284. if (val & 1)
  1285. st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
  1286. st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
  1287. st->codec->time_base.num = 1;
  1288. }
  1289. } else {
  1290. /* other codec type, just skip (rtp, mp4s ...) */
  1291. avio_skip(pb, size);
  1292. }
  1293. return 0;
  1294. }
  1295. static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
  1296. AVStream *st, MOVStreamContext *sc)
  1297. {
  1298. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1299. !st->codec->sample_rate && sc->time_scale > 1)
  1300. st->codec->sample_rate = sc->time_scale;
  1301. /* special codec parameters handling */
  1302. switch (st->codec->codec_id) {
  1303. #if CONFIG_DV_DEMUXER
  1304. case AV_CODEC_ID_DVAUDIO:
  1305. c->dv_fctx = avformat_alloc_context();
  1306. c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
  1307. if (!c->dv_demux) {
  1308. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  1309. return AVERROR(ENOMEM);
  1310. }
  1311. sc->dv_audio_container = 1;
  1312. st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
  1313. break;
  1314. #endif
  1315. /* no ifdef since parameters are always those */
  1316. case AV_CODEC_ID_QCELP:
  1317. st->codec->channels = 1;
  1318. // force sample rate for qcelp when not stored in mov
  1319. if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
  1320. st->codec->sample_rate = 8000;
  1321. break;
  1322. case AV_CODEC_ID_AMR_NB:
  1323. st->codec->channels = 1;
  1324. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  1325. st->codec->sample_rate = 8000;
  1326. break;
  1327. case AV_CODEC_ID_AMR_WB:
  1328. st->codec->channels = 1;
  1329. st->codec->sample_rate = 16000;
  1330. break;
  1331. case AV_CODEC_ID_MP2:
  1332. case AV_CODEC_ID_MP3:
  1333. /* force type after stsd for m1a hdlr */
  1334. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1335. st->need_parsing = AVSTREAM_PARSE_FULL;
  1336. break;
  1337. case AV_CODEC_ID_GSM:
  1338. case AV_CODEC_ID_ADPCM_MS:
  1339. case AV_CODEC_ID_ADPCM_IMA_WAV:
  1340. case AV_CODEC_ID_ILBC:
  1341. case AV_CODEC_ID_MACE3:
  1342. case AV_CODEC_ID_MACE6:
  1343. case AV_CODEC_ID_QDM2:
  1344. st->codec->block_align = sc->bytes_per_frame;
  1345. break;
  1346. case AV_CODEC_ID_ALAC:
  1347. if (st->codec->extradata_size == 36) {
  1348. st->codec->channels = AV_RB8 (st->codec->extradata + 21);
  1349. st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
  1350. }
  1351. break;
  1352. case AV_CODEC_ID_AC3:
  1353. st->need_parsing = AVSTREAM_PARSE_FULL;
  1354. break;
  1355. case AV_CODEC_ID_MPEG1VIDEO:
  1356. st->need_parsing = AVSTREAM_PARSE_FULL;
  1357. break;
  1358. case AV_CODEC_ID_VC1:
  1359. st->need_parsing = AVSTREAM_PARSE_FULL;
  1360. break;
  1361. default:
  1362. break;
  1363. }
  1364. return 0;
  1365. }
  1366. static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
  1367. int codec_tag, int format,
  1368. int size)
  1369. {
  1370. int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1371. if (codec_tag &&
  1372. (codec_tag != format &&
  1373. (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
  1374. : codec_tag != MKTAG('j','p','e','g')))) {
  1375. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  1376. * export it as a separate AVStream but this needs a few changes
  1377. * in the MOV demuxer, patch welcome. */
  1378. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  1379. avio_skip(pb, size);
  1380. return 1;
  1381. }
  1382. if ( codec_tag == AV_RL32("avc1") ||
  1383. codec_tag == AV_RL32("hvc1") ||
  1384. codec_tag == AV_RL32("hev1")
  1385. )
  1386. av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
  1387. return 0;
  1388. }
  1389. int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
  1390. {
  1391. AVStream *st;
  1392. MOVStreamContext *sc;
  1393. int pseudo_stream_id;
  1394. if (c->fc->nb_streams < 1)
  1395. return 0;
  1396. st = c->fc->streams[c->fc->nb_streams-1];
  1397. sc = st->priv_data;
  1398. for (pseudo_stream_id = 0;
  1399. pseudo_stream_id < entries && !pb->eof_reached;
  1400. pseudo_stream_id++) {
  1401. //Parsing Sample description table
  1402. enum AVCodecID id;
  1403. int ret, dref_id = 1;
  1404. MOVAtom a = { AV_RL32("stsd") };
  1405. int64_t start_pos = avio_tell(pb);
  1406. int64_t size = avio_rb32(pb); /* size */
  1407. uint32_t format = avio_rl32(pb); /* data format */
  1408. if (size >= 16) {
  1409. avio_rb32(pb); /* reserved */
  1410. avio_rb16(pb); /* reserved */
  1411. dref_id = avio_rb16(pb);
  1412. }else if (size <= 7){
  1413. av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
  1414. return AVERROR_INVALIDDATA;
  1415. }
  1416. if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
  1417. size - (avio_tell(pb) - start_pos)))
  1418. continue;
  1419. sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
  1420. sc->dref_id= dref_id;
  1421. id = mov_codec_id(st, format);
  1422. av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
  1423. (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  1424. (format >> 24) & 0xff, st->codec->codec_type);
  1425. if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
  1426. st->codec->codec_id = id;
  1427. mov_parse_stsd_video(c, pb, st, sc);
  1428. } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
  1429. st->codec->codec_id = id;
  1430. mov_parse_stsd_audio(c, pb, st, sc);
  1431. } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
  1432. st->codec->codec_id = id;
  1433. mov_parse_stsd_subtitle(c, pb, st, sc,
  1434. size - (avio_tell(pb) - start_pos));
  1435. } else {
  1436. ret = mov_parse_stsd_data(c, pb, st, sc,
  1437. size - (avio_tell(pb) - start_pos));
  1438. if (ret < 0)
  1439. return ret;
  1440. }
  1441. /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
  1442. a.size = size - (avio_tell(pb) - start_pos);
  1443. if (a.size > 8) {
  1444. if ((ret = mov_read_default(c, pb, a)) < 0)
  1445. return ret;
  1446. } else if (a.size > 0)
  1447. avio_skip(pb, a.size);
  1448. }
  1449. if (pb->eof_reached)
  1450. return AVERROR_EOF;
  1451. return mov_finalize_stsd_codec(c, pb, st, sc);
  1452. }
  1453. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1454. {
  1455. int entries;
  1456. avio_r8(pb); /* version */
  1457. avio_rb24(pb); /* flags */
  1458. entries = avio_rb32(pb);
  1459. return ff_mov_read_stsd_entries(c, pb, entries);
  1460. }
  1461. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1462. {
  1463. AVStream *st;
  1464. MOVStreamContext *sc;
  1465. unsigned int i, entries;
  1466. if (c->fc->nb_streams < 1)
  1467. return 0;
  1468. st = c->fc->streams[c->fc->nb_streams-1];
  1469. sc = st->priv_data;
  1470. avio_r8(pb); /* version */
  1471. avio_rb24(pb); /* flags */
  1472. entries = avio_rb32(pb);
  1473. av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1474. if (!entries)
  1475. return 0;
  1476. if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
  1477. return AVERROR_INVALIDDATA;
  1478. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  1479. if (!sc->stsc_data)
  1480. return AVERROR(ENOMEM);
  1481. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1482. sc->stsc_data[i].first = avio_rb32(pb);
  1483. sc->stsc_data[i].count = avio_rb32(pb);
  1484. sc->stsc_data[i].id = avio_rb32(pb);
  1485. }
  1486. sc->stsc_count = i;
  1487. if (pb->eof_reached)
  1488. return AVERROR_EOF;
  1489. return 0;
  1490. }
  1491. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1492. {
  1493. AVStream *st;
  1494. MOVStreamContext *sc;
  1495. unsigned i, entries;
  1496. if (c->fc->nb_streams < 1)
  1497. return 0;
  1498. st = c->fc->streams[c->fc->nb_streams-1];
  1499. sc = st->priv_data;
  1500. avio_rb32(pb); // version + flags
  1501. entries = avio_rb32(pb);
  1502. if (entries >= UINT_MAX / sizeof(*sc->stps_data))
  1503. return AVERROR_INVALIDDATA;
  1504. sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
  1505. if (!sc->stps_data)
  1506. return AVERROR(ENOMEM);
  1507. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1508. sc->stps_data[i] = avio_rb32(pb);
  1509. //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
  1510. }
  1511. sc->stps_count = i;
  1512. if (pb->eof_reached)
  1513. return AVERROR_EOF;
  1514. return 0;
  1515. }
  1516. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1517. {
  1518. AVStream *st;
  1519. MOVStreamContext *sc;
  1520. unsigned int i, entries;
  1521. if (c->fc->nb_streams < 1)
  1522. return 0;
  1523. st = c->fc->streams[c->fc->nb_streams-1];
  1524. sc = st->priv_data;
  1525. avio_r8(pb); /* version */
  1526. avio_rb24(pb); /* flags */
  1527. entries = avio_rb32(pb);
  1528. av_dlog(c->fc, "keyframe_count = %d\n", entries);
  1529. if (!entries)
  1530. {
  1531. sc->keyframe_absent = 1;
  1532. if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  1533. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  1534. return 0;
  1535. }
  1536. if (entries >= UINT_MAX / sizeof(int))
  1537. return AVERROR_INVALIDDATA;
  1538. sc->keyframes = av_malloc(entries * sizeof(int));
  1539. if (!sc->keyframes)
  1540. return AVERROR(ENOMEM);
  1541. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1542. sc->keyframes[i] = avio_rb32(pb);
  1543. //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
  1544. }
  1545. sc->keyframe_count = i;
  1546. if (pb->eof_reached)
  1547. return AVERROR_EOF;
  1548. return 0;
  1549. }
  1550. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1551. {
  1552. AVStream *st;
  1553. MOVStreamContext *sc;
  1554. unsigned int i, entries, sample_size, field_size, num_bytes;
  1555. GetBitContext gb;
  1556. unsigned char* buf;
  1557. if (c->fc->nb_streams < 1)
  1558. return 0;
  1559. st = c->fc->streams[c->fc->nb_streams-1];
  1560. sc = st->priv_data;
  1561. avio_r8(pb); /* version */
  1562. avio_rb24(pb); /* flags */
  1563. if (atom.type == MKTAG('s','t','s','z')) {
  1564. sample_size = avio_rb32(pb);
  1565. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  1566. sc->sample_size = sample_size;
  1567. sc->stsz_sample_size = sample_size;
  1568. field_size = 32;
  1569. } else {
  1570. sample_size = 0;
  1571. avio_rb24(pb); /* reserved */
  1572. field_size = avio_r8(pb);
  1573. }
  1574. entries = avio_rb32(pb);
  1575. av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  1576. sc->sample_count = entries;
  1577. if (sample_size)
  1578. return 0;
  1579. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  1580. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  1581. return AVERROR_INVALIDDATA;
  1582. }
  1583. if (!entries)
  1584. return 0;
  1585. if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
  1586. return AVERROR_INVALIDDATA;
  1587. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1588. if (!sc->sample_sizes)
  1589. return AVERROR(ENOMEM);
  1590. num_bytes = (entries*field_size+4)>>3;
  1591. buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
  1592. if (!buf) {
  1593. av_freep(&sc->sample_sizes);
  1594. return AVERROR(ENOMEM);
  1595. }
  1596. if (avio_read(pb, buf, num_bytes) < num_bytes) {
  1597. av_freep(&sc->sample_sizes);
  1598. av_free(buf);
  1599. return AVERROR_INVALIDDATA;
  1600. }
  1601. init_get_bits(&gb, buf, 8*num_bytes);
  1602. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1603. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  1604. sc->data_size += sc->sample_sizes[i];
  1605. }
  1606. sc->sample_count = i;
  1607. if (pb->eof_reached)
  1608. return AVERROR_EOF;
  1609. av_free(buf);
  1610. return 0;
  1611. }
  1612. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1613. {
  1614. AVStream *st;
  1615. MOVStreamContext *sc;
  1616. unsigned int i, entries;
  1617. int64_t duration=0;
  1618. int64_t total_sample_count=0;
  1619. if (c->fc->nb_streams < 1)
  1620. return 0;
  1621. st = c->fc->streams[c->fc->nb_streams-1];
  1622. sc = st->priv_data;
  1623. avio_r8(pb); /* version */
  1624. avio_rb24(pb); /* flags */
  1625. entries = avio_rb32(pb);
  1626. av_dlog(c->fc, "track[%i].stts.entries = %i\n",
  1627. c->fc->nb_streams-1, entries);
  1628. if (entries >= UINT_MAX / sizeof(*sc->stts_data))
  1629. return -1;
  1630. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1631. if (!sc->stts_data)
  1632. return AVERROR(ENOMEM);
  1633. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1634. int sample_duration;
  1635. int sample_count;
  1636. sample_count=avio_rb32(pb);
  1637. sample_duration = avio_rb32(pb);
  1638. /* sample_duration < 0 is invalid based on the spec */
  1639. if (sample_duration < 0) {
  1640. av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration);
  1641. sample_duration = 1;
  1642. }
  1643. if (sample_count < 0) {
  1644. av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
  1645. return AVERROR_INVALIDDATA;
  1646. }
  1647. sc->stts_data[i].count= sample_count;
  1648. sc->stts_data[i].duration= sample_duration;
  1649. av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
  1650. sample_count, sample_duration);
  1651. duration+=(int64_t)sample_duration*sample_count;
  1652. total_sample_count+=sample_count;
  1653. }
  1654. sc->stts_count = i;
  1655. if (pb->eof_reached)
  1656. return AVERROR_EOF;
  1657. st->nb_frames= total_sample_count;
  1658. if (duration)
  1659. st->duration= duration;
  1660. sc->track_end = duration;
  1661. return 0;
  1662. }
  1663. static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
  1664. {
  1665. if (duration < 0) {
  1666. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  1667. }
  1668. }
  1669. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1670. {
  1671. AVStream *st;
  1672. MOVStreamContext *sc;
  1673. unsigned int i, entries;
  1674. if (c->fc->nb_streams < 1)
  1675. return 0;
  1676. st = c->fc->streams[c->fc->nb_streams-1];
  1677. sc = st->priv_data;
  1678. avio_r8(pb); /* version */
  1679. avio_rb24(pb); /* flags */
  1680. entries = avio_rb32(pb);
  1681. av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  1682. if (!entries)
  1683. return 0;
  1684. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1685. return AVERROR_INVALIDDATA;
  1686. sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
  1687. if (!sc->ctts_data)
  1688. return AVERROR(ENOMEM);
  1689. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1690. int count =avio_rb32(pb);
  1691. int duration =avio_rb32(pb);
  1692. sc->ctts_data[i].count = count;
  1693. sc->ctts_data[i].duration= duration;
  1694. av_dlog(c->fc, "count=%d, duration=%d\n",
  1695. count, duration);
  1696. if (FFABS(duration) > (1<<28) && i+2<entries) {
  1697. av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
  1698. av_freep(&sc->ctts_data);
  1699. sc->ctts_count = 0;
  1700. return 0;
  1701. }
  1702. if (i+2<entries)
  1703. mov_update_dts_shift(sc, duration);
  1704. }
  1705. sc->ctts_count = i;
  1706. if (pb->eof_reached)
  1707. return AVERROR_EOF;
  1708. av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
  1709. return 0;
  1710. }
  1711. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1712. {
  1713. AVStream *st;
  1714. MOVStreamContext *sc;
  1715. unsigned int i, entries;
  1716. uint8_t version;
  1717. uint32_t grouping_type;
  1718. if (c->fc->nb_streams < 1)
  1719. return 0;
  1720. st = c->fc->streams[c->fc->nb_streams-1];
  1721. sc = st->priv_data;
  1722. version = avio_r8(pb); /* version */
  1723. avio_rb24(pb); /* flags */
  1724. grouping_type = avio_rl32(pb);
  1725. if (grouping_type != MKTAG( 'r','a','p',' '))
  1726. return 0; /* only support 'rap ' grouping */
  1727. if (version == 1)
  1728. avio_rb32(pb); /* grouping_type_parameter */
  1729. entries = avio_rb32(pb);
  1730. if (!entries)
  1731. return 0;
  1732. if (entries >= UINT_MAX / sizeof(*sc->rap_group))
  1733. return AVERROR_INVALIDDATA;
  1734. sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
  1735. if (!sc->rap_group)
  1736. return AVERROR(ENOMEM);
  1737. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1738. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  1739. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  1740. }
  1741. sc->rap_group_count = i;
  1742. return pb->eof_reached ? AVERROR_EOF : 0;
  1743. }
  1744. static void mov_build_index(MOVContext *mov, AVStream *st)
  1745. {
  1746. MOVStreamContext *sc = st->priv_data;
  1747. int64_t current_offset;
  1748. int64_t current_dts = 0;
  1749. unsigned int stts_index = 0;
  1750. unsigned int stsc_index = 0;
  1751. unsigned int stss_index = 0;
  1752. unsigned int stps_index = 0;
  1753. unsigned int i, j;
  1754. uint64_t stream_size = 0;
  1755. /* adjust first dts according to edit list */
  1756. if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
  1757. if (sc->empty_duration)
  1758. sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
  1759. sc->time_offset = sc->start_time - sc->empty_duration;
  1760. current_dts = -sc->time_offset;
  1761. if (sc->ctts_count>0 && sc->stts_count>0 &&
  1762. sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
  1763. /* more than 16 frames delay, dts are likely wrong
  1764. this happens with files created by iMovie */
  1765. sc->wrong_dts = 1;
  1766. st->codec->has_b_frames = 1;
  1767. }
  1768. }
  1769. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1770. if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1771. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1772. unsigned int current_sample = 0;
  1773. unsigned int stts_sample = 0;
  1774. unsigned int sample_size;
  1775. unsigned int distance = 0;
  1776. unsigned int rap_group_index = 0;
  1777. unsigned int rap_group_sample = 0;
  1778. int rap_group_present = sc->rap_group_count && sc->rap_group;
  1779. int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
  1780. current_dts -= sc->dts_shift;
  1781. if (!sc->sample_count || st->nb_index_entries)
  1782. return;
  1783. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  1784. return;
  1785. if (av_reallocp_array(&st->index_entries,
  1786. st->nb_index_entries + sc->sample_count,
  1787. sizeof(*st->index_entries)) < 0) {
  1788. st->nb_index_entries = 0;
  1789. return;
  1790. }
  1791. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  1792. for (i = 0; i < sc->chunk_count; i++) {
  1793. int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
  1794. current_offset = sc->chunk_offsets[i];
  1795. while (stsc_index + 1 < sc->stsc_count &&
  1796. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1797. stsc_index++;
  1798. if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
  1799. sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
  1800. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
  1801. sc->stsz_sample_size = sc->sample_size;
  1802. }
  1803. if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
  1804. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
  1805. sc->stsz_sample_size = sc->sample_size;
  1806. }
  1807. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1808. int keyframe = 0;
  1809. if (current_sample >= sc->sample_count) {
  1810. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1811. return;
  1812. }
  1813. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  1814. keyframe = 1;
  1815. if (stss_index + 1 < sc->keyframe_count)
  1816. stss_index++;
  1817. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  1818. keyframe = 1;
  1819. if (stps_index + 1 < sc->stps_count)
  1820. stps_index++;
  1821. }
  1822. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  1823. if (sc->rap_group[rap_group_index].index > 0)
  1824. keyframe = 1;
  1825. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  1826. rap_group_sample = 0;
  1827. rap_group_index++;
  1828. }
  1829. }
  1830. if (keyframe)
  1831. distance = 0;
  1832. sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
  1833. if (sc->pseudo_stream_id == -1 ||
  1834. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  1835. AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  1836. e->pos = current_offset;
  1837. e->timestamp = current_dts;
  1838. e->size = sample_size;
  1839. e->min_distance = distance;
  1840. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  1841. av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1842. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  1843. current_offset, current_dts, sample_size, distance, keyframe);
  1844. }
  1845. current_offset += sample_size;
  1846. stream_size += sample_size;
  1847. current_dts += sc->stts_data[stts_index].duration;
  1848. distance++;
  1849. stts_sample++;
  1850. current_sample++;
  1851. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  1852. stts_sample = 0;
  1853. stts_index++;
  1854. }
  1855. }
  1856. }
  1857. if (st->duration > 0)
  1858. st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
  1859. } else {
  1860. unsigned chunk_samples, total = 0;
  1861. // compute total chunk count
  1862. for (i = 0; i < sc->stsc_count; i++) {
  1863. unsigned count, chunk_count;
  1864. chunk_samples = sc->stsc_data[i].count;
  1865. if (i != sc->stsc_count - 1 &&
  1866. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  1867. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  1868. return;
  1869. }
  1870. if (sc->samples_per_frame >= 160) { // gsm
  1871. count = chunk_samples / sc->samples_per_frame;
  1872. } else if (sc->samples_per_frame > 1) {
  1873. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  1874. count = (chunk_samples+samples-1) / samples;
  1875. } else {
  1876. count = (chunk_samples+1023) / 1024;
  1877. }
  1878. if (i < sc->stsc_count - 1)
  1879. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  1880. else
  1881. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  1882. total += chunk_count * count;
  1883. }
  1884. av_dlog(mov->fc, "chunk count %d\n", total);
  1885. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  1886. return;
  1887. if (av_reallocp_array(&st->index_entries,
  1888. st->nb_index_entries + total,
  1889. sizeof(*st->index_entries)) < 0) {
  1890. st->nb_index_entries = 0;
  1891. return;
  1892. }
  1893. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  1894. // populate index
  1895. for (i = 0; i < sc->chunk_count; i++) {
  1896. current_offset = sc->chunk_offsets[i];
  1897. if (stsc_index + 1 < sc->stsc_count &&
  1898. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1899. stsc_index++;
  1900. chunk_samples = sc->stsc_data[stsc_index].count;
  1901. while (chunk_samples > 0) {
  1902. AVIndexEntry *e;
  1903. unsigned size, samples;
  1904. if (sc->samples_per_frame >= 160) { // gsm
  1905. samples = sc->samples_per_frame;
  1906. size = sc->bytes_per_frame;
  1907. } else {
  1908. if (sc->samples_per_frame > 1) {
  1909. samples = FFMIN((1024 / sc->samples_per_frame)*
  1910. sc->samples_per_frame, chunk_samples);
  1911. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  1912. } else {
  1913. samples = FFMIN(1024, chunk_samples);
  1914. size = samples * sc->sample_size;
  1915. }
  1916. }
  1917. if (st->nb_index_entries >= total) {
  1918. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  1919. return;
  1920. }
  1921. e = &st->index_entries[st->nb_index_entries++];
  1922. e->pos = current_offset;
  1923. e->timestamp = current_dts;
  1924. e->size = size;
  1925. e->min_distance = 0;
  1926. e->flags = AVINDEX_KEYFRAME;
  1927. av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  1928. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  1929. size, samples);
  1930. current_offset += size;
  1931. current_dts += samples;
  1932. chunk_samples -= samples;
  1933. }
  1934. }
  1935. }
  1936. }
  1937. static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
  1938. AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
  1939. {
  1940. /* try relative path, we do not try the absolute because it can leak information about our
  1941. system to an attacker */
  1942. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  1943. char filename[1024];
  1944. const char *src_path;
  1945. int i, l;
  1946. /* find a source dir */
  1947. src_path = strrchr(src, '/');
  1948. if (src_path)
  1949. src_path++;
  1950. else
  1951. src_path = src;
  1952. /* find a next level down to target */
  1953. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  1954. if (ref->path[l] == '/') {
  1955. if (i == ref->nlvl_to - 1)
  1956. break;
  1957. else
  1958. i++;
  1959. }
  1960. /* compose filename if next level down to target was found */
  1961. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  1962. memcpy(filename, src, src_path - src);
  1963. filename[src_path - src] = 0;
  1964. for (i = 1; i < ref->nlvl_from; i++)
  1965. av_strlcat(filename, "../", 1024);
  1966. av_strlcat(filename, ref->path + l + 1, 1024);
  1967. if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
  1968. return 0;
  1969. }
  1970. } else if (use_absolute_path) {
  1971. av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
  1972. "this is a possible security issue\n");
  1973. if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
  1974. return 0;
  1975. }
  1976. return AVERROR(ENOENT);
  1977. }
  1978. static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
  1979. {
  1980. if (sc->time_scale <= 0) {
  1981. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
  1982. sc->time_scale = c->time_scale;
  1983. if (sc->time_scale <= 0)
  1984. sc->time_scale = 1;
  1985. }
  1986. }
  1987. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1988. {
  1989. AVStream *st;
  1990. MOVStreamContext *sc;
  1991. int ret;
  1992. st = avformat_new_stream(c->fc, NULL);
  1993. if (!st) return AVERROR(ENOMEM);
  1994. st->id = c->fc->nb_streams;
  1995. sc = av_mallocz(sizeof(MOVStreamContext));
  1996. if (!sc) return AVERROR(ENOMEM);
  1997. st->priv_data = sc;
  1998. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1999. sc->ffindex = st->index;
  2000. if ((ret = mov_read_default(c, pb, atom)) < 0)
  2001. return ret;
  2002. /* sanity checks */
  2003. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  2004. (!sc->sample_size && !sc->sample_count))) {
  2005. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  2006. st->index);
  2007. return 0;
  2008. }
  2009. fix_timescale(c, sc);
  2010. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  2011. mov_build_index(c, st);
  2012. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  2013. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  2014. if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
  2015. c->use_absolute_path, c->fc) < 0)
  2016. av_log(c->fc, AV_LOG_ERROR,
  2017. "stream %d, error opening alias: path='%s', dir='%s', "
  2018. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  2019. st->index, dref->path, dref->dir, dref->filename,
  2020. dref->volume, dref->nlvl_from, dref->nlvl_to);
  2021. } else {
  2022. sc->pb = c->fc->pb;
  2023. sc->pb_is_copied = 1;
  2024. }
  2025. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  2026. if (!st->sample_aspect_ratio.num &&
  2027. (st->codec->width != sc->width || st->codec->height != sc->height)) {
  2028. st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
  2029. ((double)st->codec->width * sc->height), INT_MAX);
  2030. }
  2031. if (st->duration > 0)
  2032. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  2033. sc->time_scale*st->nb_frames, st->duration, INT_MAX);
  2034. #if FF_API_R_FRAME_RATE
  2035. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  2036. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  2037. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  2038. #endif
  2039. }
  2040. // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  2041. if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
  2042. TAG_IS_AVCI(st->codec->codec_tag)) {
  2043. ret = ff_generate_avci_extradata(st);
  2044. if (ret < 0)
  2045. return ret;
  2046. }
  2047. switch (st->codec->codec_id) {
  2048. #if CONFIG_H261_DECODER
  2049. case AV_CODEC_ID_H261:
  2050. #endif
  2051. #if CONFIG_H263_DECODER
  2052. case AV_CODEC_ID_H263:
  2053. #endif
  2054. #if CONFIG_MPEG4_DECODER
  2055. case AV_CODEC_ID_MPEG4:
  2056. #endif
  2057. st->codec->width = 0; /* let decoder init width/height */
  2058. st->codec->height= 0;
  2059. break;
  2060. }
  2061. /* Do not need those anymore. */
  2062. av_freep(&sc->chunk_offsets);
  2063. av_freep(&sc->stsc_data);
  2064. av_freep(&sc->sample_sizes);
  2065. av_freep(&sc->keyframes);
  2066. av_freep(&sc->stts_data);
  2067. av_freep(&sc->stps_data);
  2068. av_freep(&sc->rap_group);
  2069. return 0;
  2070. }
  2071. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2072. {
  2073. int ret;
  2074. c->itunes_metadata = 1;
  2075. ret = mov_read_default(c, pb, atom);
  2076. c->itunes_metadata = 0;
  2077. return ret;
  2078. }
  2079. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2080. {
  2081. while (atom.size > 8) {
  2082. uint32_t tag = avio_rl32(pb);
  2083. atom.size -= 4;
  2084. if (tag == MKTAG('h','d','l','r')) {
  2085. avio_seek(pb, -8, SEEK_CUR);
  2086. atom.size += 8;
  2087. return mov_read_default(c, pb, atom);
  2088. }
  2089. }
  2090. return 0;
  2091. }
  2092. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2093. {
  2094. int i;
  2095. int width;
  2096. int height;
  2097. int64_t disp_transform[2];
  2098. int display_matrix[3][2];
  2099. AVStream *st;
  2100. MOVStreamContext *sc;
  2101. int version;
  2102. int flags;
  2103. if (c->fc->nb_streams < 1)
  2104. return 0;
  2105. st = c->fc->streams[c->fc->nb_streams-1];
  2106. sc = st->priv_data;
  2107. version = avio_r8(pb);
  2108. flags = avio_rb24(pb);
  2109. st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  2110. if (version == 1) {
  2111. avio_rb64(pb);
  2112. avio_rb64(pb);
  2113. } else {
  2114. avio_rb32(pb); /* creation time */
  2115. avio_rb32(pb); /* modification time */
  2116. }
  2117. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  2118. avio_rb32(pb); /* reserved */
  2119. /* highlevel (considering edits) duration in movie timebase */
  2120. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  2121. avio_rb32(pb); /* reserved */
  2122. avio_rb32(pb); /* reserved */
  2123. avio_rb16(pb); /* layer */
  2124. avio_rb16(pb); /* alternate group */
  2125. avio_rb16(pb); /* volume */
  2126. avio_rb16(pb); /* reserved */
  2127. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  2128. // they're kept in fixed point format through all calculations
  2129. // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
  2130. for (i = 0; i < 3; i++) {
  2131. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  2132. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  2133. avio_rb32(pb); // 2.30 fixed point (not used)
  2134. }
  2135. width = avio_rb32(pb); // 16.16 fixed point track width
  2136. height = avio_rb32(pb); // 16.16 fixed point track height
  2137. sc->width = width >> 16;
  2138. sc->height = height >> 16;
  2139. //Assign clockwise rotate values based on transform matrix so that
  2140. //we can compensate for iPhone orientation during capture.
  2141. if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
  2142. av_dict_set(&st->metadata, "rotate", "90", 0);
  2143. }
  2144. if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
  2145. av_dict_set(&st->metadata, "rotate", "180", 0);
  2146. }
  2147. if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
  2148. av_dict_set(&st->metadata, "rotate", "270", 0);
  2149. }
  2150. // transform the display width/height according to the matrix
  2151. // skip this if the display matrix is the default identity matrix
  2152. // or if it is rotating the picture, ex iPhone 3GS
  2153. // to keep the same scale, use [width height 1<<16]
  2154. if (width && height &&
  2155. ((display_matrix[0][0] != 65536 ||
  2156. display_matrix[1][1] != 65536) &&
  2157. !display_matrix[0][1] &&
  2158. !display_matrix[1][0] &&
  2159. !display_matrix[2][0] && !display_matrix[2][1])) {
  2160. for (i = 0; i < 2; i++)
  2161. disp_transform[i] =
  2162. (int64_t) width * display_matrix[0][i] +
  2163. (int64_t) height * display_matrix[1][i] +
  2164. ((int64_t) display_matrix[2][i] << 16);
  2165. //sample aspect ratio is new width/height divided by old width/height
  2166. st->sample_aspect_ratio = av_d2q(
  2167. ((double) disp_transform[0] * height) /
  2168. ((double) disp_transform[1] * width), INT_MAX);
  2169. }
  2170. return 0;
  2171. }
  2172. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2173. {
  2174. MOVFragment *frag = &c->fragment;
  2175. MOVTrackExt *trex = NULL;
  2176. int flags, track_id, i;
  2177. avio_r8(pb); /* version */
  2178. flags = avio_rb24(pb);
  2179. track_id = avio_rb32(pb);
  2180. if (!track_id)
  2181. return AVERROR_INVALIDDATA;
  2182. frag->track_id = track_id;
  2183. for (i = 0; i < c->trex_count; i++)
  2184. if (c->trex_data[i].track_id == frag->track_id) {
  2185. trex = &c->trex_data[i];
  2186. break;
  2187. }
  2188. if (!trex) {
  2189. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  2190. return AVERROR_INVALIDDATA;
  2191. }
  2192. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  2193. avio_rb64(pb) : frag->moof_offset;
  2194. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  2195. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  2196. avio_rb32(pb) : trex->duration;
  2197. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  2198. avio_rb32(pb) : trex->size;
  2199. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  2200. avio_rb32(pb) : trex->flags;
  2201. av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
  2202. return 0;
  2203. }
  2204. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2205. {
  2206. c->chapter_track = avio_rb32(pb);
  2207. return 0;
  2208. }
  2209. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2210. {
  2211. MOVTrackExt *trex;
  2212. int err;
  2213. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  2214. return AVERROR_INVALIDDATA;
  2215. if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  2216. sizeof(*c->trex_data))) < 0) {
  2217. c->trex_count = 0;
  2218. return err;
  2219. }
  2220. c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
  2221. trex = &c->trex_data[c->trex_count++];
  2222. avio_r8(pb); /* version */
  2223. avio_rb24(pb); /* flags */
  2224. trex->track_id = avio_rb32(pb);
  2225. trex->stsd_id = avio_rb32(pb);
  2226. trex->duration = avio_rb32(pb);
  2227. trex->size = avio_rb32(pb);
  2228. trex->flags = avio_rb32(pb);
  2229. return 0;
  2230. }
  2231. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2232. {
  2233. MOVFragment *frag = &c->fragment;
  2234. AVStream *st = NULL;
  2235. MOVStreamContext *sc;
  2236. MOVStts *ctts_data;
  2237. uint64_t offset;
  2238. int64_t dts;
  2239. int data_offset = 0;
  2240. unsigned entries, first_sample_flags = frag->flags;
  2241. int flags, distance, i, found_keyframe = 0, err;
  2242. for (i = 0; i < c->fc->nb_streams; i++) {
  2243. if (c->fc->streams[i]->id == frag->track_id) {
  2244. st = c->fc->streams[i];
  2245. break;
  2246. }
  2247. }
  2248. if (!st) {
  2249. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  2250. return AVERROR_INVALIDDATA;
  2251. }
  2252. sc = st->priv_data;
  2253. if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
  2254. return 0;
  2255. avio_r8(pb); /* version */
  2256. flags = avio_rb24(pb);
  2257. entries = avio_rb32(pb);
  2258. av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
  2259. /* Always assume the presence of composition time offsets.
  2260. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  2261. * 1) in the initial movie, there are no samples.
  2262. * 2) in the first movie fragment, there is only one sample without composition time offset.
  2263. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  2264. if (!sc->ctts_count && sc->sample_count)
  2265. {
  2266. /* Complement ctts table if moov atom doesn't have ctts atom. */
  2267. ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
  2268. if (!ctts_data)
  2269. return AVERROR(ENOMEM);
  2270. sc->ctts_data = ctts_data;
  2271. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  2272. sc->ctts_data[sc->ctts_count].duration = 0;
  2273. sc->ctts_count++;
  2274. }
  2275. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  2276. return AVERROR_INVALIDDATA;
  2277. if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
  2278. sizeof(*sc->ctts_data))) < 0) {
  2279. sc->ctts_count = 0;
  2280. return err;
  2281. }
  2282. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  2283. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  2284. dts = sc->track_end - sc->time_offset;
  2285. offset = frag->base_data_offset + data_offset;
  2286. distance = 0;
  2287. av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
  2288. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2289. unsigned sample_size = frag->size;
  2290. int sample_flags = i ? frag->flags : first_sample_flags;
  2291. unsigned sample_duration = frag->duration;
  2292. int keyframe = 0;
  2293. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  2294. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  2295. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  2296. sc->ctts_data[sc->ctts_count].count = 1;
  2297. sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
  2298. avio_rb32(pb) : 0;
  2299. mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
  2300. sc->ctts_count++;
  2301. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  2302. keyframe = 1;
  2303. else if (!found_keyframe)
  2304. keyframe = found_keyframe =
  2305. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  2306. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  2307. if (keyframe)
  2308. distance = 0;
  2309. av_add_index_entry(st, offset, dts, sample_size, distance,
  2310. keyframe ? AVINDEX_KEYFRAME : 0);
  2311. av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  2312. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  2313. offset, dts, sample_size, distance, keyframe);
  2314. distance++;
  2315. dts += sample_duration;
  2316. offset += sample_size;
  2317. sc->data_size += sample_size;
  2318. }
  2319. if (pb->eof_reached)
  2320. return AVERROR_EOF;
  2321. frag->moof_offset = offset;
  2322. st->duration = sc->track_end = dts + sc->time_offset;
  2323. return 0;
  2324. }
  2325. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  2326. /* like the files created with Adobe Premiere 5.0, for samples see */
  2327. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  2328. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2329. {
  2330. int err;
  2331. if (atom.size < 8)
  2332. return 0; /* continue */
  2333. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  2334. avio_skip(pb, atom.size - 4);
  2335. return 0;
  2336. }
  2337. atom.type = avio_rl32(pb);
  2338. atom.size -= 8;
  2339. if (atom.type != MKTAG('m','d','a','t')) {
  2340. avio_skip(pb, atom.size);
  2341. return 0;
  2342. }
  2343. err = mov_read_mdat(c, pb, atom);
  2344. return err;
  2345. }
  2346. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2347. {
  2348. #if CONFIG_ZLIB
  2349. AVIOContext ctx;
  2350. uint8_t *cmov_data;
  2351. uint8_t *moov_data; /* uncompressed data */
  2352. long cmov_len, moov_len;
  2353. int ret = -1;
  2354. avio_rb32(pb); /* dcom atom */
  2355. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  2356. return AVERROR_INVALIDDATA;
  2357. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  2358. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
  2359. return AVERROR_INVALIDDATA;
  2360. }
  2361. avio_rb32(pb); /* cmvd atom */
  2362. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  2363. return AVERROR_INVALIDDATA;
  2364. moov_len = avio_rb32(pb); /* uncompressed size */
  2365. cmov_len = atom.size - 6 * 4;
  2366. cmov_data = av_malloc(cmov_len);
  2367. if (!cmov_data)
  2368. return AVERROR(ENOMEM);
  2369. moov_data = av_malloc(moov_len);
  2370. if (!moov_data) {
  2371. av_free(cmov_data);
  2372. return AVERROR(ENOMEM);
  2373. }
  2374. avio_read(pb, cmov_data, cmov_len);
  2375. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  2376. goto free_and_return;
  2377. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  2378. goto free_and_return;
  2379. atom.type = MKTAG('m','o','o','v');
  2380. atom.size = moov_len;
  2381. ret = mov_read_default(c, &ctx, atom);
  2382. free_and_return:
  2383. av_free(moov_data);
  2384. av_free(cmov_data);
  2385. return ret;
  2386. #else
  2387. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  2388. return AVERROR(ENOSYS);
  2389. #endif
  2390. }
  2391. /* edit list atom */
  2392. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2393. {
  2394. MOVStreamContext *sc;
  2395. int i, edit_count, version, edit_start_index = 0;
  2396. int unsupported = 0;
  2397. if (c->fc->nb_streams < 1 || c->ignore_editlist)
  2398. return 0;
  2399. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  2400. version = avio_r8(pb); /* version */
  2401. avio_rb24(pb); /* flags */
  2402. edit_count = avio_rb32(pb); /* entries */
  2403. if ((uint64_t)edit_count*12+8 > atom.size)
  2404. return AVERROR_INVALIDDATA;
  2405. av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  2406. for (i=0; i<edit_count; i++){
  2407. int64_t time;
  2408. int64_t duration;
  2409. int rate;
  2410. if (version == 1) {
  2411. duration = avio_rb64(pb);
  2412. time = avio_rb64(pb);
  2413. } else {
  2414. duration = avio_rb32(pb); /* segment duration */
  2415. time = (int32_t)avio_rb32(pb); /* media time */
  2416. }
  2417. rate = avio_rb32(pb);
  2418. if (i == 0 && time == -1) {
  2419. sc->empty_duration = duration;
  2420. edit_start_index = 1;
  2421. } else if (i == edit_start_index && time >= 0)
  2422. sc->start_time = time;
  2423. else
  2424. unsupported = 1;
  2425. av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
  2426. duration, time, rate / 65536.0);
  2427. }
  2428. if (unsupported)
  2429. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  2430. "a/v desync might occur, patch welcome\n");
  2431. return 0;
  2432. }
  2433. static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2434. {
  2435. MOVStreamContext *sc;
  2436. if (c->fc->nb_streams < 1)
  2437. return AVERROR_INVALIDDATA;
  2438. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  2439. sc->timecode_track = avio_rb32(pb);
  2440. return 0;
  2441. }
  2442. static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2443. {
  2444. int ret;
  2445. uint8_t uuid[16];
  2446. static const uint8_t uuid_isml_manifest[] = {
  2447. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  2448. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  2449. };
  2450. if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
  2451. return AVERROR_INVALIDDATA;
  2452. ret = avio_read(pb, uuid, sizeof(uuid));
  2453. if (ret < 0) {
  2454. return ret;
  2455. } else if (ret != sizeof(uuid)) {
  2456. return AVERROR_INVALIDDATA;
  2457. }
  2458. if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
  2459. uint8_t *buffer, *ptr;
  2460. char *endptr;
  2461. size_t len = atom.size - sizeof(uuid);
  2462. if (len < 4) {
  2463. return AVERROR_INVALIDDATA;
  2464. }
  2465. ret = avio_skip(pb, 4); // zeroes
  2466. len -= 4;
  2467. buffer = av_mallocz(len + 1);
  2468. if (!buffer) {
  2469. return AVERROR(ENOMEM);
  2470. }
  2471. ret = avio_read(pb, buffer, len);
  2472. if (ret < 0) {
  2473. av_free(buffer);
  2474. return ret;
  2475. } else if (ret != len) {
  2476. av_free(buffer);
  2477. return AVERROR_INVALIDDATA;
  2478. }
  2479. ptr = buffer;
  2480. while ((ptr = av_stristr(ptr, "systemBitrate=\"")) != NULL) {
  2481. ptr += sizeof("systemBitrate=\"") - 1;
  2482. c->bitrates_count++;
  2483. c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
  2484. if (!c->bitrates) {
  2485. c->bitrates_count = 0;
  2486. av_free(buffer);
  2487. return AVERROR(ENOMEM);
  2488. }
  2489. errno = 0;
  2490. ret = strtol(ptr, &endptr, 10);
  2491. if (ret < 0 || errno || *endptr != '"') {
  2492. c->bitrates[c->bitrates_count - 1] = 0;
  2493. } else {
  2494. c->bitrates[c->bitrates_count - 1] = ret;
  2495. }
  2496. }
  2497. av_free(buffer);
  2498. }
  2499. return 0;
  2500. }
  2501. static const MOVParseTableEntry mov_default_parse_table[] = {
  2502. { MKTAG('A','C','L','R'), mov_read_avid },
  2503. { MKTAG('A','P','R','G'), mov_read_avid },
  2504. { MKTAG('A','A','L','P'), mov_read_avid },
  2505. { MKTAG('A','R','E','S'), mov_read_ares },
  2506. { MKTAG('a','v','s','s'), mov_read_avss },
  2507. { MKTAG('c','h','p','l'), mov_read_chpl },
  2508. { MKTAG('c','o','6','4'), mov_read_stco },
  2509. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  2510. { MKTAG('d','i','n','f'), mov_read_default },
  2511. { MKTAG('d','r','e','f'), mov_read_dref },
  2512. { MKTAG('e','d','t','s'), mov_read_default },
  2513. { MKTAG('e','l','s','t'), mov_read_elst },
  2514. { MKTAG('e','n','d','a'), mov_read_enda },
  2515. { MKTAG('f','i','e','l'), mov_read_fiel },
  2516. { MKTAG('f','t','y','p'), mov_read_ftyp },
  2517. { MKTAG('g','l','b','l'), mov_read_glbl },
  2518. { MKTAG('h','d','l','r'), mov_read_hdlr },
  2519. { MKTAG('i','l','s','t'), mov_read_ilst },
  2520. { MKTAG('j','p','2','h'), mov_read_jp2h },
  2521. { MKTAG('m','d','a','t'), mov_read_mdat },
  2522. { MKTAG('m','d','h','d'), mov_read_mdhd },
  2523. { MKTAG('m','d','i','a'), mov_read_default },
  2524. { MKTAG('m','e','t','a'), mov_read_meta },
  2525. { MKTAG('m','i','n','f'), mov_read_default },
  2526. { MKTAG('m','o','o','f'), mov_read_moof },
  2527. { MKTAG('m','o','o','v'), mov_read_moov },
  2528. { MKTAG('m','v','e','x'), mov_read_default },
  2529. { MKTAG('m','v','h','d'), mov_read_mvhd },
  2530. { MKTAG('S','M','I',' '), mov_read_svq3 },
  2531. { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
  2532. { MKTAG('a','v','c','C'), mov_read_glbl },
  2533. { MKTAG('p','a','s','p'), mov_read_pasp },
  2534. { MKTAG('s','t','b','l'), mov_read_default },
  2535. { MKTAG('s','t','c','o'), mov_read_stco },
  2536. { MKTAG('s','t','p','s'), mov_read_stps },
  2537. { MKTAG('s','t','r','f'), mov_read_strf },
  2538. { MKTAG('s','t','s','c'), mov_read_stsc },
  2539. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  2540. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  2541. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  2542. { MKTAG('s','t','t','s'), mov_read_stts },
  2543. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  2544. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  2545. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  2546. { MKTAG('t','r','a','k'), mov_read_trak },
  2547. { MKTAG('t','r','a','f'), mov_read_default },
  2548. { MKTAG('t','r','e','f'), mov_read_default },
  2549. { MKTAG('t','m','c','d'), mov_read_tmcd },
  2550. { MKTAG('c','h','a','p'), mov_read_chap },
  2551. { MKTAG('t','r','e','x'), mov_read_trex },
  2552. { MKTAG('t','r','u','n'), mov_read_trun },
  2553. { MKTAG('u','d','t','a'), mov_read_default },
  2554. { MKTAG('w','a','v','e'), mov_read_wave },
  2555. { MKTAG('e','s','d','s'), mov_read_esds },
  2556. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  2557. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  2558. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  2559. { MKTAG('w','f','e','x'), mov_read_wfex },
  2560. { MKTAG('c','m','o','v'), mov_read_cmov },
  2561. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  2562. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  2563. { MKTAG('s','b','g','p'), mov_read_sbgp },
  2564. { MKTAG('h','v','c','C'), mov_read_glbl },
  2565. { MKTAG('u','u','i','d'), mov_read_uuid },
  2566. { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
  2567. { 0, NULL }
  2568. };
  2569. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2570. {
  2571. int64_t total_size = 0;
  2572. MOVAtom a;
  2573. int i;
  2574. if (atom.size < 0)
  2575. atom.size = INT64_MAX;
  2576. while (total_size + 8 <= atom.size && !url_feof(pb)) {
  2577. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  2578. a.size = atom.size;
  2579. a.type=0;
  2580. if (atom.size >= 8) {
  2581. a.size = avio_rb32(pb);
  2582. a.type = avio_rl32(pb);
  2583. if (atom.type != MKTAG('r','o','o','t') &&
  2584. atom.type != MKTAG('m','o','o','v'))
  2585. {
  2586. if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
  2587. {
  2588. av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
  2589. avio_skip(pb, -8);
  2590. return 0;
  2591. }
  2592. }
  2593. total_size += 8;
  2594. if (a.size == 1) { /* 64 bit extended size */
  2595. a.size = avio_rb64(pb) - 8;
  2596. total_size += 8;
  2597. }
  2598. }
  2599. av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  2600. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  2601. if (a.size == 0) {
  2602. a.size = atom.size - total_size + 8;
  2603. }
  2604. a.size -= 8;
  2605. if (a.size < 0)
  2606. break;
  2607. a.size = FFMIN(a.size, atom.size - total_size);
  2608. for (i = 0; mov_default_parse_table[i].type; i++)
  2609. if (mov_default_parse_table[i].type == a.type) {
  2610. parse = mov_default_parse_table[i].parse;
  2611. break;
  2612. }
  2613. // container is user data
  2614. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  2615. atom.type == MKTAG('i','l','s','t')))
  2616. parse = mov_read_udta_string;
  2617. if (!parse) { /* skip leaf atoms data */
  2618. avio_skip(pb, a.size);
  2619. } else {
  2620. int64_t start_pos = avio_tell(pb);
  2621. int64_t left;
  2622. int err = parse(c, pb, a);
  2623. if (err < 0)
  2624. return err;
  2625. if (c->found_moov && c->found_mdat &&
  2626. ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
  2627. start_pos + a.size == avio_size(pb))) {
  2628. if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
  2629. c->next_root_atom = start_pos + a.size;
  2630. return 0;
  2631. }
  2632. left = a.size - avio_tell(pb) + start_pos;
  2633. if (left > 0) /* skip garbage at atom end */
  2634. avio_skip(pb, left);
  2635. else if (left < 0) {
  2636. av_log(c->fc, AV_LOG_WARNING,
  2637. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  2638. (char*)&a.type, -left);
  2639. avio_seek(pb, left, SEEK_CUR);
  2640. }
  2641. }
  2642. total_size += a.size;
  2643. }
  2644. if (total_size < atom.size && atom.size < 0x7ffff)
  2645. avio_skip(pb, atom.size - total_size);
  2646. return 0;
  2647. }
  2648. static int mov_probe(AVProbeData *p)
  2649. {
  2650. int64_t offset;
  2651. uint32_t tag;
  2652. int score = 0;
  2653. int moov_offset = -1;
  2654. /* check file header */
  2655. offset = 0;
  2656. for (;;) {
  2657. /* ignore invalid offset */
  2658. if ((offset + 8) > (unsigned int)p->buf_size)
  2659. break;
  2660. tag = AV_RL32(p->buf + offset + 4);
  2661. switch(tag) {
  2662. /* check for obvious tags */
  2663. case MKTAG('m','o','o','v'):
  2664. moov_offset = offset + 4;
  2665. case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
  2666. case MKTAG('m','d','a','t'):
  2667. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  2668. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  2669. case MKTAG('f','t','y','p'):
  2670. if (AV_RB32(p->buf+offset) < 8 &&
  2671. (AV_RB32(p->buf+offset) != 1 ||
  2672. offset + 12 > (unsigned int)p->buf_size ||
  2673. AV_RB64(p->buf+offset + 8) == 0)) {
  2674. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  2675. } else {
  2676. score = AVPROBE_SCORE_MAX;
  2677. }
  2678. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  2679. break;
  2680. /* those are more common words, so rate then a bit less */
  2681. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  2682. case MKTAG('w','i','d','e'):
  2683. case MKTAG('f','r','e','e'):
  2684. case MKTAG('j','u','n','k'):
  2685. case MKTAG('p','i','c','t'):
  2686. score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
  2687. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  2688. break;
  2689. case MKTAG(0x82,0x82,0x7f,0x7d):
  2690. case MKTAG('s','k','i','p'):
  2691. case MKTAG('u','u','i','d'):
  2692. case MKTAG('p','r','f','l'):
  2693. /* if we only find those cause probedata is too small at least rate them */
  2694. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  2695. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  2696. break;
  2697. default:
  2698. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  2699. }
  2700. }
  2701. if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
  2702. /* moov atom in the header - we should make sure that this is not a
  2703. * MOV-packed MPEG-PS */
  2704. offset = moov_offset;
  2705. while(offset < (p->buf_size - 16)){ /* Sufficient space */
  2706. /* We found an actual hdlr atom */
  2707. if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
  2708. AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
  2709. AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
  2710. av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
  2711. /* We found a media handler reference atom describing an
  2712. * MPEG-PS-in-MOV, return a
  2713. * low score to force expanding the probe window until
  2714. * mpegps_probe finds what it needs */
  2715. return 5;
  2716. }else
  2717. /* Keep looking */
  2718. offset+=2;
  2719. }
  2720. }
  2721. return score;
  2722. }
  2723. // must be done after parsing all trak because there's no order requirement
  2724. static void mov_read_chapters(AVFormatContext *s)
  2725. {
  2726. MOVContext *mov = s->priv_data;
  2727. AVStream *st = NULL;
  2728. MOVStreamContext *sc;
  2729. int64_t cur_pos;
  2730. int i;
  2731. for (i = 0; i < s->nb_streams; i++)
  2732. if (s->streams[i]->id == mov->chapter_track) {
  2733. st = s->streams[i];
  2734. break;
  2735. }
  2736. if (!st) {
  2737. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  2738. return;
  2739. }
  2740. st->discard = AVDISCARD_ALL;
  2741. sc = st->priv_data;
  2742. cur_pos = avio_tell(sc->pb);
  2743. for (i = 0; i < st->nb_index_entries; i++) {
  2744. AVIndexEntry *sample = &st->index_entries[i];
  2745. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  2746. uint8_t *title;
  2747. uint16_t ch;
  2748. int len, title_len;
  2749. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2750. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  2751. goto finish;
  2752. }
  2753. // the first two bytes are the length of the title
  2754. len = avio_rb16(sc->pb);
  2755. if (len > sample->size-2)
  2756. continue;
  2757. title_len = 2*len + 1;
  2758. if (!(title = av_mallocz(title_len)))
  2759. goto finish;
  2760. // The samples could theoretically be in any encoding if there's an encd
  2761. // atom following, but in practice are only utf-8 or utf-16, distinguished
  2762. // instead by the presence of a BOM
  2763. if (!len) {
  2764. title[0] = 0;
  2765. } else {
  2766. ch = avio_rb16(sc->pb);
  2767. if (ch == 0xfeff)
  2768. avio_get_str16be(sc->pb, len, title, title_len);
  2769. else if (ch == 0xfffe)
  2770. avio_get_str16le(sc->pb, len, title, title_len);
  2771. else {
  2772. AV_WB16(title, ch);
  2773. if (len == 1 || len == 2)
  2774. title[len] = 0;
  2775. else
  2776. avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
  2777. }
  2778. }
  2779. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  2780. av_freep(&title);
  2781. }
  2782. finish:
  2783. avio_seek(sc->pb, cur_pos, SEEK_SET);
  2784. }
  2785. static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
  2786. uint32_t value, int flags)
  2787. {
  2788. AVTimecode tc;
  2789. char buf[AV_TIMECODE_STR_SIZE];
  2790. AVRational rate = {st->codec->time_base.den,
  2791. st->codec->time_base.num};
  2792. int ret = av_timecode_init(&tc, rate, flags, 0, s);
  2793. if (ret < 0)
  2794. return ret;
  2795. av_dict_set(&st->metadata, "timecode",
  2796. av_timecode_make_string(&tc, buf, value), 0);
  2797. return 0;
  2798. }
  2799. static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
  2800. {
  2801. MOVStreamContext *sc = st->priv_data;
  2802. int flags = 0;
  2803. int64_t cur_pos = avio_tell(sc->pb);
  2804. uint32_t value;
  2805. if (!st->nb_index_entries)
  2806. return -1;
  2807. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  2808. value = avio_rb32(s->pb);
  2809. if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
  2810. if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  2811. if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
  2812. /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
  2813. * not the case) and thus assume "frame number format" instead of QT one.
  2814. * No sample with tmcd track can be found with a QT timecode at the moment,
  2815. * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
  2816. * format). */
  2817. parse_timecode_in_framenum_format(s, st, value, flags);
  2818. avio_seek(sc->pb, cur_pos, SEEK_SET);
  2819. return 0;
  2820. }
  2821. static int mov_read_close(AVFormatContext *s)
  2822. {
  2823. MOVContext *mov = s->priv_data;
  2824. int i, j;
  2825. for (i = 0; i < s->nb_streams; i++) {
  2826. AVStream *st = s->streams[i];
  2827. MOVStreamContext *sc = st->priv_data;
  2828. av_freep(&sc->ctts_data);
  2829. for (j = 0; j < sc->drefs_count; j++) {
  2830. av_freep(&sc->drefs[j].path);
  2831. av_freep(&sc->drefs[j].dir);
  2832. }
  2833. av_freep(&sc->drefs);
  2834. if (!sc->pb_is_copied)
  2835. avio_close(sc->pb);
  2836. sc->pb = NULL;
  2837. av_freep(&sc->chunk_offsets);
  2838. av_freep(&sc->keyframes);
  2839. av_freep(&sc->sample_sizes);
  2840. av_freep(&sc->stps_data);
  2841. av_freep(&sc->stsc_data);
  2842. av_freep(&sc->stts_data);
  2843. }
  2844. if (mov->dv_demux) {
  2845. for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
  2846. av_freep(&mov->dv_fctx->streams[i]->codec);
  2847. av_freep(&mov->dv_fctx->streams[i]);
  2848. }
  2849. av_freep(&mov->dv_fctx);
  2850. av_freep(&mov->dv_demux);
  2851. }
  2852. av_freep(&mov->trex_data);
  2853. av_freep(&mov->bitrates);
  2854. return 0;
  2855. }
  2856. static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
  2857. {
  2858. int i;
  2859. for (i = 0; i < s->nb_streams; i++) {
  2860. AVStream *st = s->streams[i];
  2861. MOVStreamContext *sc = st->priv_data;
  2862. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  2863. sc->timecode_track == tmcd_id)
  2864. return 1;
  2865. }
  2866. return 0;
  2867. }
  2868. /* look for a tmcd track not referenced by any video track, and export it globally */
  2869. static void export_orphan_timecode(AVFormatContext *s)
  2870. {
  2871. int i;
  2872. for (i = 0; i < s->nb_streams; i++) {
  2873. AVStream *st = s->streams[i];
  2874. if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
  2875. !tmcd_is_referenced(s, i + 1)) {
  2876. AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
  2877. if (tcr) {
  2878. av_dict_set(&s->metadata, "timecode", tcr->value, 0);
  2879. break;
  2880. }
  2881. }
  2882. }
  2883. }
  2884. static int mov_read_header(AVFormatContext *s)
  2885. {
  2886. MOVContext *mov = s->priv_data;
  2887. AVIOContext *pb = s->pb;
  2888. int i, j, err;
  2889. MOVAtom atom = { AV_RL32("root") };
  2890. mov->fc = s;
  2891. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  2892. if (pb->seekable)
  2893. atom.size = avio_size(pb);
  2894. else
  2895. atom.size = INT64_MAX;
  2896. /* check MOV header */
  2897. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  2898. av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
  2899. mov_read_close(s);
  2900. return err;
  2901. }
  2902. if (!mov->found_moov) {
  2903. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  2904. mov_read_close(s);
  2905. return AVERROR_INVALIDDATA;
  2906. }
  2907. av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  2908. if (pb->seekable) {
  2909. if (mov->chapter_track > 0)
  2910. mov_read_chapters(s);
  2911. for (i = 0; i < s->nb_streams; i++)
  2912. if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
  2913. mov_read_timecode_track(s, s->streams[i]);
  2914. }
  2915. /* copy timecode metadata from tmcd tracks to the related video streams */
  2916. for (i = 0; i < s->nb_streams; i++) {
  2917. AVStream *st = s->streams[i];
  2918. MOVStreamContext *sc = st->priv_data;
  2919. if (sc->timecode_track > 0) {
  2920. AVDictionaryEntry *tcr;
  2921. int tmcd_st_id = -1;
  2922. for (j = 0; j < s->nb_streams; j++)
  2923. if (s->streams[j]->id == sc->timecode_track)
  2924. tmcd_st_id = j;
  2925. if (tmcd_st_id < 0 || tmcd_st_id == i)
  2926. continue;
  2927. tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
  2928. if (tcr)
  2929. av_dict_set(&st->metadata, "timecode", tcr->value, 0);
  2930. }
  2931. }
  2932. export_orphan_timecode(s);
  2933. for (i = 0; i < s->nb_streams; i++) {
  2934. AVStream *st = s->streams[i];
  2935. MOVStreamContext *sc = st->priv_data;
  2936. fix_timescale(mov, sc);
  2937. if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
  2938. st->skip_samples = sc->start_pad;
  2939. }
  2940. }
  2941. if (mov->trex_data) {
  2942. for (i = 0; i < s->nb_streams; i++) {
  2943. AVStream *st = s->streams[i];
  2944. MOVStreamContext *sc = st->priv_data;
  2945. if (st->duration > 0)
  2946. st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  2947. }
  2948. }
  2949. for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
  2950. if (mov->bitrates[i]) {
  2951. s->streams[i]->codec->bit_rate = mov->bitrates[i];
  2952. }
  2953. }
  2954. return 0;
  2955. }
  2956. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  2957. {
  2958. AVIndexEntry *sample = NULL;
  2959. int64_t best_dts = INT64_MAX;
  2960. int i;
  2961. for (i = 0; i < s->nb_streams; i++) {
  2962. AVStream *avst = s->streams[i];
  2963. MOVStreamContext *msc = avst->priv_data;
  2964. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  2965. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  2966. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  2967. av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  2968. if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  2969. (s->pb->seekable &&
  2970. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  2971. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  2972. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  2973. sample = current_sample;
  2974. best_dts = dts;
  2975. *st = avst;
  2976. }
  2977. }
  2978. }
  2979. return sample;
  2980. }
  2981. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  2982. {
  2983. MOVContext *mov = s->priv_data;
  2984. MOVStreamContext *sc;
  2985. AVIndexEntry *sample;
  2986. AVStream *st = NULL;
  2987. int ret;
  2988. mov->fc = s;
  2989. retry:
  2990. sample = mov_find_next_sample(s, &st);
  2991. if (!sample) {
  2992. mov->found_mdat = 0;
  2993. if (!mov->next_root_atom)
  2994. return AVERROR_EOF;
  2995. avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
  2996. mov->next_root_atom = 0;
  2997. if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  2998. url_feof(s->pb))
  2999. return AVERROR_EOF;
  3000. av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  3001. goto retry;
  3002. }
  3003. sc = st->priv_data;
  3004. /* must be done just before reading, to avoid infinite loop on sample */
  3005. sc->current_sample++;
  3006. if (mov->next_root_atom) {
  3007. sample->pos = FFMIN(sample->pos, mov->next_root_atom);
  3008. sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
  3009. }
  3010. if (st->discard != AVDISCARD_ALL) {
  3011. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  3012. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  3013. sc->ffindex, sample->pos);
  3014. return AVERROR_INVALIDDATA;
  3015. }
  3016. ret = av_get_packet(sc->pb, pkt, sample->size);
  3017. if (ret < 0)
  3018. return ret;
  3019. if (sc->has_palette) {
  3020. uint8_t *pal;
  3021. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  3022. if (!pal) {
  3023. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  3024. } else {
  3025. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  3026. sc->has_palette = 0;
  3027. }
  3028. }
  3029. #if CONFIG_DV_DEMUXER
  3030. if (mov->dv_demux && sc->dv_audio_container) {
  3031. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  3032. av_free(pkt->data);
  3033. pkt->size = 0;
  3034. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  3035. if (ret < 0)
  3036. return ret;
  3037. }
  3038. #endif
  3039. }
  3040. pkt->stream_index = sc->ffindex;
  3041. pkt->dts = sample->timestamp;
  3042. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  3043. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  3044. /* update ctts context */
  3045. sc->ctts_sample++;
  3046. if (sc->ctts_index < sc->ctts_count &&
  3047. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  3048. sc->ctts_index++;
  3049. sc->ctts_sample = 0;
  3050. }
  3051. if (sc->wrong_dts)
  3052. pkt->dts = AV_NOPTS_VALUE;
  3053. } else {
  3054. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  3055. st->index_entries[sc->current_sample].timestamp : st->duration;
  3056. pkt->duration = next_dts - pkt->dts;
  3057. pkt->pts = pkt->dts;
  3058. }
  3059. if (st->discard == AVDISCARD_ALL)
  3060. goto retry;
  3061. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  3062. pkt->pos = sample->pos;
  3063. av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
  3064. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  3065. return 0;
  3066. }
  3067. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  3068. {
  3069. MOVStreamContext *sc = st->priv_data;
  3070. int sample, time_sample;
  3071. int i;
  3072. sample = av_index_search_timestamp(st, timestamp, flags);
  3073. av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  3074. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  3075. sample = 0;
  3076. if (sample < 0) /* not sure what to do */
  3077. return AVERROR_INVALIDDATA;
  3078. sc->current_sample = sample;
  3079. av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
  3080. /* adjust ctts index */
  3081. if (sc->ctts_data) {
  3082. time_sample = 0;
  3083. for (i = 0; i < sc->ctts_count; i++) {
  3084. int next = time_sample + sc->ctts_data[i].count;
  3085. if (next > sc->current_sample) {
  3086. sc->ctts_index = i;
  3087. sc->ctts_sample = sc->current_sample - time_sample;
  3088. break;
  3089. }
  3090. time_sample = next;
  3091. }
  3092. }
  3093. return sample;
  3094. }
  3095. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  3096. {
  3097. AVStream *st;
  3098. int64_t seek_timestamp, timestamp;
  3099. int sample;
  3100. int i;
  3101. if (stream_index >= s->nb_streams)
  3102. return AVERROR_INVALIDDATA;
  3103. st = s->streams[stream_index];
  3104. sample = mov_seek_stream(s, st, sample_time, flags);
  3105. if (sample < 0)
  3106. return sample;
  3107. /* adjust seek timestamp to found sample timestamp */
  3108. seek_timestamp = st->index_entries[sample].timestamp;
  3109. for (i = 0; i < s->nb_streams; i++) {
  3110. MOVStreamContext *sc = s->streams[i]->priv_data;
  3111. st = s->streams[i];
  3112. st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
  3113. if (stream_index == i)
  3114. continue;
  3115. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  3116. mov_seek_stream(s, st, timestamp, flags);
  3117. }
  3118. return 0;
  3119. }
  3120. static const AVOption options[] = {
  3121. {"use_absolute_path",
  3122. "allow using absolute path when opening alias, this is a possible security issue",
  3123. offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
  3124. 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
  3125. {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
  3126. 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
  3127. {NULL}
  3128. };
  3129. static const AVClass mov_class = {
  3130. .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
  3131. .item_name = av_default_item_name,
  3132. .option = options,
  3133. .version = LIBAVUTIL_VERSION_INT,
  3134. };
  3135. AVInputFormat ff_mov_demuxer = {
  3136. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  3137. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  3138. .priv_data_size = sizeof(MOVContext),
  3139. .read_probe = mov_probe,
  3140. .read_header = mov_read_header,
  3141. .read_packet = mov_read_packet,
  3142. .read_close = mov_read_close,
  3143. .read_seek = mov_read_seek,
  3144. .priv_class = &mov_class,
  3145. .flags = AVFMT_NO_BYTE_SEEK,
  3146. };