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.

1522 lines
51KB

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