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.

1974 lines
69KB

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