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.

3870 lines
127KB

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