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.

3765 lines
123KB

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