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.

1607 lines
54KB

  1. /*
  2. * AVI demuxer
  3. * Copyright (c) 2001 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include <inttypes.h>
  22. #include "libavutil/avstring.h"
  23. #include "libavutil/bswap.h"
  24. #include "libavutil/dict.h"
  25. #include "libavutil/internal.h"
  26. #include "libavutil/intreadwrite.h"
  27. #include "libavutil/mathematics.h"
  28. #include "avformat.h"
  29. #include "avi.h"
  30. #include "dv.h"
  31. #include "internal.h"
  32. #include "riff.h"
  33. #undef NDEBUG
  34. #include <assert.h>
  35. typedef struct AVIStream {
  36. int64_t frame_offset; /* current frame (video) or byte (audio) counter
  37. * (used to compute the pts) */
  38. int remaining;
  39. int packet_size;
  40. uint32_t handler;
  41. uint32_t scale;
  42. uint32_t rate;
  43. int sample_size; /* size of one sample (or packet)
  44. * (in the rate/scale sense) in bytes */
  45. int64_t cum_len; /* temporary storage (used during seek) */
  46. int prefix; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
  47. int prefix_count;
  48. uint32_t pal[256];
  49. int has_pal;
  50. int dshow_block_align; /* block align variable used to emulate bugs in
  51. * the MS dshow demuxer */
  52. AVFormatContext *sub_ctx;
  53. AVPacket sub_pkt;
  54. uint8_t *sub_buffer;
  55. } AVIStream;
  56. typedef struct AVIContext {
  57. int64_t riff_end;
  58. int64_t movi_end;
  59. int64_t fsize;
  60. int64_t movi_list;
  61. int64_t last_pkt_pos;
  62. int index_loaded;
  63. int is_odml;
  64. int non_interleaved;
  65. int stream_index;
  66. DVDemuxContext *dv_demux;
  67. int odml_depth;
  68. #define MAX_ODML_DEPTH 1000
  69. } AVIContext;
  70. static const char avi_headers[][8] = {
  71. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
  72. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
  73. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
  74. { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
  75. { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
  76. { 0 }
  77. };
  78. static const AVMetadataConv avi_metadata_conv[] = {
  79. { "strn", "title" },
  80. { 0 },
  81. };
  82. static int avi_load_index(AVFormatContext *s);
  83. static int guess_ni_flag(AVFormatContext *s);
  84. #define print_tag(str, tag, size) \
  85. av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
  86. str, tag & 0xff, \
  87. (tag >> 8) & 0xff, \
  88. (tag >> 16) & 0xff, \
  89. (tag >> 24) & 0xff, \
  90. size)
  91. static inline int get_duration(AVIStream *ast, int len)
  92. {
  93. if (ast->sample_size)
  94. return len;
  95. else if (ast->dshow_block_align)
  96. return (len + ast->dshow_block_align - 1) / ast->dshow_block_align;
  97. else
  98. return 1;
  99. }
  100. static int get_riff(AVFormatContext *s, AVIOContext *pb)
  101. {
  102. AVIContext *avi = s->priv_data;
  103. char header[8];
  104. int i;
  105. /* check RIFF header */
  106. avio_read(pb, header, 4);
  107. avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
  108. avi->riff_end += avio_tell(pb); /* RIFF chunk end */
  109. avio_read(pb, header + 4, 4);
  110. for (i = 0; avi_headers[i][0]; i++)
  111. if (!memcmp(header, avi_headers[i], 8))
  112. break;
  113. if (!avi_headers[i][0])
  114. return AVERROR_INVALIDDATA;
  115. if (header[7] == 0x19)
  116. av_log(s, AV_LOG_INFO,
  117. "This file has been generated by a totally broken muxer.\n");
  118. return 0;
  119. }
  120. static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
  121. {
  122. AVIContext *avi = s->priv_data;
  123. AVIOContext *pb = s->pb;
  124. int longs_pre_entry = avio_rl16(pb);
  125. int index_sub_type = avio_r8(pb);
  126. int index_type = avio_r8(pb);
  127. int entries_in_use = avio_rl32(pb);
  128. int chunk_id = avio_rl32(pb);
  129. int64_t base = avio_rl64(pb);
  130. int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
  131. ((chunk_id >> 8 & 0xFF) - '0');
  132. AVStream *st;
  133. AVIStream *ast;
  134. int i;
  135. int64_t last_pos = -1;
  136. int64_t filesize = avi->fsize;
  137. av_dlog(s,
  138. "longs_pre_entry:%d index_type:%d entries_in_use:%d "
  139. "chunk_id:%X base:%16"PRIX64"\n",
  140. longs_pre_entry,
  141. index_type,
  142. entries_in_use,
  143. chunk_id,
  144. base);
  145. if (stream_id >= s->nb_streams || stream_id < 0)
  146. return AVERROR_INVALIDDATA;
  147. st = s->streams[stream_id];
  148. ast = st->priv_data;
  149. if (index_sub_type)
  150. return AVERROR_INVALIDDATA;
  151. avio_rl32(pb);
  152. if (index_type && longs_pre_entry != 2)
  153. return AVERROR_INVALIDDATA;
  154. if (index_type > 1)
  155. return AVERROR_INVALIDDATA;
  156. if (filesize > 0 && base >= filesize) {
  157. av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
  158. if (base >> 32 == (base & 0xFFFFFFFF) &&
  159. (base & 0xFFFFFFFF) < filesize &&
  160. filesize <= 0xFFFFFFFF)
  161. base &= 0xFFFFFFFF;
  162. else
  163. return AVERROR_INVALIDDATA;
  164. }
  165. for (i = 0; i < entries_in_use; i++) {
  166. if (index_type) {
  167. int64_t pos = avio_rl32(pb) + base - 8;
  168. int len = avio_rl32(pb);
  169. int key = len >= 0;
  170. len &= 0x7FFFFFFF;
  171. av_dlog(s, "pos:%"PRId64", len:%X\n", pos, len);
  172. if (pb->eof_reached)
  173. return AVERROR_INVALIDDATA;
  174. if (last_pos == pos || pos == base - 8)
  175. avi->non_interleaved = 1;
  176. if (last_pos != pos && (len || !ast->sample_size))
  177. av_add_index_entry(st, pos, ast->cum_len, len, 0,
  178. key ? AVINDEX_KEYFRAME : 0);
  179. ast->cum_len += get_duration(ast, len);
  180. last_pos = pos;
  181. } else {
  182. int64_t offset, pos;
  183. int duration;
  184. offset = avio_rl64(pb);
  185. avio_rl32(pb); /* size */
  186. duration = avio_rl32(pb);
  187. if (pb->eof_reached)
  188. return AVERROR_INVALIDDATA;
  189. pos = avio_tell(pb);
  190. if (avi->odml_depth > MAX_ODML_DEPTH) {
  191. av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
  192. return AVERROR_INVALIDDATA;
  193. }
  194. avio_seek(pb, offset + 8, SEEK_SET);
  195. avi->odml_depth++;
  196. read_braindead_odml_indx(s, frame_num);
  197. avi->odml_depth--;
  198. frame_num += duration;
  199. avio_seek(pb, pos, SEEK_SET);
  200. }
  201. }
  202. avi->index_loaded = 1;
  203. return 0;
  204. }
  205. static void clean_index(AVFormatContext *s)
  206. {
  207. int i;
  208. int64_t j;
  209. for (i = 0; i < s->nb_streams; i++) {
  210. AVStream *st = s->streams[i];
  211. AVIStream *ast = st->priv_data;
  212. int n = st->nb_index_entries;
  213. int max = ast->sample_size;
  214. int64_t pos, size, ts;
  215. if (n != 1 || ast->sample_size == 0)
  216. continue;
  217. while (max < 1024)
  218. max += max;
  219. pos = st->index_entries[0].pos;
  220. size = st->index_entries[0].size;
  221. ts = st->index_entries[0].timestamp;
  222. for (j = 0; j < size; j += max)
  223. av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
  224. AVINDEX_KEYFRAME);
  225. }
  226. }
  227. static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
  228. uint32_t size)
  229. {
  230. AVIOContext *pb = s->pb;
  231. char key[5] = { 0 };
  232. char *value;
  233. size += (size & 1);
  234. if (size == UINT_MAX)
  235. return AVERROR(EINVAL);
  236. value = av_malloc(size + 1);
  237. if (!value)
  238. return AVERROR(ENOMEM);
  239. avio_read(pb, value, size);
  240. value[size] = 0;
  241. AV_WL32(key, tag);
  242. return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
  243. AV_DICT_DONT_STRDUP_VAL);
  244. }
  245. static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  246. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  247. static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
  248. {
  249. char month[4], time[9], buffer[64];
  250. int i, day, year;
  251. /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
  252. if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
  253. month, &day, time, &year) == 4) {
  254. for (i = 0; i < 12; i++)
  255. if (!av_strcasecmp(month, months[i])) {
  256. snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
  257. year, i + 1, day, time);
  258. av_dict_set(metadata, "creation_time", buffer, 0);
  259. }
  260. } else if (date[4] == '/' && date[7] == '/') {
  261. date[4] = date[7] = '-';
  262. av_dict_set(metadata, "creation_time", date, 0);
  263. }
  264. }
  265. static void avi_read_nikon(AVFormatContext *s, uint64_t end)
  266. {
  267. while (avio_tell(s->pb) < end) {
  268. uint32_t tag = avio_rl32(s->pb);
  269. uint32_t size = avio_rl32(s->pb);
  270. switch (tag) {
  271. case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
  272. {
  273. uint64_t tag_end = avio_tell(s->pb) + size;
  274. while (avio_tell(s->pb) < tag_end) {
  275. uint16_t tag = avio_rl16(s->pb);
  276. uint16_t size = avio_rl16(s->pb);
  277. const char *name = NULL;
  278. char buffer[64] = { 0 };
  279. size -= avio_read(s->pb, buffer,
  280. FFMIN(size, sizeof(buffer) - 1));
  281. switch (tag) {
  282. case 0x03:
  283. name = "maker";
  284. break;
  285. case 0x04:
  286. name = "model";
  287. break;
  288. case 0x13:
  289. name = "creation_time";
  290. if (buffer[4] == ':' && buffer[7] == ':')
  291. buffer[4] = buffer[7] = '-';
  292. break;
  293. }
  294. if (name)
  295. av_dict_set(&s->metadata, name, buffer, 0);
  296. avio_skip(s->pb, size);
  297. }
  298. break;
  299. }
  300. default:
  301. avio_skip(s->pb, size);
  302. break;
  303. }
  304. }
  305. }
  306. static int avi_read_header(AVFormatContext *s)
  307. {
  308. AVIContext *avi = s->priv_data;
  309. AVIOContext *pb = s->pb;
  310. unsigned int tag, tag1, handler;
  311. int codec_type, stream_index, frame_period;
  312. unsigned int size;
  313. int i;
  314. AVStream *st;
  315. AVIStream *ast = NULL;
  316. int avih_width = 0, avih_height = 0;
  317. int amv_file_format = 0;
  318. uint64_t list_end = 0;
  319. int ret;
  320. avi->stream_index = -1;
  321. ret = get_riff(s, pb);
  322. if (ret < 0)
  323. return ret;
  324. avi->fsize = avio_size(pb);
  325. if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
  326. avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
  327. /* first list tag */
  328. stream_index = -1;
  329. codec_type = -1;
  330. frame_period = 0;
  331. for (;;) {
  332. if (pb->eof_reached)
  333. goto fail;
  334. tag = avio_rl32(pb);
  335. size = avio_rl32(pb);
  336. print_tag("tag", tag, size);
  337. switch (tag) {
  338. case MKTAG('L', 'I', 'S', 'T'):
  339. list_end = avio_tell(pb) + size;
  340. /* Ignored, except at start of video packets. */
  341. tag1 = avio_rl32(pb);
  342. print_tag("list", tag1, 0);
  343. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  344. avi->movi_list = avio_tell(pb) - 4;
  345. if (size)
  346. avi->movi_end = avi->movi_list + size + (size & 1);
  347. else
  348. avi->movi_end = avi->fsize;
  349. av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
  350. goto end_of_header;
  351. } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
  352. ff_read_riff_info(s, size - 4);
  353. else if (tag1 == MKTAG('n', 'c', 'd', 't'))
  354. avi_read_nikon(s, list_end);
  355. break;
  356. case MKTAG('I', 'D', 'I', 'T'):
  357. {
  358. unsigned char date[64] = { 0 };
  359. size += (size & 1);
  360. size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
  361. avio_skip(pb, size);
  362. avi_metadata_creation_time(&s->metadata, date);
  363. break;
  364. }
  365. case MKTAG('d', 'm', 'l', 'h'):
  366. avi->is_odml = 1;
  367. avio_skip(pb, size + (size & 1));
  368. break;
  369. case MKTAG('a', 'm', 'v', 'h'):
  370. amv_file_format = 1;
  371. case MKTAG('a', 'v', 'i', 'h'):
  372. /* AVI header */
  373. /* using frame_period is bad idea */
  374. frame_period = avio_rl32(pb);
  375. avio_skip(pb, 4);
  376. avio_rl32(pb);
  377. avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
  378. avio_skip(pb, 2 * 4);
  379. avio_rl32(pb);
  380. avio_rl32(pb);
  381. avih_width = avio_rl32(pb);
  382. avih_height = avio_rl32(pb);
  383. avio_skip(pb, size - 10 * 4);
  384. break;
  385. case MKTAG('s', 't', 'r', 'h'):
  386. /* stream header */
  387. tag1 = avio_rl32(pb);
  388. handler = avio_rl32(pb); /* codec tag */
  389. if (tag1 == MKTAG('p', 'a', 'd', 's')) {
  390. avio_skip(pb, size - 8);
  391. break;
  392. } else {
  393. stream_index++;
  394. st = avformat_new_stream(s, NULL);
  395. if (!st)
  396. goto fail;
  397. st->id = stream_index;
  398. ast = av_mallocz(sizeof(AVIStream));
  399. if (!ast)
  400. goto fail;
  401. st->priv_data = ast;
  402. }
  403. if (amv_file_format)
  404. tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
  405. : MKTAG('v', 'i', 'd', 's');
  406. print_tag("strh", tag1, -1);
  407. if (tag1 == MKTAG('i', 'a', 'v', 's') ||
  408. tag1 == MKTAG('i', 'v', 'a', 's')) {
  409. int64_t dv_dur;
  410. /* After some consideration -- I don't think we
  411. * have to support anything but DV in type1 AVIs. */
  412. if (s->nb_streams != 1)
  413. goto fail;
  414. if (handler != MKTAG('d', 'v', 's', 'd') &&
  415. handler != MKTAG('d', 'v', 'h', 'd') &&
  416. handler != MKTAG('d', 'v', 's', 'l'))
  417. goto fail;
  418. ast = s->streams[0]->priv_data;
  419. av_freep(&s->streams[0]->codec->extradata);
  420. av_freep(&s->streams[0]->codec);
  421. av_freep(&s->streams[0]->info);
  422. av_freep(&s->streams[0]);
  423. s->nb_streams = 0;
  424. if (CONFIG_DV_DEMUXER) {
  425. avi->dv_demux = avpriv_dv_init_demux(s);
  426. if (!avi->dv_demux)
  427. goto fail;
  428. } else
  429. goto fail;
  430. s->streams[0]->priv_data = ast;
  431. avio_skip(pb, 3 * 4);
  432. ast->scale = avio_rl32(pb);
  433. ast->rate = avio_rl32(pb);
  434. avio_skip(pb, 4); /* start time */
  435. dv_dur = avio_rl32(pb);
  436. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  437. dv_dur *= AV_TIME_BASE;
  438. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  439. }
  440. /* else, leave duration alone; timing estimation in utils.c
  441. * will make a guess based on bitrate. */
  442. stream_index = s->nb_streams - 1;
  443. avio_skip(pb, size - 9 * 4);
  444. break;
  445. }
  446. assert(stream_index < s->nb_streams);
  447. ast->handler = handler;
  448. avio_rl32(pb); /* flags */
  449. avio_rl16(pb); /* priority */
  450. avio_rl16(pb); /* language */
  451. avio_rl32(pb); /* initial frame */
  452. ast->scale = avio_rl32(pb);
  453. ast->rate = avio_rl32(pb);
  454. if (!(ast->scale && ast->rate)) {
  455. av_log(s, AV_LOG_WARNING,
  456. "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
  457. "(This file has been generated by broken software.)\n",
  458. ast->scale,
  459. ast->rate);
  460. if (frame_period) {
  461. ast->rate = 1000000;
  462. ast->scale = frame_period;
  463. } else {
  464. ast->rate = 25;
  465. ast->scale = 1;
  466. }
  467. }
  468. avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
  469. ast->cum_len = avio_rl32(pb); /* start */
  470. st->nb_frames = avio_rl32(pb);
  471. st->start_time = 0;
  472. avio_rl32(pb); /* buffer size */
  473. avio_rl32(pb); /* quality */
  474. ast->sample_size = avio_rl32(pb); /* sample ssize */
  475. ast->cum_len *= FFMAX(1, ast->sample_size);
  476. av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
  477. ast->rate, ast->scale, ast->sample_size);
  478. switch (tag1) {
  479. case MKTAG('v', 'i', 'd', 's'):
  480. codec_type = AVMEDIA_TYPE_VIDEO;
  481. ast->sample_size = 0;
  482. break;
  483. case MKTAG('a', 'u', 'd', 's'):
  484. codec_type = AVMEDIA_TYPE_AUDIO;
  485. break;
  486. case MKTAG('t', 'x', 't', 's'):
  487. codec_type = AVMEDIA_TYPE_SUBTITLE;
  488. break;
  489. case MKTAG('d', 'a', 't', 's'):
  490. codec_type = AVMEDIA_TYPE_DATA;
  491. break;
  492. default:
  493. av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
  494. goto fail;
  495. }
  496. if (ast->sample_size == 0)
  497. st->duration = st->nb_frames;
  498. ast->frame_offset = ast->cum_len;
  499. avio_skip(pb, size - 12 * 4);
  500. break;
  501. case MKTAG('s', 't', 'r', 'f'):
  502. /* stream header */
  503. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  504. avio_skip(pb, size);
  505. } else {
  506. uint64_t cur_pos = avio_tell(pb);
  507. if (cur_pos < list_end)
  508. size = FFMIN(size, list_end - cur_pos);
  509. st = s->streams[stream_index];
  510. switch (codec_type) {
  511. case AVMEDIA_TYPE_VIDEO:
  512. if (amv_file_format) {
  513. st->codec->width = avih_width;
  514. st->codec->height = avih_height;
  515. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  516. st->codec->codec_id = AV_CODEC_ID_AMV;
  517. avio_skip(pb, size);
  518. break;
  519. }
  520. tag1 = ff_get_bmp_header(pb, st);
  521. if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
  522. tag1 == MKTAG('D', 'X', 'S', 'A')) {
  523. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  524. st->codec->codec_tag = tag1;
  525. st->codec->codec_id = AV_CODEC_ID_XSUB;
  526. break;
  527. }
  528. if (size > 10 * 4 && size < (1 << 30)) {
  529. st->codec->extradata_size = size - 10 * 4;
  530. st->codec->extradata = av_malloc(st->codec->extradata_size +
  531. FF_INPUT_BUFFER_PADDING_SIZE);
  532. if (!st->codec->extradata) {
  533. st->codec->extradata_size = 0;
  534. return AVERROR(ENOMEM);
  535. }
  536. avio_read(pb,
  537. st->codec->extradata,
  538. st->codec->extradata_size);
  539. }
  540. // FIXME: check if the encoder really did this correctly
  541. if (st->codec->extradata_size & 1)
  542. avio_r8(pb);
  543. /* Extract palette from extradata if bpp <= 8.
  544. * This code assumes that extradata contains only palette.
  545. * This is true for all paletted codecs implemented in
  546. * Libav. */
  547. if (st->codec->extradata_size &&
  548. (st->codec->bits_per_coded_sample <= 8)) {
  549. int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
  550. const uint8_t *pal_src;
  551. pal_size = FFMIN(pal_size, st->codec->extradata_size);
  552. pal_src = st->codec->extradata +
  553. st->codec->extradata_size - pal_size;
  554. #if HAVE_BIGENDIAN
  555. for (i = 0; i < pal_size / 4; i++)
  556. ast->pal[i] = av_bswap32(((uint32_t *)pal_src)[i]);
  557. #else
  558. memcpy(ast->pal, pal_src, pal_size);
  559. #endif
  560. ast->has_pal = 1;
  561. }
  562. print_tag("video", tag1, 0);
  563. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  564. st->codec->codec_tag = tag1;
  565. st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
  566. tag1);
  567. /* This is needed to get the pict type which is necessary
  568. * for generating correct pts. */
  569. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  570. if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
  571. ast->handler == MKTAG('X', 'V', 'I', 'D'))
  572. st->codec->codec_tag = MKTAG('X', 'V', 'I', 'D');
  573. // Support "Resolution 1:1" for Avid AVI Codec
  574. if (tag1 == MKTAG('A', 'V', 'R', 'n') &&
  575. st->codec->extradata_size >= 31 &&
  576. !memcmp(&st->codec->extradata[28], "1:1", 3))
  577. st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
  578. if (st->codec->codec_tag == 0 && st->codec->height > 0 &&
  579. st->codec->extradata_size < 1U << 30) {
  580. st->codec->extradata_size += 9;
  581. if ((ret = av_reallocp(&st->codec->extradata,
  582. st->codec->extradata_size +
  583. FF_INPUT_BUFFER_PADDING_SIZE)) < 0) {
  584. st->codec->extradata_size = 0;
  585. return ret;
  586. } else
  587. memcpy(st->codec->extradata + st->codec->extradata_size - 9,
  588. "BottomUp", 9);
  589. }
  590. st->codec->height = FFABS(st->codec->height);
  591. // avio_skip(pb, size - 5 * 4);
  592. break;
  593. case AVMEDIA_TYPE_AUDIO:
  594. ret = ff_get_wav_header(pb, st->codec, size);
  595. if (ret < 0)
  596. return ret;
  597. ast->dshow_block_align = st->codec->block_align;
  598. if (ast->sample_size && st->codec->block_align &&
  599. ast->sample_size != st->codec->block_align) {
  600. av_log(s,
  601. AV_LOG_WARNING,
  602. "sample size (%d) != block align (%d)\n",
  603. ast->sample_size,
  604. st->codec->block_align);
  605. ast->sample_size = st->codec->block_align;
  606. }
  607. /* 2-aligned
  608. * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  609. if (size & 1)
  610. avio_skip(pb, 1);
  611. /* Force parsing as several audio frames can be in
  612. * one packet and timestamps refer to packet start. */
  613. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  614. /* ADTS header is in extradata, AAC without header must be
  615. * stored as exact frames. Parser not needed and it will
  616. * fail. */
  617. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  618. st->codec->extradata_size)
  619. st->need_parsing = AVSTREAM_PARSE_NONE;
  620. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  621. * audio in the header but have Axan as stream_code_tag. */
  622. if (ast->handler == AV_RL32("Axan")) {
  623. st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
  624. st->codec->codec_tag = 0;
  625. }
  626. if (amv_file_format) {
  627. st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
  628. ast->dshow_block_align = 0;
  629. }
  630. break;
  631. case AVMEDIA_TYPE_SUBTITLE:
  632. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  633. st->codec->codec_id = AV_CODEC_ID_PROBE;
  634. break;
  635. default:
  636. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  637. st->codec->codec_id = AV_CODEC_ID_NONE;
  638. st->codec->codec_tag = 0;
  639. avio_skip(pb, size);
  640. break;
  641. }
  642. }
  643. break;
  644. case MKTAG('i', 'n', 'd', 'x'):
  645. i = avio_tell(pb);
  646. if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
  647. read_braindead_odml_indx(s, 0) < 0 &&
  648. (s->error_recognition & AV_EF_EXPLODE))
  649. goto fail;
  650. avio_seek(pb, i + size, SEEK_SET);
  651. break;
  652. case MKTAG('v', 'p', 'r', 'p'):
  653. if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
  654. AVRational active, active_aspect;
  655. st = s->streams[stream_index];
  656. avio_rl32(pb);
  657. avio_rl32(pb);
  658. avio_rl32(pb);
  659. avio_rl32(pb);
  660. avio_rl32(pb);
  661. active_aspect.den = avio_rl16(pb);
  662. active_aspect.num = avio_rl16(pb);
  663. active.num = avio_rl32(pb);
  664. active.den = avio_rl32(pb);
  665. avio_rl32(pb); // nbFieldsPerFrame
  666. if (active_aspect.num && active_aspect.den &&
  667. active.num && active.den) {
  668. st->sample_aspect_ratio = av_div_q(active_aspect, active);
  669. av_dlog(s, "vprp %d/%d %d/%d\n",
  670. active_aspect.num, active_aspect.den,
  671. active.num, active.den);
  672. }
  673. size -= 9 * 4;
  674. }
  675. avio_skip(pb, size);
  676. break;
  677. case MKTAG('s', 't', 'r', 'n'):
  678. if (s->nb_streams) {
  679. ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
  680. if (ret < 0)
  681. return ret;
  682. break;
  683. }
  684. default:
  685. if (size > 1000000) {
  686. av_log(s, AV_LOG_ERROR,
  687. "Something went wrong during header parsing, "
  688. "I will ignore it and try to continue anyway.\n");
  689. if (s->error_recognition & AV_EF_EXPLODE)
  690. goto fail;
  691. avi->movi_list = avio_tell(pb) - 4;
  692. avi->movi_end = avi->fsize;
  693. goto end_of_header;
  694. }
  695. /* skip tag */
  696. size += (size & 1);
  697. avio_skip(pb, size);
  698. break;
  699. }
  700. }
  701. end_of_header:
  702. /* check stream number */
  703. if (stream_index != s->nb_streams - 1) {
  704. fail:
  705. return AVERROR_INVALIDDATA;
  706. }
  707. if (!avi->index_loaded && pb->seekable)
  708. avi_load_index(s);
  709. avi->index_loaded = 1;
  710. if ((ret = guess_ni_flag(s)) < 0)
  711. return ret;
  712. avi->non_interleaved |= ret;
  713. for (i = 0; i < s->nb_streams; i++) {
  714. AVStream *st = s->streams[i];
  715. if (st->nb_index_entries)
  716. break;
  717. }
  718. if (i == s->nb_streams && avi->non_interleaved) {
  719. av_log(s, AV_LOG_WARNING,
  720. "Non-interleaved AVI without index, switching to interleaved\n");
  721. avi->non_interleaved = 0;
  722. }
  723. if (avi->non_interleaved) {
  724. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  725. clean_index(s);
  726. }
  727. ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
  728. ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
  729. return 0;
  730. }
  731. static int read_gab2_sub(AVStream *st, AVPacket *pkt)
  732. {
  733. if (pkt->size >= 7 &&
  734. !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
  735. uint8_t desc[256];
  736. int score = AVPROBE_SCORE_EXTENSION, ret;
  737. AVIStream *ast = st->priv_data;
  738. AVInputFormat *sub_demuxer;
  739. AVRational time_base;
  740. AVIOContext *pb = avio_alloc_context(pkt->data + 7,
  741. pkt->size - 7,
  742. 0, NULL, NULL, NULL, NULL);
  743. AVProbeData pd;
  744. unsigned int desc_len = avio_rl32(pb);
  745. if (desc_len > pb->buf_end - pb->buf_ptr)
  746. goto error;
  747. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  748. avio_skip(pb, desc_len - ret);
  749. if (*desc)
  750. av_dict_set(&st->metadata, "title", desc, 0);
  751. avio_rl16(pb); /* flags? */
  752. avio_rl32(pb); /* data size */
  753. pd = (AVProbeData) { .buf = pb->buf_ptr,
  754. .buf_size = pb->buf_end - pb->buf_ptr };
  755. if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
  756. goto error;
  757. if (!(ast->sub_ctx = avformat_alloc_context()))
  758. goto error;
  759. ast->sub_ctx->pb = pb;
  760. if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
  761. ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
  762. *st->codec = *ast->sub_ctx->streams[0]->codec;
  763. ast->sub_ctx->streams[0]->codec->extradata = NULL;
  764. time_base = ast->sub_ctx->streams[0]->time_base;
  765. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  766. }
  767. ast->sub_buffer = pkt->data;
  768. memset(pkt, 0, sizeof(*pkt));
  769. return 1;
  770. error:
  771. av_freep(&pb);
  772. }
  773. return 0;
  774. }
  775. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  776. AVPacket *pkt)
  777. {
  778. AVIStream *ast, *next_ast = next_st->priv_data;
  779. int64_t ts, next_ts, ts_min = INT64_MAX;
  780. AVStream *st, *sub_st = NULL;
  781. int i;
  782. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  783. AV_TIME_BASE_Q);
  784. for (i = 0; i < s->nb_streams; i++) {
  785. st = s->streams[i];
  786. ast = st->priv_data;
  787. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  788. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  789. if (ts <= next_ts && ts < ts_min) {
  790. ts_min = ts;
  791. sub_st = st;
  792. }
  793. }
  794. }
  795. if (sub_st) {
  796. ast = sub_st->priv_data;
  797. *pkt = ast->sub_pkt;
  798. pkt->stream_index = sub_st->index;
  799. if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  800. ast->sub_pkt.data = NULL;
  801. }
  802. return sub_st;
  803. }
  804. static int get_stream_idx(int *d)
  805. {
  806. if (d[0] >= '0' && d[0] <= '9' &&
  807. d[1] >= '0' && d[1] <= '9') {
  808. return (d[0] - '0') * 10 + (d[1] - '0');
  809. } else {
  810. return 100; // invalid stream ID
  811. }
  812. }
  813. static int avi_sync(AVFormatContext *s, int exit_early)
  814. {
  815. AVIContext *avi = s->priv_data;
  816. AVIOContext *pb = s->pb;
  817. int n;
  818. unsigned int d[8];
  819. unsigned int size;
  820. int64_t i, sync;
  821. start_sync:
  822. memset(d, -1, sizeof(d));
  823. for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
  824. int j;
  825. for (j = 0; j < 7; j++)
  826. d[j] = d[j + 1];
  827. d[7] = avio_r8(pb);
  828. size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
  829. n = get_stream_idx(d + 2);
  830. av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
  831. d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  832. if (i + (uint64_t)size > avi->fsize || d[0] > 127)
  833. continue;
  834. // parse ix##
  835. if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
  836. // parse JUNK
  837. (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
  838. (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
  839. avio_skip(pb, size);
  840. goto start_sync;
  841. }
  842. // parse stray LIST
  843. if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
  844. avio_skip(pb, 4);
  845. goto start_sync;
  846. }
  847. n = avi->dv_demux ? 0 : get_stream_idx(d);
  848. if (!((i - avi->last_pkt_pos) & 1) &&
  849. get_stream_idx(d + 1) < s->nb_streams)
  850. continue;
  851. // detect ##ix chunk and skip
  852. if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
  853. avio_skip(pb, size);
  854. goto start_sync;
  855. }
  856. // parse ##dc/##wb
  857. if (n < s->nb_streams) {
  858. AVStream *st;
  859. AVIStream *ast;
  860. st = s->streams[n];
  861. ast = st->priv_data;
  862. if (s->nb_streams >= 2) {
  863. AVStream *st1 = s->streams[1];
  864. AVIStream *ast1 = st1->priv_data;
  865. // workaround for broken small-file-bug402.avi
  866. if (d[2] == 'w' && d[3] == 'b' && n == 0 &&
  867. st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  868. st1->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  869. ast->prefix == 'd' * 256 + 'c' &&
  870. (d[2] * 256 + d[3] == ast1->prefix ||
  871. !ast1->prefix_count)) {
  872. n = 1;
  873. st = st1;
  874. ast = ast1;
  875. av_log(s, AV_LOG_WARNING,
  876. "Invalid stream + prefix combination, assuming audio.\n");
  877. }
  878. }
  879. if (!avi->dv_demux &&
  880. ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
  881. // FIXME: needs a little reordering
  882. (st->discard >= AVDISCARD_NONKEY &&
  883. !(pkt->flags & AV_PKT_FLAG_KEY)) */
  884. || st->discard >= AVDISCARD_ALL)) {
  885. if (!exit_early) {
  886. ast->frame_offset += get_duration(ast, size);
  887. }
  888. avio_skip(pb, size);
  889. goto start_sync;
  890. }
  891. if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
  892. int k = avio_r8(pb);
  893. int last = (k + avio_r8(pb) - 1) & 0xFF;
  894. avio_rl16(pb); // flags
  895. // b + (g << 8) + (r << 16);
  896. for (; k <= last; k++)
  897. ast->pal[k] = avio_rb32(pb) >> 8;
  898. ast->has_pal = 1;
  899. goto start_sync;
  900. } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
  901. d[2] < 128 && d[3] < 128) ||
  902. d[2] * 256 + d[3] == ast->prefix /* ||
  903. (d[2] == 'd' && d[3] == 'c') ||
  904. (d[2] == 'w' && d[3] == 'b') */) {
  905. if (exit_early)
  906. return 0;
  907. if (d[2] * 256 + d[3] == ast->prefix)
  908. ast->prefix_count++;
  909. else {
  910. ast->prefix = d[2] * 256 + d[3];
  911. ast->prefix_count = 0;
  912. }
  913. avi->stream_index = n;
  914. ast->packet_size = size + 8;
  915. ast->remaining = size;
  916. if (size || !ast->sample_size) {
  917. uint64_t pos = avio_tell(pb) - 8;
  918. if (!st->index_entries || !st->nb_index_entries ||
  919. st->index_entries[st->nb_index_entries - 1].pos < pos) {
  920. av_add_index_entry(st, pos, ast->frame_offset, size,
  921. 0, AVINDEX_KEYFRAME);
  922. }
  923. }
  924. return 0;
  925. }
  926. }
  927. }
  928. return AVERROR_EOF;
  929. }
  930. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  931. {
  932. AVIContext *avi = s->priv_data;
  933. AVIOContext *pb = s->pb;
  934. int err;
  935. #if FF_API_DESTRUCT_PACKET
  936. void *dstr;
  937. #endif
  938. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  939. int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
  940. if (size >= 0)
  941. return size;
  942. else
  943. goto resync;
  944. }
  945. if (avi->non_interleaved) {
  946. int best_stream_index = 0;
  947. AVStream *best_st = NULL;
  948. AVIStream *best_ast;
  949. int64_t best_ts = INT64_MAX;
  950. int i;
  951. for (i = 0; i < s->nb_streams; i++) {
  952. AVStream *st = s->streams[i];
  953. AVIStream *ast = st->priv_data;
  954. int64_t ts = ast->frame_offset;
  955. int64_t last_ts;
  956. if (!st->nb_index_entries)
  957. continue;
  958. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  959. if (!ast->remaining && ts > last_ts)
  960. continue;
  961. ts = av_rescale_q(ts, st->time_base,
  962. (AVRational) { FFMAX(1, ast->sample_size),
  963. AV_TIME_BASE });
  964. av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
  965. st->time_base.num, st->time_base.den, ast->frame_offset);
  966. if (ts < best_ts) {
  967. best_ts = ts;
  968. best_st = st;
  969. best_stream_index = i;
  970. }
  971. }
  972. if (!best_st)
  973. return AVERROR_EOF;
  974. best_ast = best_st->priv_data;
  975. best_ts = av_rescale_q(best_ts,
  976. (AVRational) { FFMAX(1, best_ast->sample_size),
  977. AV_TIME_BASE },
  978. best_st->time_base);
  979. if (best_ast->remaining) {
  980. i = av_index_search_timestamp(best_st,
  981. best_ts,
  982. AVSEEK_FLAG_ANY |
  983. AVSEEK_FLAG_BACKWARD);
  984. } else {
  985. i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  986. if (i >= 0)
  987. best_ast->frame_offset = best_st->index_entries[i].timestamp;
  988. }
  989. if (i >= 0) {
  990. int64_t pos = best_st->index_entries[i].pos;
  991. pos += best_ast->packet_size - best_ast->remaining;
  992. avio_seek(s->pb, pos + 8, SEEK_SET);
  993. assert(best_ast->remaining <= best_ast->packet_size);
  994. avi->stream_index = best_stream_index;
  995. if (!best_ast->remaining)
  996. best_ast->packet_size =
  997. best_ast->remaining = best_st->index_entries[i].size;
  998. }
  999. }
  1000. resync:
  1001. if (avi->stream_index >= 0) {
  1002. AVStream *st = s->streams[avi->stream_index];
  1003. AVIStream *ast = st->priv_data;
  1004. int size, err;
  1005. if (get_subtitle_pkt(s, st, pkt))
  1006. return 0;
  1007. // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  1008. if (ast->sample_size <= 1)
  1009. size = INT_MAX;
  1010. else if (ast->sample_size < 32)
  1011. // arbitrary multiplier to avoid tiny packets for raw PCM data
  1012. size = 1024 * ast->sample_size;
  1013. else
  1014. size = ast->sample_size;
  1015. if (size > ast->remaining)
  1016. size = ast->remaining;
  1017. avi->last_pkt_pos = avio_tell(pb);
  1018. err = av_get_packet(pb, pkt, size);
  1019. if (err < 0)
  1020. return err;
  1021. if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
  1022. uint8_t *pal;
  1023. pal = av_packet_new_side_data(pkt,
  1024. AV_PKT_DATA_PALETTE,
  1025. AVPALETTE_SIZE);
  1026. if (!pal) {
  1027. av_log(s, AV_LOG_ERROR,
  1028. "Failed to allocate data for palette\n");
  1029. } else {
  1030. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  1031. ast->has_pal = 0;
  1032. }
  1033. }
  1034. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1035. AVBufferRef *avbuf = pkt->buf;
  1036. #if FF_API_DESTRUCT_PACKET
  1037. FF_DISABLE_DEPRECATION_WARNINGS
  1038. dstr = pkt->destruct;
  1039. FF_ENABLE_DEPRECATION_WARNINGS
  1040. #endif
  1041. size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
  1042. pkt->data, pkt->size);
  1043. #if FF_API_DESTRUCT_PACKET
  1044. FF_DISABLE_DEPRECATION_WARNINGS
  1045. pkt->destruct = dstr;
  1046. FF_ENABLE_DEPRECATION_WARNINGS
  1047. #endif
  1048. pkt->buf = avbuf;
  1049. pkt->flags |= AV_PKT_FLAG_KEY;
  1050. if (size < 0)
  1051. av_free_packet(pkt);
  1052. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1053. !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
  1054. ast->frame_offset++;
  1055. avi->stream_index = -1;
  1056. ast->remaining = 0;
  1057. goto resync;
  1058. } else {
  1059. /* XXX: How to handle B-frames in AVI? */
  1060. pkt->dts = ast->frame_offset;
  1061. // pkt->dts += ast->start;
  1062. if (ast->sample_size)
  1063. pkt->dts /= ast->sample_size;
  1064. av_dlog(s,
  1065. "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
  1066. "base:%d st:%d size:%d\n",
  1067. pkt->dts,
  1068. ast->frame_offset,
  1069. ast->scale,
  1070. ast->rate,
  1071. ast->sample_size,
  1072. AV_TIME_BASE,
  1073. avi->stream_index,
  1074. size);
  1075. pkt->stream_index = avi->stream_index;
  1076. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1077. AVIndexEntry *e;
  1078. int index;
  1079. assert(st->index_entries);
  1080. index = av_index_search_timestamp(st, ast->frame_offset, 0);
  1081. e = &st->index_entries[index];
  1082. if (index >= 0 && e->timestamp == ast->frame_offset)
  1083. if (e->flags & AVINDEX_KEYFRAME)
  1084. pkt->flags |= AV_PKT_FLAG_KEY;
  1085. } else {
  1086. pkt->flags |= AV_PKT_FLAG_KEY;
  1087. }
  1088. ast->frame_offset += get_duration(ast, pkt->size);
  1089. }
  1090. ast->remaining -= err;
  1091. if (!ast->remaining) {
  1092. avi->stream_index = -1;
  1093. ast->packet_size = 0;
  1094. }
  1095. return 0;
  1096. }
  1097. if ((err = avi_sync(s, 0)) < 0)
  1098. return err;
  1099. goto resync;
  1100. }
  1101. /* XXX: We make the implicit supposition that the positions are sorted
  1102. * for each stream. */
  1103. static int avi_read_idx1(AVFormatContext *s, int size)
  1104. {
  1105. AVIContext *avi = s->priv_data;
  1106. AVIOContext *pb = s->pb;
  1107. int nb_index_entries, i;
  1108. AVStream *st;
  1109. AVIStream *ast;
  1110. unsigned int index, tag, flags, pos, len, first_packet = 1;
  1111. unsigned last_pos = -1;
  1112. int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
  1113. nb_index_entries = size / 16;
  1114. if (nb_index_entries <= 0)
  1115. return AVERROR_INVALIDDATA;
  1116. idx1_pos = avio_tell(pb);
  1117. avio_seek(pb, avi->movi_list + 4, SEEK_SET);
  1118. if (avi_sync(s, 1) == 0)
  1119. first_packet_pos = avio_tell(pb) - 8;
  1120. avi->stream_index = -1;
  1121. avio_seek(pb, idx1_pos, SEEK_SET);
  1122. /* Read the entries and sort them in each stream component. */
  1123. for (i = 0; i < nb_index_entries; i++) {
  1124. tag = avio_rl32(pb);
  1125. flags = avio_rl32(pb);
  1126. pos = avio_rl32(pb);
  1127. len = avio_rl32(pb);
  1128. av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  1129. i, tag, flags, pos, len);
  1130. index = ((tag & 0xff) - '0') * 10;
  1131. index += (tag >> 8 & 0xff) - '0';
  1132. if (index >= s->nb_streams)
  1133. continue;
  1134. st = s->streams[index];
  1135. ast = st->priv_data;
  1136. if (first_packet && first_packet_pos && len) {
  1137. data_offset = first_packet_pos - pos;
  1138. first_packet = 0;
  1139. }
  1140. pos += data_offset;
  1141. av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1142. if (pb->eof_reached)
  1143. return AVERROR_INVALIDDATA;
  1144. if (last_pos == pos)
  1145. avi->non_interleaved = 1;
  1146. else if (len || !ast->sample_size)
  1147. av_add_index_entry(st, pos, ast->cum_len, len, 0,
  1148. (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1149. ast->cum_len += get_duration(ast, len);
  1150. last_pos = pos;
  1151. }
  1152. return 0;
  1153. }
  1154. /* Scan the index and consider any file with streams more than
  1155. * 2 seconds or 64MB apart non-interleaved. */
  1156. static int check_stream_max_drift(AVFormatContext *s)
  1157. {
  1158. int64_t min_pos, pos;
  1159. int i;
  1160. int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
  1161. if (!idx)
  1162. return AVERROR(ENOMEM);
  1163. for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
  1164. int64_t max_dts = INT64_MIN / 2;
  1165. int64_t min_dts = INT64_MAX / 2;
  1166. int64_t max_buffer = 0;
  1167. min_pos = INT64_MAX;
  1168. for (i = 0; i < s->nb_streams; i++) {
  1169. AVStream *st = s->streams[i];
  1170. AVIStream *ast = st->priv_data;
  1171. int n = st->nb_index_entries;
  1172. while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
  1173. idx[i]++;
  1174. if (idx[i] < n) {
  1175. int64_t dts;
  1176. dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
  1177. FFMAX(ast->sample_size, 1),
  1178. st->time_base, AV_TIME_BASE_Q);
  1179. min_dts = FFMIN(min_dts, dts);
  1180. min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
  1181. }
  1182. }
  1183. for (i = 0; i < s->nb_streams; i++) {
  1184. AVStream *st = s->streams[i];
  1185. AVIStream *ast = st->priv_data;
  1186. if (idx[i] && min_dts != INT64_MAX / 2) {
  1187. int64_t dts;
  1188. dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
  1189. FFMAX(ast->sample_size, 1),
  1190. st->time_base, AV_TIME_BASE_Q);
  1191. max_dts = FFMAX(max_dts, dts);
  1192. max_buffer = FFMAX(max_buffer,
  1193. av_rescale(dts - min_dts,
  1194. st->codec->bit_rate,
  1195. AV_TIME_BASE));
  1196. }
  1197. }
  1198. if (max_dts - min_dts > 2 * AV_TIME_BASE ||
  1199. max_buffer > 1024 * 1024 * 8 * 8) {
  1200. av_free(idx);
  1201. return 1;
  1202. }
  1203. }
  1204. av_free(idx);
  1205. return 0;
  1206. }
  1207. static int guess_ni_flag(AVFormatContext *s)
  1208. {
  1209. int i;
  1210. int64_t last_start = 0;
  1211. int64_t first_end = INT64_MAX;
  1212. int64_t oldpos = avio_tell(s->pb);
  1213. for (i = 0; i < s->nb_streams; i++) {
  1214. AVStream *st = s->streams[i];
  1215. int n = st->nb_index_entries;
  1216. unsigned int size;
  1217. if (n <= 0)
  1218. continue;
  1219. if (n >= 2) {
  1220. int64_t pos = st->index_entries[0].pos;
  1221. avio_seek(s->pb, pos + 4, SEEK_SET);
  1222. size = avio_rl32(s->pb);
  1223. if (pos + size > st->index_entries[1].pos)
  1224. last_start = INT64_MAX;
  1225. }
  1226. if (st->index_entries[0].pos > last_start)
  1227. last_start = st->index_entries[0].pos;
  1228. if (st->index_entries[n - 1].pos < first_end)
  1229. first_end = st->index_entries[n - 1].pos;
  1230. }
  1231. avio_seek(s->pb, oldpos, SEEK_SET);
  1232. if (last_start > first_end)
  1233. return 1;
  1234. return check_stream_max_drift(s);
  1235. }
  1236. static int avi_load_index(AVFormatContext *s)
  1237. {
  1238. AVIContext *avi = s->priv_data;
  1239. AVIOContext *pb = s->pb;
  1240. uint32_t tag, size;
  1241. int64_t pos = avio_tell(pb);
  1242. int ret = -1;
  1243. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1244. goto the_end; // maybe truncated file
  1245. av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1246. for (;;) {
  1247. if (pb->eof_reached)
  1248. break;
  1249. tag = avio_rl32(pb);
  1250. size = avio_rl32(pb);
  1251. av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
  1252. tag & 0xff,
  1253. (tag >> 8) & 0xff,
  1254. (tag >> 16) & 0xff,
  1255. (tag >> 24) & 0xff,
  1256. size);
  1257. if (tag == MKTAG('i', 'd', 'x', '1') &&
  1258. avi_read_idx1(s, size) >= 0) {
  1259. ret = 0;
  1260. break;
  1261. }
  1262. size += (size & 1);
  1263. if (avio_skip(pb, size) < 0)
  1264. break; // something is wrong here
  1265. }
  1266. the_end:
  1267. avio_seek(pb, pos, SEEK_SET);
  1268. return ret;
  1269. }
  1270. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1271. {
  1272. AVIStream *ast2 = st2->priv_data;
  1273. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1274. av_free_packet(&ast2->sub_pkt);
  1275. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1276. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1277. ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1278. }
  1279. static int avi_read_seek(AVFormatContext *s, int stream_index,
  1280. int64_t timestamp, int flags)
  1281. {
  1282. AVIContext *avi = s->priv_data;
  1283. AVStream *st;
  1284. int i, index;
  1285. int64_t pos;
  1286. AVIStream *ast;
  1287. /* Does not matter which stream is requested dv in avi has the
  1288. * stream information in the first video stream.
  1289. */
  1290. if (avi->dv_demux)
  1291. stream_index = 0;
  1292. if (!avi->index_loaded) {
  1293. /* we only load the index on demand */
  1294. avi_load_index(s);
  1295. avi->index_loaded = 1;
  1296. }
  1297. st = s->streams[stream_index];
  1298. ast = st->priv_data;
  1299. index = av_index_search_timestamp(st,
  1300. timestamp * FFMAX(ast->sample_size, 1),
  1301. flags);
  1302. if (index < 0)
  1303. return AVERROR_INVALIDDATA;
  1304. /* find the position */
  1305. pos = st->index_entries[index].pos;
  1306. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1307. av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
  1308. timestamp, index, st->index_entries[index].timestamp);
  1309. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1310. /* One and only one real stream for DV in AVI, and it has video */
  1311. /* offsets. Calling with other stream indexes should have failed */
  1312. /* the av_index_search_timestamp call above. */
  1313. /* Feed the DV video stream version of the timestamp to the */
  1314. /* DV demux so it can synthesize correct timestamps. */
  1315. ff_dv_offset_reset(avi->dv_demux, timestamp);
  1316. avio_seek(s->pb, pos, SEEK_SET);
  1317. avi->stream_index = -1;
  1318. return 0;
  1319. }
  1320. for (i = 0; i < s->nb_streams; i++) {
  1321. AVStream *st2 = s->streams[i];
  1322. AVIStream *ast2 = st2->priv_data;
  1323. ast2->packet_size =
  1324. ast2->remaining = 0;
  1325. if (ast2->sub_ctx) {
  1326. seek_subtitle(st, st2, timestamp);
  1327. continue;
  1328. }
  1329. if (st2->nb_index_entries <= 0)
  1330. continue;
  1331. // assert(st2->codec->block_align);
  1332. assert((int64_t)st2->time_base.num * ast2->rate ==
  1333. (int64_t)st2->time_base.den * ast2->scale);
  1334. index = av_index_search_timestamp(st2,
  1335. av_rescale_q(timestamp,
  1336. st->time_base,
  1337. st2->time_base) *
  1338. FFMAX(ast2->sample_size, 1),
  1339. flags | AVSEEK_FLAG_BACKWARD);
  1340. if (index < 0)
  1341. index = 0;
  1342. if (!avi->non_interleaved) {
  1343. while (index > 0 && st2->index_entries[index].pos > pos)
  1344. index--;
  1345. while (index + 1 < st2->nb_index_entries &&
  1346. st2->index_entries[index].pos < pos)
  1347. index++;
  1348. }
  1349. av_dlog(s, "%"PRId64" %d %"PRId64"\n",
  1350. timestamp, index, st2->index_entries[index].timestamp);
  1351. /* extract the current frame number */
  1352. ast2->frame_offset = st2->index_entries[index].timestamp;
  1353. }
  1354. /* do the seek */
  1355. avio_seek(s->pb, pos, SEEK_SET);
  1356. avi->stream_index = -1;
  1357. return 0;
  1358. }
  1359. static int avi_read_close(AVFormatContext *s)
  1360. {
  1361. int i;
  1362. AVIContext *avi = s->priv_data;
  1363. for (i = 0; i < s->nb_streams; i++) {
  1364. AVStream *st = s->streams[i];
  1365. AVIStream *ast = st->priv_data;
  1366. if (ast) {
  1367. if (ast->sub_ctx) {
  1368. av_freep(&ast->sub_ctx->pb);
  1369. avformat_close_input(&ast->sub_ctx);
  1370. }
  1371. av_free(ast->sub_buffer);
  1372. av_free_packet(&ast->sub_pkt);
  1373. }
  1374. }
  1375. av_free(avi->dv_demux);
  1376. return 0;
  1377. }
  1378. static int avi_probe(AVProbeData *p)
  1379. {
  1380. int i;
  1381. /* check file header */
  1382. for (i = 0; avi_headers[i][0]; i++)
  1383. if (!memcmp(p->buf, avi_headers[i], 4) &&
  1384. !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
  1385. return AVPROBE_SCORE_MAX;
  1386. return 0;
  1387. }
  1388. AVInputFormat ff_avi_demuxer = {
  1389. .name = "avi",
  1390. .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
  1391. .priv_data_size = sizeof(AVIContext),
  1392. .extensions = "avi",
  1393. .read_probe = avi_probe,
  1394. .read_header = avi_read_header,
  1395. .read_packet = avi_read_packet,
  1396. .read_close = avi_read_close,
  1397. .read_seek = avi_read_seek,
  1398. };