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.

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