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.

1951 lines
67KB

  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 && !avio_feof(s->pb)) {
  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 && !avio_feof(s->pb)) {
  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(AVFormatContext *s, AVStream *st)
  334. {
  335. GetByteContext gb;
  336. uint8_t *data = st->codecpar->extradata;
  337. int data_size = st->codecpar->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(s, &gb, 1, 0, &st->metadata);
  352. break;
  353. case MKTAG('C', 'A', 'S', 'I'):
  354. avpriv_request_sample(s, "RIFF stream data tag type CASI (%u)", tag);
  355. break;
  356. case MKTAG('Z', 'o', 'r', 'a'):
  357. avpriv_request_sample(s, "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->codecpar->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->codecpar->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]->codecpar->extradata);
  518. av_freep(&s->streams[0]->codecpar);
  519. av_freep(&s->streams[0]->codec);
  520. if (s->streams[0]->info)
  521. av_freep(&s->streams[0]->info->duration_error);
  522. av_freep(&s->streams[0]->info);
  523. if (s->streams[0]->internal)
  524. av_freep(&s->streams[0]->internal->avctx);
  525. av_freep(&s->streams[0]->internal);
  526. av_freep(&s->streams[0]);
  527. s->nb_streams = 0;
  528. if (CONFIG_DV_DEMUXER) {
  529. avi->dv_demux = avpriv_dv_init_demux(s);
  530. if (!avi->dv_demux)
  531. goto fail;
  532. } else
  533. goto fail;
  534. s->streams[0]->priv_data = ast;
  535. avio_skip(pb, 3 * 4);
  536. ast->scale = avio_rl32(pb);
  537. ast->rate = avio_rl32(pb);
  538. avio_skip(pb, 4); /* start time */
  539. dv_dur = avio_rl32(pb);
  540. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  541. dv_dur *= AV_TIME_BASE;
  542. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  543. }
  544. /* else, leave duration alone; timing estimation in utils.c
  545. * will make a guess based on bitrate. */
  546. stream_index = s->nb_streams - 1;
  547. avio_skip(pb, size - 9 * 4);
  548. break;
  549. }
  550. av_assert0(stream_index < s->nb_streams);
  551. ast->handler = handler;
  552. avio_rl32(pb); /* flags */
  553. avio_rl16(pb); /* priority */
  554. avio_rl16(pb); /* language */
  555. avio_rl32(pb); /* initial frame */
  556. ast->scale = avio_rl32(pb);
  557. ast->rate = avio_rl32(pb);
  558. if (!(ast->scale && ast->rate)) {
  559. av_log(s, AV_LOG_WARNING,
  560. "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
  561. "(This file has been generated by broken software.)\n",
  562. ast->scale,
  563. ast->rate);
  564. if (frame_period) {
  565. ast->rate = 1000000;
  566. ast->scale = frame_period;
  567. } else {
  568. ast->rate = 25;
  569. ast->scale = 1;
  570. }
  571. }
  572. avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
  573. ast->cum_len = avio_rl32(pb); /* start */
  574. st->nb_frames = avio_rl32(pb);
  575. st->start_time = 0;
  576. avio_rl32(pb); /* buffer size */
  577. avio_rl32(pb); /* quality */
  578. if (ast->cum_len*ast->scale/ast->rate > 3600) {
  579. av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
  580. ast->cum_len = 0;
  581. }
  582. ast->sample_size = avio_rl32(pb);
  583. ast->cum_len *= FFMAX(1, ast->sample_size);
  584. av_log(s, AV_LOG_TRACE, "%"PRIu32" %"PRIu32" %d\n",
  585. ast->rate, ast->scale, ast->sample_size);
  586. switch (tag1) {
  587. case MKTAG('v', 'i', 'd', 's'):
  588. codec_type = AVMEDIA_TYPE_VIDEO;
  589. ast->sample_size = 0;
  590. st->avg_frame_rate = av_inv_q(st->time_base);
  591. break;
  592. case MKTAG('a', 'u', 'd', 's'):
  593. codec_type = AVMEDIA_TYPE_AUDIO;
  594. break;
  595. case MKTAG('t', 'x', 't', 's'):
  596. codec_type = AVMEDIA_TYPE_SUBTITLE;
  597. break;
  598. case MKTAG('d', 'a', 't', 's'):
  599. codec_type = AVMEDIA_TYPE_DATA;
  600. break;
  601. default:
  602. av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
  603. }
  604. if (ast->sample_size < 0) {
  605. if (s->error_recognition & AV_EF_EXPLODE) {
  606. av_log(s, AV_LOG_ERROR,
  607. "Invalid sample_size %d at stream %d\n",
  608. ast->sample_size,
  609. stream_index);
  610. goto fail;
  611. }
  612. av_log(s, AV_LOG_WARNING,
  613. "Invalid sample_size %d at stream %d "
  614. "setting it to 0\n",
  615. ast->sample_size,
  616. stream_index);
  617. ast->sample_size = 0;
  618. }
  619. if (ast->sample_size == 0) {
  620. st->duration = st->nb_frames;
  621. if (st->duration > 0 && avi->io_fsize > 0 && avi->riff_end > avi->io_fsize) {
  622. av_log(s, AV_LOG_DEBUG, "File is truncated adjusting duration\n");
  623. st->duration = av_rescale(st->duration, avi->io_fsize, avi->riff_end);
  624. }
  625. }
  626. ast->frame_offset = ast->cum_len;
  627. avio_skip(pb, size - 12 * 4);
  628. break;
  629. case MKTAG('s', 't', 'r', 'f'):
  630. /* stream header */
  631. if (!size)
  632. break;
  633. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  634. avio_skip(pb, size);
  635. } else {
  636. uint64_t cur_pos = avio_tell(pb);
  637. unsigned esize;
  638. if (cur_pos < list_end)
  639. size = FFMIN(size, list_end - cur_pos);
  640. st = s->streams[stream_index];
  641. if (st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN) {
  642. avio_skip(pb, size);
  643. break;
  644. }
  645. switch (codec_type) {
  646. case AVMEDIA_TYPE_VIDEO:
  647. if (amv_file_format) {
  648. st->codecpar->width = avih_width;
  649. st->codecpar->height = avih_height;
  650. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  651. st->codecpar->codec_id = AV_CODEC_ID_AMV;
  652. avio_skip(pb, size);
  653. break;
  654. }
  655. tag1 = ff_get_bmp_header(pb, st, &esize);
  656. if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
  657. tag1 == MKTAG('D', 'X', 'S', 'A')) {
  658. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  659. st->codecpar->codec_tag = tag1;
  660. st->codecpar->codec_id = AV_CODEC_ID_XSUB;
  661. break;
  662. }
  663. if (size > 10 * 4 && size < (1 << 30) && size < avi->fsize) {
  664. if (esize == size-1 && (esize&1)) {
  665. st->codecpar->extradata_size = esize - 10 * 4;
  666. } else
  667. st->codecpar->extradata_size = size - 10 * 4;
  668. if (ff_get_extradata(s, st->codecpar, pb, st->codecpar->extradata_size) < 0)
  669. return AVERROR(ENOMEM);
  670. }
  671. // FIXME: check if the encoder really did this correctly
  672. if (st->codecpar->extradata_size & 1)
  673. avio_r8(pb);
  674. /* Extract palette from extradata if bpp <= 8.
  675. * This code assumes that extradata contains only palette.
  676. * This is true for all paletted codecs implemented in
  677. * FFmpeg. */
  678. if (st->codecpar->extradata_size &&
  679. (st->codecpar->bits_per_coded_sample <= 8)) {
  680. int pal_size = (1 << st->codecpar->bits_per_coded_sample) << 2;
  681. const uint8_t *pal_src;
  682. pal_size = FFMIN(pal_size, st->codecpar->extradata_size);
  683. pal_src = st->codecpar->extradata +
  684. st->codecpar->extradata_size - pal_size;
  685. /* Exclude the "BottomUp" field from the palette */
  686. if (pal_src - st->codecpar->extradata >= 9 &&
  687. !memcmp(st->codecpar->extradata + st->codecpar->extradata_size - 9, "BottomUp", 9))
  688. pal_src -= 9;
  689. for (i = 0; i < pal_size / 4; i++)
  690. ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src+4*i);
  691. ast->has_pal = 1;
  692. }
  693. print_tag("video", tag1, 0);
  694. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  695. st->codecpar->codec_tag = tag1;
  696. st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
  697. tag1);
  698. /* If codec is not found yet, try with the mov tags. */
  699. if (!st->codecpar->codec_id) {
  700. char tag_buf[32];
  701. av_get_codec_tag_string(tag_buf, sizeof(tag_buf), tag1);
  702. st->codecpar->codec_id =
  703. ff_codec_get_id(ff_codec_movvideo_tags, tag1);
  704. if (st->codecpar->codec_id)
  705. av_log(s, AV_LOG_WARNING,
  706. "mov tag found in avi (fourcc %s)\n",
  707. tag_buf);
  708. }
  709. /* This is needed to get the pict type which is necessary
  710. * for generating correct pts. */
  711. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  712. if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4 &&
  713. ast->handler == MKTAG('X', 'V', 'I', 'D'))
  714. st->codecpar->codec_tag = MKTAG('X', 'V', 'I', 'D');
  715. if (st->codecpar->codec_tag == MKTAG('V', 'S', 'S', 'H'))
  716. st->need_parsing = AVSTREAM_PARSE_FULL;
  717. if (st->codecpar->codec_id == AV_CODEC_ID_RV40)
  718. st->need_parsing = AVSTREAM_PARSE_NONE;
  719. if (st->codecpar->codec_tag == 0 && st->codecpar->height > 0 &&
  720. st->codecpar->extradata_size < 1U << 30) {
  721. st->codecpar->extradata_size += 9;
  722. if ((ret = av_reallocp(&st->codecpar->extradata,
  723. st->codecpar->extradata_size +
  724. AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {
  725. st->codecpar->extradata_size = 0;
  726. return ret;
  727. } else
  728. memcpy(st->codecpar->extradata + st->codecpar->extradata_size - 9,
  729. "BottomUp", 9);
  730. }
  731. st->codecpar->height = FFABS(st->codecpar->height);
  732. // avio_skip(pb, size - 5 * 4);
  733. break;
  734. case AVMEDIA_TYPE_AUDIO:
  735. ret = ff_get_wav_header(s, pb, st->codecpar, size, 0);
  736. if (ret < 0)
  737. return ret;
  738. ast->dshow_block_align = st->codecpar->block_align;
  739. if (ast->sample_size && st->codecpar->block_align &&
  740. ast->sample_size != st->codecpar->block_align) {
  741. av_log(s,
  742. AV_LOG_WARNING,
  743. "sample size (%d) != block align (%d)\n",
  744. ast->sample_size,
  745. st->codecpar->block_align);
  746. ast->sample_size = st->codecpar->block_align;
  747. }
  748. /* 2-aligned
  749. * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  750. if (size & 1)
  751. avio_skip(pb, 1);
  752. /* Force parsing as several audio frames can be in
  753. * one packet and timestamps refer to packet start. */
  754. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  755. /* ADTS header is in extradata, AAC without header must be
  756. * stored as exact frames. Parser not needed and it will
  757. * fail. */
  758. if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
  759. st->codecpar->extradata_size)
  760. st->need_parsing = AVSTREAM_PARSE_NONE;
  761. // The flac parser does not work with AVSTREAM_PARSE_TIMESTAMPS
  762. if (st->codecpar->codec_id == AV_CODEC_ID_FLAC)
  763. st->need_parsing = AVSTREAM_PARSE_NONE;
  764. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  765. * audio in the header but have Axan as stream_code_tag. */
  766. if (ast->handler == AV_RL32("Axan")) {
  767. st->codecpar->codec_id = AV_CODEC_ID_XAN_DPCM;
  768. st->codecpar->codec_tag = 0;
  769. ast->dshow_block_align = 0;
  770. }
  771. if (amv_file_format) {
  772. st->codecpar->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
  773. ast->dshow_block_align = 0;
  774. }
  775. if ((st->codecpar->codec_id == AV_CODEC_ID_AAC ||
  776. st->codecpar->codec_id == AV_CODEC_ID_FLAC ||
  777. st->codecpar->codec_id == AV_CODEC_ID_MP2 ) && ast->dshow_block_align <= 4 && ast->dshow_block_align) {
  778. av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align);
  779. ast->dshow_block_align = 0;
  780. }
  781. if (st->codecpar->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 ||
  782. st->codecpar->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 ||
  783. st->codecpar->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) {
  784. av_log(s, AV_LOG_DEBUG, "overriding sample_size\n");
  785. ast->sample_size = 0;
  786. }
  787. break;
  788. case AVMEDIA_TYPE_SUBTITLE:
  789. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  790. st->request_probe= 1;
  791. avio_skip(pb, size);
  792. break;
  793. default:
  794. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  795. st->codecpar->codec_id = AV_CODEC_ID_NONE;
  796. st->codecpar->codec_tag = 0;
  797. avio_skip(pb, size);
  798. break;
  799. }
  800. }
  801. break;
  802. case MKTAG('s', 't', 'r', 'd'):
  803. if (stream_index >= (unsigned)s->nb_streams
  804. || s->streams[stream_index]->codecpar->extradata_size
  805. || s->streams[stream_index]->codecpar->codec_tag == MKTAG('H','2','6','4')) {
  806. avio_skip(pb, size);
  807. } else {
  808. uint64_t cur_pos = avio_tell(pb);
  809. if (cur_pos < list_end)
  810. size = FFMIN(size, list_end - cur_pos);
  811. st = s->streams[stream_index];
  812. if (size<(1<<30)) {
  813. if (ff_get_extradata(s, st->codecpar, pb, size) < 0)
  814. return AVERROR(ENOMEM);
  815. }
  816. if (st->codecpar->extradata_size & 1) //FIXME check if the encoder really did this correctly
  817. avio_r8(pb);
  818. ret = avi_extract_stream_metadata(s, st);
  819. if (ret < 0) {
  820. av_log(s, AV_LOG_WARNING, "could not decoding EXIF data in stream header.\n");
  821. }
  822. }
  823. break;
  824. case MKTAG('i', 'n', 'd', 'x'):
  825. pos = avio_tell(pb);
  826. if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
  827. avi->use_odml &&
  828. read_braindead_odml_indx(s, 0) < 0 &&
  829. (s->error_recognition & AV_EF_EXPLODE))
  830. goto fail;
  831. avio_seek(pb, pos + size, SEEK_SET);
  832. break;
  833. case MKTAG('v', 'p', 'r', 'p'):
  834. if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
  835. AVRational active, active_aspect;
  836. st = s->streams[stream_index];
  837. avio_rl32(pb);
  838. avio_rl32(pb);
  839. avio_rl32(pb);
  840. avio_rl32(pb);
  841. avio_rl32(pb);
  842. active_aspect.den = avio_rl16(pb);
  843. active_aspect.num = avio_rl16(pb);
  844. active.num = avio_rl32(pb);
  845. active.den = avio_rl32(pb);
  846. avio_rl32(pb); // nbFieldsPerFrame
  847. if (active_aspect.num && active_aspect.den &&
  848. active.num && active.den) {
  849. st->sample_aspect_ratio = av_div_q(active_aspect, active);
  850. av_log(s, AV_LOG_TRACE, "vprp %d/%d %d/%d\n",
  851. active_aspect.num, active_aspect.den,
  852. active.num, active.den);
  853. }
  854. size -= 9 * 4;
  855. }
  856. avio_skip(pb, size);
  857. break;
  858. case MKTAG('s', 't', 'r', 'n'):
  859. if (s->nb_streams) {
  860. ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
  861. if (ret < 0)
  862. return ret;
  863. break;
  864. }
  865. default:
  866. if (size > 1000000) {
  867. av_log(s, AV_LOG_ERROR,
  868. "Something went wrong during header parsing, "
  869. "I will ignore it and try to continue anyway.\n");
  870. if (s->error_recognition & AV_EF_EXPLODE)
  871. goto fail;
  872. avi->movi_list = avio_tell(pb) - 4;
  873. avi->movi_end = avi->fsize;
  874. goto end_of_header;
  875. }
  876. /* skip tag */
  877. size += (size & 1);
  878. avio_skip(pb, size);
  879. break;
  880. }
  881. }
  882. end_of_header:
  883. /* check stream number */
  884. if (stream_index != s->nb_streams - 1) {
  885. fail:
  886. return AVERROR_INVALIDDATA;
  887. }
  888. if (!avi->index_loaded && pb->seekable)
  889. avi_load_index(s);
  890. calculate_bitrate(s);
  891. avi->index_loaded |= 1;
  892. if ((ret = guess_ni_flag(s)) < 0)
  893. return ret;
  894. avi->non_interleaved |= ret | (s->flags & AVFMT_FLAG_SORT_DTS);
  895. dict_entry = av_dict_get(s->metadata, "ISFT", NULL, 0);
  896. if (dict_entry && !strcmp(dict_entry->value, "PotEncoder"))
  897. for (i = 0; i < s->nb_streams; i++) {
  898. AVStream *st = s->streams[i];
  899. if ( st->codecpar->codec_id == AV_CODEC_ID_MPEG1VIDEO
  900. || st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO)
  901. st->need_parsing = AVSTREAM_PARSE_FULL;
  902. }
  903. for (i = 0; i < s->nb_streams; i++) {
  904. AVStream *st = s->streams[i];
  905. if (st->nb_index_entries)
  906. break;
  907. }
  908. // DV-in-AVI cannot be non-interleaved, if set this must be
  909. // a mis-detection.
  910. if (avi->dv_demux)
  911. avi->non_interleaved = 0;
  912. if (i == s->nb_streams && avi->non_interleaved) {
  913. av_log(s, AV_LOG_WARNING,
  914. "Non-interleaved AVI without index, switching to interleaved\n");
  915. avi->non_interleaved = 0;
  916. }
  917. if (avi->non_interleaved) {
  918. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  919. clean_index(s);
  920. }
  921. ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
  922. ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
  923. return 0;
  924. }
  925. static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt)
  926. {
  927. if (pkt->size >= 7 &&
  928. pkt->size < INT_MAX - AVPROBE_PADDING_SIZE &&
  929. !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
  930. uint8_t desc[256];
  931. int score = AVPROBE_SCORE_EXTENSION, ret;
  932. AVIStream *ast = st->priv_data;
  933. AVInputFormat *sub_demuxer;
  934. AVRational time_base;
  935. int size;
  936. AVIOContext *pb = avio_alloc_context(pkt->data + 7,
  937. pkt->size - 7,
  938. 0, NULL, NULL, NULL, NULL);
  939. AVProbeData pd;
  940. unsigned int desc_len = avio_rl32(pb);
  941. if (desc_len > pb->buf_end - pb->buf_ptr)
  942. goto error;
  943. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  944. avio_skip(pb, desc_len - ret);
  945. if (*desc)
  946. av_dict_set(&st->metadata, "title", desc, 0);
  947. avio_rl16(pb); /* flags? */
  948. avio_rl32(pb); /* data size */
  949. size = pb->buf_end - pb->buf_ptr;
  950. pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE),
  951. .buf_size = size };
  952. if (!pd.buf)
  953. goto error;
  954. memcpy(pd.buf, pb->buf_ptr, size);
  955. sub_demuxer = av_probe_input_format2(&pd, 1, &score);
  956. av_freep(&pd.buf);
  957. if (!sub_demuxer)
  958. goto error;
  959. if (strcmp(sub_demuxer->name, "srt") && strcmp(sub_demuxer->name, "ass"))
  960. goto error;
  961. if (!(ast->sub_ctx = avformat_alloc_context()))
  962. goto error;
  963. ast->sub_ctx->pb = pb;
  964. if (ff_copy_whiteblacklists(ast->sub_ctx, s) < 0)
  965. goto error;
  966. if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
  967. if (ast->sub_ctx->nb_streams != 1)
  968. goto error;
  969. ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
  970. avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar);
  971. time_base = ast->sub_ctx->streams[0]->time_base;
  972. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  973. }
  974. ast->sub_buffer = pkt->data;
  975. memset(pkt, 0, sizeof(*pkt));
  976. return 1;
  977. error:
  978. av_freep(&ast->sub_ctx);
  979. av_freep(&pb);
  980. }
  981. return 0;
  982. }
  983. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  984. AVPacket *pkt)
  985. {
  986. AVIStream *ast, *next_ast = next_st->priv_data;
  987. int64_t ts, next_ts, ts_min = INT64_MAX;
  988. AVStream *st, *sub_st = NULL;
  989. int i;
  990. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  991. AV_TIME_BASE_Q);
  992. for (i = 0; i < s->nb_streams; i++) {
  993. st = s->streams[i];
  994. ast = st->priv_data;
  995. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  996. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  997. if (ts <= next_ts && ts < ts_min) {
  998. ts_min = ts;
  999. sub_st = st;
  1000. }
  1001. }
  1002. }
  1003. if (sub_st) {
  1004. ast = sub_st->priv_data;
  1005. *pkt = ast->sub_pkt;
  1006. pkt->stream_index = sub_st->index;
  1007. if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  1008. ast->sub_pkt.data = NULL;
  1009. }
  1010. return sub_st;
  1011. }
  1012. static int get_stream_idx(const unsigned *d)
  1013. {
  1014. if (d[0] >= '0' && d[0] <= '9' &&
  1015. d[1] >= '0' && d[1] <= '9') {
  1016. return (d[0] - '0') * 10 + (d[1] - '0');
  1017. } else {
  1018. return 100; // invalid stream ID
  1019. }
  1020. }
  1021. /**
  1022. *
  1023. * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
  1024. */
  1025. static int avi_sync(AVFormatContext *s, int exit_early)
  1026. {
  1027. AVIContext *avi = s->priv_data;
  1028. AVIOContext *pb = s->pb;
  1029. int n;
  1030. unsigned int d[8];
  1031. unsigned int size;
  1032. int64_t i, sync;
  1033. start_sync:
  1034. memset(d, -1, sizeof(d));
  1035. for (i = sync = avio_tell(pb); !avio_feof(pb); i++) {
  1036. int j;
  1037. for (j = 0; j < 7; j++)
  1038. d[j] = d[j + 1];
  1039. d[7] = avio_r8(pb);
  1040. size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
  1041. n = get_stream_idx(d + 2);
  1042. ff_tlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
  1043. d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  1044. if (i*(avi->io_fsize>0) + (uint64_t)size > avi->fsize || d[0] > 127)
  1045. continue;
  1046. // parse ix##
  1047. if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
  1048. // parse JUNK
  1049. (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
  1050. (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1') ||
  1051. (d[0] == 'i' && d[1] == 'n' && d[2] == 'd' && d[3] == 'x')) {
  1052. avio_skip(pb, size);
  1053. goto start_sync;
  1054. }
  1055. // parse stray LIST
  1056. if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
  1057. avio_skip(pb, 4);
  1058. goto start_sync;
  1059. }
  1060. n = get_stream_idx(d);
  1061. if (!((i - avi->last_pkt_pos) & 1) &&
  1062. get_stream_idx(d + 1) < s->nb_streams)
  1063. continue;
  1064. // detect ##ix chunk and skip
  1065. if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
  1066. avio_skip(pb, size);
  1067. goto start_sync;
  1068. }
  1069. if (avi->dv_demux && n != 0)
  1070. continue;
  1071. // parse ##dc/##wb
  1072. if (n < s->nb_streams) {
  1073. AVStream *st;
  1074. AVIStream *ast;
  1075. st = s->streams[n];
  1076. ast = st->priv_data;
  1077. if (!ast) {
  1078. av_log(s, AV_LOG_WARNING, "Skipping foreign stream %d packet\n", n);
  1079. continue;
  1080. }
  1081. if (s->nb_streams >= 2) {
  1082. AVStream *st1 = s->streams[1];
  1083. AVIStream *ast1 = st1->priv_data;
  1084. // workaround for broken small-file-bug402.avi
  1085. if ( d[2] == 'w' && d[3] == 'b'
  1086. && n == 0
  1087. && st ->codecpar->codec_type == AVMEDIA_TYPE_VIDEO
  1088. && st1->codecpar->codec_type == AVMEDIA_TYPE_AUDIO
  1089. && ast->prefix == 'd'*256+'c'
  1090. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  1091. ) {
  1092. n = 1;
  1093. st = st1;
  1094. ast = ast1;
  1095. av_log(s, AV_LOG_WARNING,
  1096. "Invalid stream + prefix combination, assuming audio.\n");
  1097. }
  1098. }
  1099. if (!avi->dv_demux &&
  1100. ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
  1101. // FIXME: needs a little reordering
  1102. (st->discard >= AVDISCARD_NONKEY &&
  1103. !(pkt->flags & AV_PKT_FLAG_KEY)) */
  1104. || st->discard >= AVDISCARD_ALL)) {
  1105. if (!exit_early) {
  1106. ast->frame_offset += get_duration(ast, size);
  1107. avio_skip(pb, size);
  1108. goto start_sync;
  1109. }
  1110. }
  1111. if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
  1112. int k = avio_r8(pb);
  1113. int last = (k + avio_r8(pb) - 1) & 0xFF;
  1114. avio_rl16(pb); // flags
  1115. // b + (g << 8) + (r << 16);
  1116. for (; k <= last; k++)
  1117. ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8;
  1118. ast->has_pal = 1;
  1119. goto start_sync;
  1120. } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
  1121. d[2] < 128 && d[3] < 128) ||
  1122. d[2] * 256 + d[3] == ast->prefix /* ||
  1123. (d[2] == 'd' && d[3] == 'c') ||
  1124. (d[2] == 'w' && d[3] == 'b') */) {
  1125. if (exit_early)
  1126. return 0;
  1127. if (d[2] * 256 + d[3] == ast->prefix)
  1128. ast->prefix_count++;
  1129. else {
  1130. ast->prefix = d[2] * 256 + d[3];
  1131. ast->prefix_count = 0;
  1132. }
  1133. avi->stream_index = n;
  1134. ast->packet_size = size + 8;
  1135. ast->remaining = size;
  1136. if (size) {
  1137. uint64_t pos = avio_tell(pb) - 8;
  1138. if (!st->index_entries || !st->nb_index_entries ||
  1139. st->index_entries[st->nb_index_entries - 1].pos < pos) {
  1140. av_add_index_entry(st, pos, ast->frame_offset, size,
  1141. 0, AVINDEX_KEYFRAME);
  1142. }
  1143. }
  1144. return 0;
  1145. }
  1146. }
  1147. }
  1148. if (pb->error)
  1149. return pb->error;
  1150. return AVERROR_EOF;
  1151. }
  1152. static int ni_prepare_read(AVFormatContext *s)
  1153. {
  1154. AVIContext *avi = s->priv_data;
  1155. int best_stream_index = 0;
  1156. AVStream *best_st = NULL;
  1157. AVIStream *best_ast;
  1158. int64_t best_ts = INT64_MAX;
  1159. int i;
  1160. for (i = 0; i < s->nb_streams; i++) {
  1161. AVStream *st = s->streams[i];
  1162. AVIStream *ast = st->priv_data;
  1163. int64_t ts = ast->frame_offset;
  1164. int64_t last_ts;
  1165. if (!st->nb_index_entries)
  1166. continue;
  1167. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  1168. if (!ast->remaining && ts > last_ts)
  1169. continue;
  1170. ts = av_rescale_q(ts, st->time_base,
  1171. (AVRational) { FFMAX(1, ast->sample_size),
  1172. AV_TIME_BASE });
  1173. av_log(s, AV_LOG_TRACE, "%"PRId64" %d/%d %"PRId64"\n", ts,
  1174. st->time_base.num, st->time_base.den, ast->frame_offset);
  1175. if (ts < best_ts) {
  1176. best_ts = ts;
  1177. best_st = st;
  1178. best_stream_index = i;
  1179. }
  1180. }
  1181. if (!best_st)
  1182. return AVERROR_EOF;
  1183. best_ast = best_st->priv_data;
  1184. best_ts = best_ast->frame_offset;
  1185. if (best_ast->remaining) {
  1186. i = av_index_search_timestamp(best_st,
  1187. best_ts,
  1188. AVSEEK_FLAG_ANY |
  1189. AVSEEK_FLAG_BACKWARD);
  1190. } else {
  1191. i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  1192. if (i >= 0)
  1193. best_ast->frame_offset = best_st->index_entries[i].timestamp;
  1194. }
  1195. if (i >= 0) {
  1196. int64_t pos = best_st->index_entries[i].pos;
  1197. pos += best_ast->packet_size - best_ast->remaining;
  1198. if (avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
  1199. return AVERROR_EOF;
  1200. av_assert0(best_ast->remaining <= best_ast->packet_size);
  1201. avi->stream_index = best_stream_index;
  1202. if (!best_ast->remaining)
  1203. best_ast->packet_size =
  1204. best_ast->remaining = best_st->index_entries[i].size;
  1205. }
  1206. else
  1207. return AVERROR_EOF;
  1208. return 0;
  1209. }
  1210. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  1211. {
  1212. AVIContext *avi = s->priv_data;
  1213. AVIOContext *pb = s->pb;
  1214. int err;
  1215. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1216. int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
  1217. if (size >= 0)
  1218. return size;
  1219. else
  1220. goto resync;
  1221. }
  1222. if (avi->non_interleaved) {
  1223. err = ni_prepare_read(s);
  1224. if (err < 0)
  1225. return err;
  1226. }
  1227. resync:
  1228. if (avi->stream_index >= 0) {
  1229. AVStream *st = s->streams[avi->stream_index];
  1230. AVIStream *ast = st->priv_data;
  1231. int size, err;
  1232. if (get_subtitle_pkt(s, st, pkt))
  1233. return 0;
  1234. // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  1235. if (ast->sample_size <= 1)
  1236. size = INT_MAX;
  1237. else if (ast->sample_size < 32)
  1238. // arbitrary multiplier to avoid tiny packets for raw PCM data
  1239. size = 1024 * ast->sample_size;
  1240. else
  1241. size = ast->sample_size;
  1242. if (size > ast->remaining)
  1243. size = ast->remaining;
  1244. avi->last_pkt_pos = avio_tell(pb);
  1245. err = av_get_packet(pb, pkt, size);
  1246. if (err < 0)
  1247. return err;
  1248. size = err;
  1249. if (ast->has_pal && pkt->size < (unsigned)INT_MAX / 2) {
  1250. uint8_t *pal;
  1251. pal = av_packet_new_side_data(pkt,
  1252. AV_PKT_DATA_PALETTE,
  1253. AVPALETTE_SIZE);
  1254. if (!pal) {
  1255. av_log(s, AV_LOG_ERROR,
  1256. "Failed to allocate data for palette\n");
  1257. } else {
  1258. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  1259. ast->has_pal = 0;
  1260. }
  1261. }
  1262. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1263. AVBufferRef *avbuf = pkt->buf;
  1264. size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
  1265. pkt->data, pkt->size, pkt->pos);
  1266. pkt->buf = avbuf;
  1267. pkt->flags |= AV_PKT_FLAG_KEY;
  1268. if (size < 0)
  1269. av_packet_unref(pkt);
  1270. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1271. !st->codecpar->codec_tag && read_gab2_sub(s, st, pkt)) {
  1272. ast->frame_offset++;
  1273. avi->stream_index = -1;
  1274. ast->remaining = 0;
  1275. goto resync;
  1276. } else {
  1277. /* XXX: How to handle B-frames in AVI? */
  1278. pkt->dts = ast->frame_offset;
  1279. // pkt->dts += ast->start;
  1280. if (ast->sample_size)
  1281. pkt->dts /= ast->sample_size;
  1282. av_log(s, AV_LOG_TRACE,
  1283. "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
  1284. "base:%d st:%d size:%d\n",
  1285. pkt->dts,
  1286. ast->frame_offset,
  1287. ast->scale,
  1288. ast->rate,
  1289. ast->sample_size,
  1290. AV_TIME_BASE,
  1291. avi->stream_index,
  1292. size);
  1293. pkt->stream_index = avi->stream_index;
  1294. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->index_entries) {
  1295. AVIndexEntry *e;
  1296. int index;
  1297. index = av_index_search_timestamp(st, ast->frame_offset, AVSEEK_FLAG_ANY);
  1298. e = &st->index_entries[index];
  1299. if (index >= 0 && e->timestamp == ast->frame_offset) {
  1300. if (index == st->nb_index_entries-1) {
  1301. int key=1;
  1302. uint32_t state=-1;
  1303. if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
  1304. const uint8_t *ptr = pkt->data, *end = ptr + FFMIN(size, 256);
  1305. while (ptr < end) {
  1306. ptr = avpriv_find_start_code(ptr, end, &state);
  1307. if (state == 0x1B6 && ptr < end) {
  1308. key = !(*ptr & 0xC0);
  1309. break;
  1310. }
  1311. }
  1312. }
  1313. if (!key)
  1314. e->flags &= ~AVINDEX_KEYFRAME;
  1315. }
  1316. if (e->flags & AVINDEX_KEYFRAME)
  1317. pkt->flags |= AV_PKT_FLAG_KEY;
  1318. }
  1319. } else {
  1320. pkt->flags |= AV_PKT_FLAG_KEY;
  1321. }
  1322. ast->frame_offset += get_duration(ast, pkt->size);
  1323. }
  1324. ast->remaining -= err;
  1325. if (!ast->remaining) {
  1326. avi->stream_index = -1;
  1327. ast->packet_size = 0;
  1328. }
  1329. if (!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos) {
  1330. av_packet_unref(pkt);
  1331. goto resync;
  1332. }
  1333. ast->seek_pos= 0;
  1334. if (!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1) {
  1335. int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
  1336. if (avi->dts_max - dts > 2*AV_TIME_BASE) {
  1337. avi->non_interleaved= 1;
  1338. av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
  1339. }else if (avi->dts_max < dts)
  1340. avi->dts_max = dts;
  1341. }
  1342. return 0;
  1343. }
  1344. if ((err = avi_sync(s, 0)) < 0)
  1345. return err;
  1346. goto resync;
  1347. }
  1348. /* XXX: We make the implicit supposition that the positions are sorted
  1349. * for each stream. */
  1350. static int avi_read_idx1(AVFormatContext *s, int size)
  1351. {
  1352. AVIContext *avi = s->priv_data;
  1353. AVIOContext *pb = s->pb;
  1354. int nb_index_entries, i;
  1355. AVStream *st;
  1356. AVIStream *ast;
  1357. int64_t pos;
  1358. unsigned int index, tag, flags, len, first_packet = 1;
  1359. int64_t last_pos = -1;
  1360. unsigned last_idx = -1;
  1361. int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
  1362. int anykey = 0;
  1363. nb_index_entries = size / 16;
  1364. if (nb_index_entries <= 0)
  1365. return AVERROR_INVALIDDATA;
  1366. idx1_pos = avio_tell(pb);
  1367. avio_seek(pb, avi->movi_list + 4, SEEK_SET);
  1368. if (avi_sync(s, 1) == 0)
  1369. first_packet_pos = avio_tell(pb) - 8;
  1370. avi->stream_index = -1;
  1371. avio_seek(pb, idx1_pos, SEEK_SET);
  1372. if (s->nb_streams == 1 && s->streams[0]->codecpar->codec_tag == AV_RL32("MMES")) {
  1373. first_packet_pos = 0;
  1374. data_offset = avi->movi_list;
  1375. }
  1376. /* Read the entries and sort them in each stream component. */
  1377. for (i = 0; i < nb_index_entries; i++) {
  1378. if (avio_feof(pb))
  1379. return -1;
  1380. tag = avio_rl32(pb);
  1381. flags = avio_rl32(pb);
  1382. pos = avio_rl32(pb);
  1383. len = avio_rl32(pb);
  1384. av_log(s, AV_LOG_TRACE, "%d: tag=0x%x flags=0x%x pos=0x%"PRIx64" len=%d/",
  1385. i, tag, flags, pos, len);
  1386. index = ((tag & 0xff) - '0') * 10;
  1387. index += (tag >> 8 & 0xff) - '0';
  1388. if (index >= s->nb_streams)
  1389. continue;
  1390. st = s->streams[index];
  1391. ast = st->priv_data;
  1392. /* Skip 'xxpc' palette change entries in the index until a logic
  1393. * to process these is properly implemented. */
  1394. if ((tag >> 16 & 0xff) == 'p' && (tag >> 24 & 0xff) == 'c')
  1395. continue;
  1396. if (first_packet && first_packet_pos) {
  1397. if (avi->movi_list + 4 != pos || pos + 500 > first_packet_pos)
  1398. data_offset = first_packet_pos - pos;
  1399. first_packet = 0;
  1400. }
  1401. pos += data_offset;
  1402. av_log(s, AV_LOG_TRACE, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1403. // even if we have only a single stream, we should
  1404. // switch to non-interleaved to get correct timestamps
  1405. if (last_pos == pos)
  1406. avi->non_interleaved = 1;
  1407. if (last_idx != pos && len) {
  1408. av_add_index_entry(st, pos, ast->cum_len, len, 0,
  1409. (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1410. last_idx= pos;
  1411. }
  1412. ast->cum_len += get_duration(ast, len);
  1413. last_pos = pos;
  1414. anykey |= flags&AVIIF_INDEX;
  1415. }
  1416. if (!anykey) {
  1417. for (index = 0; index < s->nb_streams; index++) {
  1418. st = s->streams[index];
  1419. if (st->nb_index_entries)
  1420. st->index_entries[0].flags |= AVINDEX_KEYFRAME;
  1421. }
  1422. }
  1423. return 0;
  1424. }
  1425. /* Scan the index and consider any file with streams more than
  1426. * 2 seconds or 64MB apart non-interleaved. */
  1427. static int check_stream_max_drift(AVFormatContext *s)
  1428. {
  1429. int64_t min_pos, pos;
  1430. int i;
  1431. int *idx = av_mallocz_array(s->nb_streams, sizeof(*idx));
  1432. if (!idx)
  1433. return AVERROR(ENOMEM);
  1434. for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
  1435. int64_t max_dts = INT64_MIN / 2;
  1436. int64_t min_dts = INT64_MAX / 2;
  1437. int64_t max_buffer = 0;
  1438. min_pos = INT64_MAX;
  1439. for (i = 0; i < s->nb_streams; i++) {
  1440. AVStream *st = s->streams[i];
  1441. AVIStream *ast = st->priv_data;
  1442. int n = st->nb_index_entries;
  1443. while (idx[i] < n && st->index_entries[idx[i]].pos < pos)
  1444. idx[i]++;
  1445. if (idx[i] < n) {
  1446. int64_t dts;
  1447. dts = av_rescale_q(st->index_entries[idx[i]].timestamp /
  1448. FFMAX(ast->sample_size, 1),
  1449. st->time_base, AV_TIME_BASE_Q);
  1450. min_dts = FFMIN(min_dts, dts);
  1451. min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
  1452. }
  1453. }
  1454. for (i = 0; i < s->nb_streams; i++) {
  1455. AVStream *st = s->streams[i];
  1456. AVIStream *ast = st->priv_data;
  1457. if (idx[i] && min_dts != INT64_MAX / 2) {
  1458. int64_t dts;
  1459. dts = av_rescale_q(st->index_entries[idx[i] - 1].timestamp /
  1460. FFMAX(ast->sample_size, 1),
  1461. st->time_base, AV_TIME_BASE_Q);
  1462. max_dts = FFMAX(max_dts, dts);
  1463. max_buffer = FFMAX(max_buffer,
  1464. av_rescale(dts - min_dts,
  1465. st->codecpar->bit_rate,
  1466. AV_TIME_BASE));
  1467. }
  1468. }
  1469. if (max_dts - min_dts > 2 * AV_TIME_BASE ||
  1470. max_buffer > 1024 * 1024 * 8 * 8) {
  1471. av_free(idx);
  1472. return 1;
  1473. }
  1474. }
  1475. av_free(idx);
  1476. return 0;
  1477. }
  1478. static int guess_ni_flag(AVFormatContext *s)
  1479. {
  1480. int i;
  1481. int64_t last_start = 0;
  1482. int64_t first_end = INT64_MAX;
  1483. int64_t oldpos = avio_tell(s->pb);
  1484. for (i = 0; i < s->nb_streams; i++) {
  1485. AVStream *st = s->streams[i];
  1486. int n = st->nb_index_entries;
  1487. unsigned int size;
  1488. if (n <= 0)
  1489. continue;
  1490. if (n >= 2) {
  1491. int64_t pos = st->index_entries[0].pos;
  1492. unsigned tag[2];
  1493. avio_seek(s->pb, pos, SEEK_SET);
  1494. tag[0] = avio_r8(s->pb);
  1495. tag[1] = avio_r8(s->pb);
  1496. avio_rl16(s->pb);
  1497. size = avio_rl32(s->pb);
  1498. if (get_stream_idx(tag) == i && pos + size > st->index_entries[1].pos)
  1499. last_start = INT64_MAX;
  1500. if (get_stream_idx(tag) == i && size == st->index_entries[0].size + 8)
  1501. last_start = INT64_MAX;
  1502. }
  1503. if (st->index_entries[0].pos > last_start)
  1504. last_start = st->index_entries[0].pos;
  1505. if (st->index_entries[n - 1].pos < first_end)
  1506. first_end = st->index_entries[n - 1].pos;
  1507. }
  1508. avio_seek(s->pb, oldpos, SEEK_SET);
  1509. if (last_start > first_end)
  1510. return 1;
  1511. return check_stream_max_drift(s);
  1512. }
  1513. static int avi_load_index(AVFormatContext *s)
  1514. {
  1515. AVIContext *avi = s->priv_data;
  1516. AVIOContext *pb = s->pb;
  1517. uint32_t tag, size;
  1518. int64_t pos = avio_tell(pb);
  1519. int64_t next;
  1520. int ret = -1;
  1521. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1522. goto the_end; // maybe truncated file
  1523. av_log(s, AV_LOG_TRACE, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1524. for (;;) {
  1525. tag = avio_rl32(pb);
  1526. size = avio_rl32(pb);
  1527. if (avio_feof(pb))
  1528. break;
  1529. next = avio_tell(pb) + size + (size & 1);
  1530. av_log(s, AV_LOG_TRACE, "tag=%c%c%c%c size=0x%x\n",
  1531. tag & 0xff,
  1532. (tag >> 8) & 0xff,
  1533. (tag >> 16) & 0xff,
  1534. (tag >> 24) & 0xff,
  1535. size);
  1536. if (tag == MKTAG('i', 'd', 'x', '1') &&
  1537. avi_read_idx1(s, size) >= 0) {
  1538. avi->index_loaded=2;
  1539. ret = 0;
  1540. }else if (tag == MKTAG('L', 'I', 'S', 'T')) {
  1541. uint32_t tag1 = avio_rl32(pb);
  1542. if (tag1 == MKTAG('I', 'N', 'F', 'O'))
  1543. ff_read_riff_info(s, size - 4);
  1544. }else if (!ret)
  1545. break;
  1546. if (avio_seek(pb, next, SEEK_SET) < 0)
  1547. break; // something is wrong here
  1548. }
  1549. the_end:
  1550. avio_seek(pb, pos, SEEK_SET);
  1551. return ret;
  1552. }
  1553. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1554. {
  1555. AVIStream *ast2 = st2->priv_data;
  1556. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1557. av_packet_unref(&ast2->sub_pkt);
  1558. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1559. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1560. ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1561. }
  1562. static int avi_read_seek(AVFormatContext *s, int stream_index,
  1563. int64_t timestamp, int flags)
  1564. {
  1565. AVIContext *avi = s->priv_data;
  1566. AVStream *st;
  1567. int i, index;
  1568. int64_t pos, pos_min;
  1569. AVIStream *ast;
  1570. /* Does not matter which stream is requested dv in avi has the
  1571. * stream information in the first video stream.
  1572. */
  1573. if (avi->dv_demux)
  1574. stream_index = 0;
  1575. if (!avi->index_loaded) {
  1576. /* we only load the index on demand */
  1577. avi_load_index(s);
  1578. avi->index_loaded |= 1;
  1579. }
  1580. av_assert0(stream_index >= 0);
  1581. st = s->streams[stream_index];
  1582. ast = st->priv_data;
  1583. index = av_index_search_timestamp(st,
  1584. timestamp * FFMAX(ast->sample_size, 1),
  1585. flags);
  1586. if (index < 0) {
  1587. if (st->nb_index_entries > 0)
  1588. av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",
  1589. timestamp * FFMAX(ast->sample_size, 1),
  1590. st->index_entries[0].timestamp,
  1591. st->index_entries[st->nb_index_entries - 1].timestamp);
  1592. return AVERROR_INVALIDDATA;
  1593. }
  1594. /* find the position */
  1595. pos = st->index_entries[index].pos;
  1596. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1597. av_log(s, AV_LOG_TRACE, "XX %"PRId64" %d %"PRId64"\n",
  1598. timestamp, index, st->index_entries[index].timestamp);
  1599. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1600. /* One and only one real stream for DV in AVI, and it has video */
  1601. /* offsets. Calling with other stream indexes should have failed */
  1602. /* the av_index_search_timestamp call above. */
  1603. if (avio_seek(s->pb, pos, SEEK_SET) < 0)
  1604. return -1;
  1605. /* Feed the DV video stream version of the timestamp to the */
  1606. /* DV demux so it can synthesize correct timestamps. */
  1607. ff_dv_offset_reset(avi->dv_demux, timestamp);
  1608. avi->stream_index = -1;
  1609. return 0;
  1610. }
  1611. pos_min = pos;
  1612. for (i = 0; i < s->nb_streams; i++) {
  1613. AVStream *st2 = s->streams[i];
  1614. AVIStream *ast2 = st2->priv_data;
  1615. ast2->packet_size =
  1616. ast2->remaining = 0;
  1617. if (ast2->sub_ctx) {
  1618. seek_subtitle(st, st2, timestamp);
  1619. continue;
  1620. }
  1621. if (st2->nb_index_entries <= 0)
  1622. continue;
  1623. // av_assert1(st2->codecpar->block_align);
  1624. index = av_index_search_timestamp(st2,
  1625. av_rescale_q(timestamp,
  1626. st->time_base,
  1627. st2->time_base) *
  1628. FFMAX(ast2->sample_size, 1),
  1629. flags |
  1630. AVSEEK_FLAG_BACKWARD |
  1631. (st2->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
  1632. if (index < 0)
  1633. index = 0;
  1634. ast2->seek_pos = st2->index_entries[index].pos;
  1635. pos_min = FFMIN(pos_min,ast2->seek_pos);
  1636. }
  1637. for (i = 0; i < s->nb_streams; i++) {
  1638. AVStream *st2 = s->streams[i];
  1639. AVIStream *ast2 = st2->priv_data;
  1640. if (ast2->sub_ctx || st2->nb_index_entries <= 0)
  1641. continue;
  1642. index = av_index_search_timestamp(
  1643. st2,
  1644. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1645. flags | AVSEEK_FLAG_BACKWARD | (st2->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
  1646. if (index < 0)
  1647. index = 0;
  1648. while (!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
  1649. index--;
  1650. ast2->frame_offset = st2->index_entries[index].timestamp;
  1651. }
  1652. /* do the seek */
  1653. if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) {
  1654. av_log(s, AV_LOG_ERROR, "Seek failed\n");
  1655. return -1;
  1656. }
  1657. avi->stream_index = -1;
  1658. avi->dts_max = INT_MIN;
  1659. return 0;
  1660. }
  1661. static int avi_read_close(AVFormatContext *s)
  1662. {
  1663. int i;
  1664. AVIContext *avi = s->priv_data;
  1665. for (i = 0; i < s->nb_streams; i++) {
  1666. AVStream *st = s->streams[i];
  1667. AVIStream *ast = st->priv_data;
  1668. if (ast) {
  1669. if (ast->sub_ctx) {
  1670. av_freep(&ast->sub_ctx->pb);
  1671. avformat_close_input(&ast->sub_ctx);
  1672. }
  1673. av_freep(&ast->sub_buffer);
  1674. av_packet_unref(&ast->sub_pkt);
  1675. }
  1676. }
  1677. av_freep(&avi->dv_demux);
  1678. return 0;
  1679. }
  1680. static int avi_probe(AVProbeData *p)
  1681. {
  1682. int i;
  1683. /* check file header */
  1684. for (i = 0; avi_headers[i][0]; i++)
  1685. if (AV_RL32(p->buf ) == AV_RL32(avi_headers[i] ) &&
  1686. AV_RL32(p->buf + 8) == AV_RL32(avi_headers[i] + 4))
  1687. return AVPROBE_SCORE_MAX;
  1688. return 0;
  1689. }
  1690. AVInputFormat ff_avi_demuxer = {
  1691. .name = "avi",
  1692. .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
  1693. .priv_data_size = sizeof(AVIContext),
  1694. .extensions = "avi",
  1695. .read_probe = avi_probe,
  1696. .read_header = avi_read_header,
  1697. .read_packet = avi_read_packet,
  1698. .read_close = avi_read_close,
  1699. .read_seek = avi_read_seek,
  1700. .priv_class = &demuxer_class,
  1701. };