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.

3899 lines
128KB

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