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.

3698 lines
121KB

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