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.

1926 lines
66KB

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