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.

3263 lines
109KB

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