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.

1521 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. st->codec->extradata = av_realloc(st->codec->extradata,
  575. st->codec->extradata_size +
  576. FF_INPUT_BUFFER_PADDING_SIZE);
  577. if (st->codec->extradata)
  578. memcpy(st->codec->extradata + st->codec->extradata_size - 9,
  579. "BottomUp", 9);
  580. }
  581. st->codec->height = FFABS(st->codec->height);
  582. // avio_skip(pb, size - 5 * 4);
  583. break;
  584. case AVMEDIA_TYPE_AUDIO:
  585. ret = ff_get_wav_header(pb, st->codec, size);
  586. if (ret < 0)
  587. return ret;
  588. ast->dshow_block_align = st->codec->block_align;
  589. if (ast->sample_size && st->codec->block_align &&
  590. ast->sample_size != st->codec->block_align) {
  591. av_log(s,
  592. AV_LOG_WARNING,
  593. "sample size (%d) != block align (%d)\n",
  594. ast->sample_size,
  595. st->codec->block_align);
  596. ast->sample_size = st->codec->block_align;
  597. }
  598. /* 2-aligned
  599. * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  600. if (size & 1)
  601. avio_skip(pb, 1);
  602. /* Force parsing as several audio frames can be in
  603. * one packet and timestamps refer to packet start. */
  604. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  605. /* ADTS header is in extradata, AAC without header must be
  606. * stored as exact frames. Parser not needed and it will
  607. * fail. */
  608. if (st->codec->codec_id == AV_CODEC_ID_AAC &&
  609. st->codec->extradata_size)
  610. st->need_parsing = AVSTREAM_PARSE_NONE;
  611. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  612. * audio in the header but have Axan as stream_code_tag. */
  613. if (st->codec->stream_codec_tag == AV_RL32("Axan")) {
  614. st->codec->codec_id = AV_CODEC_ID_XAN_DPCM;
  615. st->codec->codec_tag = 0;
  616. }
  617. if (amv_file_format) {
  618. st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
  619. ast->dshow_block_align = 0;
  620. }
  621. break;
  622. case AVMEDIA_TYPE_SUBTITLE:
  623. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  624. st->codec->codec_id = AV_CODEC_ID_PROBE;
  625. break;
  626. default:
  627. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  628. st->codec->codec_id = AV_CODEC_ID_NONE;
  629. st->codec->codec_tag = 0;
  630. avio_skip(pb, size);
  631. break;
  632. }
  633. }
  634. break;
  635. case MKTAG('i', 'n', 'd', 'x'):
  636. i = avio_tell(pb);
  637. if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
  638. read_braindead_odml_indx(s, 0) < 0 &&
  639. (s->error_recognition & AV_EF_EXPLODE))
  640. goto fail;
  641. avio_seek(pb, i + size, SEEK_SET);
  642. break;
  643. case MKTAG('v', 'p', 'r', 'p'):
  644. if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
  645. AVRational active, active_aspect;
  646. st = s->streams[stream_index];
  647. avio_rl32(pb);
  648. avio_rl32(pb);
  649. avio_rl32(pb);
  650. avio_rl32(pb);
  651. avio_rl32(pb);
  652. active_aspect.den = avio_rl16(pb);
  653. active_aspect.num = avio_rl16(pb);
  654. active.num = avio_rl32(pb);
  655. active.den = avio_rl32(pb);
  656. avio_rl32(pb); // nbFieldsPerFrame
  657. if (active_aspect.num && active_aspect.den &&
  658. active.num && active.den) {
  659. st->sample_aspect_ratio = av_div_q(active_aspect, active);
  660. av_dlog(s, "vprp %d/%d %d/%d\n",
  661. active_aspect.num, active_aspect.den,
  662. active.num, active.den);
  663. }
  664. size -= 9 * 4;
  665. }
  666. avio_skip(pb, size);
  667. break;
  668. case MKTAG('s', 't', 'r', 'n'):
  669. if (s->nb_streams) {
  670. ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
  671. if (ret < 0)
  672. return ret;
  673. break;
  674. }
  675. default:
  676. if (size > 1000000) {
  677. av_log(s, AV_LOG_ERROR,
  678. "Something went wrong during header parsing, "
  679. "I will ignore it and try to continue anyway.\n");
  680. if (s->error_recognition & AV_EF_EXPLODE)
  681. goto fail;
  682. avi->movi_list = avio_tell(pb) - 4;
  683. avi->movi_end = avio_size(pb);
  684. goto end_of_header;
  685. }
  686. /* skip tag */
  687. size += (size & 1);
  688. avio_skip(pb, size);
  689. break;
  690. }
  691. }
  692. end_of_header:
  693. /* check stream number */
  694. if (stream_index != s->nb_streams - 1) {
  695. fail:
  696. return AVERROR_INVALIDDATA;
  697. }
  698. if (!avi->index_loaded && pb->seekable)
  699. avi_load_index(s);
  700. avi->index_loaded = 1;
  701. avi->non_interleaved |= guess_ni_flag(s);
  702. for (i = 0; i < s->nb_streams; i++) {
  703. AVStream *st = s->streams[i];
  704. if (st->nb_index_entries)
  705. break;
  706. }
  707. if (i == s->nb_streams && avi->non_interleaved) {
  708. av_log(s, AV_LOG_WARNING,
  709. "Non-interleaved AVI without index, switching to interleaved\n");
  710. avi->non_interleaved = 0;
  711. }
  712. if (avi->non_interleaved) {
  713. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  714. clean_index(s);
  715. }
  716. ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
  717. ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
  718. return 0;
  719. }
  720. static int read_gab2_sub(AVStream *st, AVPacket *pkt)
  721. {
  722. if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
  723. uint8_t desc[256];
  724. int score = AVPROBE_SCORE_EXTENSION, ret;
  725. AVIStream *ast = st->priv_data;
  726. AVInputFormat *sub_demuxer;
  727. AVRational time_base;
  728. AVIOContext *pb = avio_alloc_context(pkt->data + 7,
  729. pkt->size - 7,
  730. 0, NULL, NULL, NULL, NULL);
  731. AVProbeData pd;
  732. unsigned int desc_len = avio_rl32(pb);
  733. if (desc_len > pb->buf_end - pb->buf_ptr)
  734. goto error;
  735. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  736. avio_skip(pb, desc_len - ret);
  737. if (*desc)
  738. av_dict_set(&st->metadata, "title", desc, 0);
  739. avio_rl16(pb); /* flags? */
  740. avio_rl32(pb); /* data size */
  741. pd = (AVProbeData) { .buf = pb->buf_ptr,
  742. .buf_size = pb->buf_end - pb->buf_ptr };
  743. if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
  744. goto error;
  745. if (!(ast->sub_ctx = avformat_alloc_context()))
  746. goto error;
  747. ast->sub_ctx->pb = pb;
  748. if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
  749. ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
  750. *st->codec = *ast->sub_ctx->streams[0]->codec;
  751. ast->sub_ctx->streams[0]->codec->extradata = NULL;
  752. time_base = ast->sub_ctx->streams[0]->time_base;
  753. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  754. }
  755. ast->sub_buffer = pkt->data;
  756. memset(pkt, 0, sizeof(*pkt));
  757. return 1;
  758. error:
  759. av_freep(&pb);
  760. }
  761. return 0;
  762. }
  763. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  764. AVPacket *pkt)
  765. {
  766. AVIStream *ast, *next_ast = next_st->priv_data;
  767. int64_t ts, next_ts, ts_min = INT64_MAX;
  768. AVStream *st, *sub_st = NULL;
  769. int i;
  770. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  771. AV_TIME_BASE_Q);
  772. for (i = 0; i < s->nb_streams; i++) {
  773. st = s->streams[i];
  774. ast = st->priv_data;
  775. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  776. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  777. if (ts <= next_ts && ts < ts_min) {
  778. ts_min = ts;
  779. sub_st = st;
  780. }
  781. }
  782. }
  783. if (sub_st) {
  784. ast = sub_st->priv_data;
  785. *pkt = ast->sub_pkt;
  786. pkt->stream_index = sub_st->index;
  787. if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  788. ast->sub_pkt.data = NULL;
  789. }
  790. return sub_st;
  791. }
  792. static int get_stream_idx(int *d)
  793. {
  794. if (d[0] >= '0' && d[0] <= '9' &&
  795. d[1] >= '0' && d[1] <= '9') {
  796. return (d[0] - '0') * 10 + (d[1] - '0');
  797. } else {
  798. return 100; // invalid stream ID
  799. }
  800. }
  801. static int avi_sync(AVFormatContext *s, int exit_early)
  802. {
  803. AVIContext *avi = s->priv_data;
  804. AVIOContext *pb = s->pb;
  805. int n;
  806. unsigned int d[8];
  807. unsigned int size;
  808. int64_t i, sync;
  809. start_sync:
  810. memset(d, -1, sizeof(d));
  811. for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
  812. int j;
  813. for (j = 0; j < 7; j++)
  814. d[j] = d[j + 1];
  815. d[7] = avio_r8(pb);
  816. size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
  817. n = get_stream_idx(d + 2);
  818. av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
  819. d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  820. if (i + (uint64_t)size > avi->fsize || d[0] > 127)
  821. continue;
  822. // parse ix##
  823. if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
  824. // parse JUNK
  825. (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
  826. (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
  827. avio_skip(pb, size);
  828. goto start_sync;
  829. }
  830. // parse stray LIST
  831. if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
  832. avio_skip(pb, 4);
  833. goto start_sync;
  834. }
  835. n = get_stream_idx(d);
  836. if (!((i - avi->last_pkt_pos) & 1) &&
  837. get_stream_idx(d + 1) < s->nb_streams)
  838. continue;
  839. // detect ##ix chunk and skip
  840. if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
  841. avio_skip(pb, size);
  842. goto start_sync;
  843. }
  844. // parse ##dc/##wb
  845. if (n < s->nb_streams) {
  846. AVStream *st;
  847. AVIStream *ast;
  848. st = s->streams[n];
  849. ast = st->priv_data;
  850. if (s->nb_streams >= 2) {
  851. AVStream *st1 = s->streams[1];
  852. AVIStream *ast1 = st1->priv_data;
  853. // workaround for broken small-file-bug402.avi
  854. if (d[2] == 'w' && d[3] == 'b' && n == 0 &&
  855. st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  856. st1->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  857. ast->prefix == 'd' * 256 + 'c' &&
  858. (d[2] * 256 + d[3] == ast1->prefix ||
  859. !ast1->prefix_count)) {
  860. n = 1;
  861. st = st1;
  862. ast = ast1;
  863. av_log(s, AV_LOG_WARNING,
  864. "Invalid stream + prefix combination, assuming audio.\n");
  865. }
  866. }
  867. if (!avi->dv_demux &&
  868. ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
  869. // FIXME: needs a little reordering
  870. (st->discard >= AVDISCARD_NONKEY &&
  871. !(pkt->flags & AV_PKT_FLAG_KEY)) */
  872. || st->discard >= AVDISCARD_ALL)) {
  873. if (!exit_early) {
  874. ast->frame_offset += get_duration(ast, size);
  875. }
  876. avio_skip(pb, size);
  877. goto start_sync;
  878. }
  879. if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
  880. int k = avio_r8(pb);
  881. int last = (k + avio_r8(pb) - 1) & 0xFF;
  882. avio_rl16(pb); // flags
  883. // b + (g << 8) + (r << 16);
  884. for (; k <= last; k++)
  885. ast->pal[k] = avio_rb32(pb) >> 8;
  886. ast->has_pal = 1;
  887. goto start_sync;
  888. } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
  889. d[2] < 128 && d[3] < 128) ||
  890. d[2] * 256 + d[3] == ast->prefix /* ||
  891. (d[2] == 'd' && d[3] == 'c') ||
  892. (d[2] == 'w' && d[3] == 'b') */) {
  893. if (exit_early)
  894. return 0;
  895. if (d[2] * 256 + d[3] == ast->prefix)
  896. ast->prefix_count++;
  897. else {
  898. ast->prefix = d[2] * 256 + d[3];
  899. ast->prefix_count = 0;
  900. }
  901. avi->stream_index = n;
  902. ast->packet_size = size + 8;
  903. ast->remaining = size;
  904. if (size || !ast->sample_size) {
  905. uint64_t pos = avio_tell(pb) - 8;
  906. if (!st->index_entries || !st->nb_index_entries ||
  907. st->index_entries[st->nb_index_entries - 1].pos < pos) {
  908. av_add_index_entry(st, pos, ast->frame_offset, size,
  909. 0, AVINDEX_KEYFRAME);
  910. }
  911. }
  912. return 0;
  913. }
  914. }
  915. }
  916. return AVERROR_EOF;
  917. }
  918. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  919. {
  920. AVIContext *avi = s->priv_data;
  921. AVIOContext *pb = s->pb;
  922. int err;
  923. #if FF_API_DESTRUCT_PACKET
  924. void *dstr;
  925. #endif
  926. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  927. int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
  928. if (size >= 0)
  929. return size;
  930. }
  931. if (avi->non_interleaved) {
  932. int best_stream_index = 0;
  933. AVStream *best_st = NULL;
  934. AVIStream *best_ast;
  935. int64_t best_ts = INT64_MAX;
  936. int i;
  937. for (i = 0; i < s->nb_streams; i++) {
  938. AVStream *st = s->streams[i];
  939. AVIStream *ast = st->priv_data;
  940. int64_t ts = ast->frame_offset;
  941. int64_t last_ts;
  942. if (!st->nb_index_entries)
  943. continue;
  944. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  945. if (!ast->remaining && ts > last_ts)
  946. continue;
  947. ts = av_rescale_q(ts, st->time_base,
  948. (AVRational) { FFMAX(1, ast->sample_size),
  949. AV_TIME_BASE });
  950. av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
  951. st->time_base.num, st->time_base.den, ast->frame_offset);
  952. if (ts < best_ts) {
  953. best_ts = ts;
  954. best_st = st;
  955. best_stream_index = i;
  956. }
  957. }
  958. if (!best_st)
  959. return AVERROR_EOF;
  960. best_ast = best_st->priv_data;
  961. best_ts = av_rescale_q(best_ts,
  962. (AVRational) { FFMAX(1, best_ast->sample_size),
  963. AV_TIME_BASE },
  964. best_st->time_base);
  965. if (best_ast->remaining) {
  966. i = av_index_search_timestamp(best_st,
  967. best_ts,
  968. AVSEEK_FLAG_ANY |
  969. AVSEEK_FLAG_BACKWARD);
  970. } else {
  971. i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  972. if (i >= 0)
  973. best_ast->frame_offset = best_st->index_entries[i].timestamp;
  974. }
  975. if (i >= 0) {
  976. int64_t pos = best_st->index_entries[i].pos;
  977. pos += best_ast->packet_size - best_ast->remaining;
  978. avio_seek(s->pb, pos + 8, SEEK_SET);
  979. assert(best_ast->remaining <= best_ast->packet_size);
  980. avi->stream_index = best_stream_index;
  981. if (!best_ast->remaining)
  982. best_ast->packet_size =
  983. best_ast->remaining = best_st->index_entries[i].size;
  984. }
  985. }
  986. resync:
  987. if (avi->stream_index >= 0) {
  988. AVStream *st = s->streams[avi->stream_index];
  989. AVIStream *ast = st->priv_data;
  990. int size, err;
  991. if (get_subtitle_pkt(s, st, pkt))
  992. return 0;
  993. // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  994. if (ast->sample_size <= 1)
  995. size = INT_MAX;
  996. else if (ast->sample_size < 32)
  997. // arbitrary multiplier to avoid tiny packets for raw PCM data
  998. size = 1024 * ast->sample_size;
  999. else
  1000. size = ast->sample_size;
  1001. if (size > ast->remaining)
  1002. size = ast->remaining;
  1003. avi->last_pkt_pos = avio_tell(pb);
  1004. err = av_get_packet(pb, pkt, size);
  1005. if (err < 0)
  1006. return err;
  1007. if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
  1008. uint8_t *pal;
  1009. pal = av_packet_new_side_data(pkt,
  1010. AV_PKT_DATA_PALETTE,
  1011. AVPALETTE_SIZE);
  1012. if (!pal) {
  1013. av_log(s, AV_LOG_ERROR,
  1014. "Failed to allocate data for palette\n");
  1015. } else {
  1016. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  1017. ast->has_pal = 0;
  1018. }
  1019. }
  1020. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1021. AVBufferRef *avbuf = pkt->buf;
  1022. #if FF_API_DESTRUCT_PACKET
  1023. FF_DISABLE_DEPRECATION_WARNINGS
  1024. dstr = pkt->destruct;
  1025. FF_ENABLE_DEPRECATION_WARNINGS
  1026. #endif
  1027. size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
  1028. pkt->data, pkt->size);
  1029. #if FF_API_DESTRUCT_PACKET
  1030. FF_DISABLE_DEPRECATION_WARNINGS
  1031. pkt->destruct = dstr;
  1032. FF_ENABLE_DEPRECATION_WARNINGS
  1033. #endif
  1034. pkt->buf = avbuf;
  1035. pkt->flags |= AV_PKT_FLAG_KEY;
  1036. if (size < 0)
  1037. av_free_packet(pkt);
  1038. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1039. !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
  1040. ast->frame_offset++;
  1041. avi->stream_index = -1;
  1042. ast->remaining = 0;
  1043. goto resync;
  1044. } else {
  1045. /* XXX: How to handle B-frames in AVI? */
  1046. pkt->dts = ast->frame_offset;
  1047. // pkt->dts += ast->start;
  1048. if (ast->sample_size)
  1049. pkt->dts /= ast->sample_size;
  1050. av_dlog(s,
  1051. "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
  1052. "base:%d st:%d size:%d\n",
  1053. pkt->dts,
  1054. ast->frame_offset,
  1055. ast->scale,
  1056. ast->rate,
  1057. ast->sample_size,
  1058. AV_TIME_BASE,
  1059. avi->stream_index,
  1060. size);
  1061. pkt->stream_index = avi->stream_index;
  1062. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1063. AVIndexEntry *e;
  1064. int index;
  1065. assert(st->index_entries);
  1066. index = av_index_search_timestamp(st, ast->frame_offset, 0);
  1067. e = &st->index_entries[index];
  1068. if (index >= 0 && e->timestamp == ast->frame_offset)
  1069. if (e->flags & AVINDEX_KEYFRAME)
  1070. pkt->flags |= AV_PKT_FLAG_KEY;
  1071. } else {
  1072. pkt->flags |= AV_PKT_FLAG_KEY;
  1073. }
  1074. ast->frame_offset += get_duration(ast, pkt->size);
  1075. }
  1076. ast->remaining -= err;
  1077. if (!ast->remaining) {
  1078. avi->stream_index = -1;
  1079. ast->packet_size = 0;
  1080. }
  1081. return 0;
  1082. }
  1083. if ((err = avi_sync(s, 0)) < 0)
  1084. return err;
  1085. goto resync;
  1086. }
  1087. /* XXX: We make the implicit supposition that the positions are sorted
  1088. * for each stream. */
  1089. static int avi_read_idx1(AVFormatContext *s, int size)
  1090. {
  1091. AVIContext *avi = s->priv_data;
  1092. AVIOContext *pb = s->pb;
  1093. int nb_index_entries, i;
  1094. AVStream *st;
  1095. AVIStream *ast;
  1096. unsigned int index, tag, flags, pos, len, first_packet = 1;
  1097. unsigned last_pos = -1;
  1098. int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
  1099. nb_index_entries = size / 16;
  1100. if (nb_index_entries <= 0)
  1101. return AVERROR_INVALIDDATA;
  1102. idx1_pos = avio_tell(pb);
  1103. avio_seek(pb, avi->movi_list + 4, SEEK_SET);
  1104. if (avi_sync(s, 1) == 0)
  1105. first_packet_pos = avio_tell(pb) - 8;
  1106. avi->stream_index = -1;
  1107. avio_seek(pb, idx1_pos, SEEK_SET);
  1108. /* Read the entries and sort them in each stream component. */
  1109. for (i = 0; i < nb_index_entries; i++) {
  1110. tag = avio_rl32(pb);
  1111. flags = avio_rl32(pb);
  1112. pos = avio_rl32(pb);
  1113. len = avio_rl32(pb);
  1114. av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  1115. i, tag, flags, pos, len);
  1116. index = ((tag & 0xff) - '0') * 10;
  1117. index += (tag >> 8 & 0xff) - '0';
  1118. if (index >= s->nb_streams)
  1119. continue;
  1120. st = s->streams[index];
  1121. ast = st->priv_data;
  1122. if (first_packet && first_packet_pos && len) {
  1123. data_offset = first_packet_pos - pos;
  1124. first_packet = 0;
  1125. }
  1126. pos += data_offset;
  1127. av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1128. if (pb->eof_reached)
  1129. return AVERROR_INVALIDDATA;
  1130. if (last_pos == pos)
  1131. avi->non_interleaved = 1;
  1132. else if (len || !ast->sample_size)
  1133. av_add_index_entry(st, pos, ast->cum_len, len, 0,
  1134. (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1135. ast->cum_len += get_duration(ast, len);
  1136. last_pos = pos;
  1137. }
  1138. return 0;
  1139. }
  1140. static int guess_ni_flag(AVFormatContext *s)
  1141. {
  1142. int i;
  1143. int64_t last_start = 0;
  1144. int64_t first_end = INT64_MAX;
  1145. int64_t oldpos = avio_tell(s->pb);
  1146. for (i = 0; i < s->nb_streams; i++) {
  1147. AVStream *st = s->streams[i];
  1148. int n = st->nb_index_entries;
  1149. unsigned int size;
  1150. if (n <= 0)
  1151. continue;
  1152. if (n >= 2) {
  1153. int64_t pos = st->index_entries[0].pos;
  1154. avio_seek(s->pb, pos + 4, SEEK_SET);
  1155. size = avio_rl32(s->pb);
  1156. if (pos + size > st->index_entries[1].pos)
  1157. last_start = INT64_MAX;
  1158. }
  1159. if (st->index_entries[0].pos > last_start)
  1160. last_start = st->index_entries[0].pos;
  1161. if (st->index_entries[n - 1].pos < first_end)
  1162. first_end = st->index_entries[n - 1].pos;
  1163. }
  1164. avio_seek(s->pb, oldpos, SEEK_SET);
  1165. return last_start > first_end;
  1166. }
  1167. static int avi_load_index(AVFormatContext *s)
  1168. {
  1169. AVIContext *avi = s->priv_data;
  1170. AVIOContext *pb = s->pb;
  1171. uint32_t tag, size;
  1172. int64_t pos = avio_tell(pb);
  1173. int ret = -1;
  1174. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1175. goto the_end; // maybe truncated file
  1176. av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1177. for (;;) {
  1178. if (pb->eof_reached)
  1179. break;
  1180. tag = avio_rl32(pb);
  1181. size = avio_rl32(pb);
  1182. av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
  1183. tag & 0xff,
  1184. (tag >> 8) & 0xff,
  1185. (tag >> 16) & 0xff,
  1186. (tag >> 24) & 0xff,
  1187. size);
  1188. if (tag == MKTAG('i', 'd', 'x', '1') &&
  1189. avi_read_idx1(s, size) >= 0) {
  1190. ret = 0;
  1191. break;
  1192. }
  1193. size += (size & 1);
  1194. if (avio_skip(pb, size) < 0)
  1195. break; // something is wrong here
  1196. }
  1197. the_end:
  1198. avio_seek(pb, pos, SEEK_SET);
  1199. return ret;
  1200. }
  1201. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1202. {
  1203. AVIStream *ast2 = st2->priv_data;
  1204. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1205. av_free_packet(&ast2->sub_pkt);
  1206. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1207. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1208. ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1209. }
  1210. static int avi_read_seek(AVFormatContext *s, int stream_index,
  1211. int64_t timestamp, int flags)
  1212. {
  1213. AVIContext *avi = s->priv_data;
  1214. AVStream *st;
  1215. int i, index;
  1216. int64_t pos;
  1217. AVIStream *ast;
  1218. if (!avi->index_loaded) {
  1219. /* we only load the index on demand */
  1220. avi_load_index(s);
  1221. avi->index_loaded = 1;
  1222. }
  1223. assert(stream_index >= 0);
  1224. st = s->streams[stream_index];
  1225. ast = st->priv_data;
  1226. index = av_index_search_timestamp(st,
  1227. timestamp * FFMAX(ast->sample_size, 1),
  1228. flags);
  1229. if (index < 0)
  1230. return AVERROR_INVALIDDATA;
  1231. /* find the position */
  1232. pos = st->index_entries[index].pos;
  1233. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1234. av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
  1235. timestamp, index, st->index_entries[index].timestamp);
  1236. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1237. /* One and only one real stream for DV in AVI, and it has video */
  1238. /* offsets. Calling with other stream indexes should have failed */
  1239. /* the av_index_search_timestamp call above. */
  1240. assert(stream_index == 0);
  1241. /* Feed the DV video stream version of the timestamp to the */
  1242. /* DV demux so it can synthesize correct timestamps. */
  1243. ff_dv_offset_reset(avi->dv_demux, timestamp);
  1244. avio_seek(s->pb, pos, SEEK_SET);
  1245. avi->stream_index = -1;
  1246. return 0;
  1247. }
  1248. for (i = 0; i < s->nb_streams; i++) {
  1249. AVStream *st2 = s->streams[i];
  1250. AVIStream *ast2 = st2->priv_data;
  1251. ast2->packet_size =
  1252. ast2->remaining = 0;
  1253. if (ast2->sub_ctx) {
  1254. seek_subtitle(st, st2, timestamp);
  1255. continue;
  1256. }
  1257. if (st2->nb_index_entries <= 0)
  1258. continue;
  1259. // assert(st2->codec->block_align);
  1260. assert((int64_t)st2->time_base.num * ast2->rate ==
  1261. (int64_t)st2->time_base.den * ast2->scale);
  1262. index = av_index_search_timestamp(st2,
  1263. av_rescale_q(timestamp,
  1264. st->time_base,
  1265. st2->time_base) *
  1266. FFMAX(ast2->sample_size, 1),
  1267. flags | AVSEEK_FLAG_BACKWARD);
  1268. if (index < 0)
  1269. index = 0;
  1270. if (!avi->non_interleaved) {
  1271. while (index > 0 && st2->index_entries[index].pos > pos)
  1272. index--;
  1273. while (index + 1 < st2->nb_index_entries &&
  1274. st2->index_entries[index].pos < pos)
  1275. index++;
  1276. }
  1277. av_dlog(s, "%"PRId64" %d %"PRId64"\n",
  1278. timestamp, index, st2->index_entries[index].timestamp);
  1279. /* extract the current frame number */
  1280. ast2->frame_offset = st2->index_entries[index].timestamp;
  1281. }
  1282. /* do the seek */
  1283. avio_seek(s->pb, pos, SEEK_SET);
  1284. avi->stream_index = -1;
  1285. return 0;
  1286. }
  1287. static int avi_read_close(AVFormatContext *s)
  1288. {
  1289. int i;
  1290. AVIContext *avi = s->priv_data;
  1291. for (i = 0; i < s->nb_streams; i++) {
  1292. AVStream *st = s->streams[i];
  1293. AVIStream *ast = st->priv_data;
  1294. if (ast) {
  1295. if (ast->sub_ctx) {
  1296. av_freep(&ast->sub_ctx->pb);
  1297. avformat_close_input(&ast->sub_ctx);
  1298. }
  1299. av_free(ast->sub_buffer);
  1300. av_free_packet(&ast->sub_pkt);
  1301. }
  1302. }
  1303. av_free(avi->dv_demux);
  1304. return 0;
  1305. }
  1306. static int avi_probe(AVProbeData *p)
  1307. {
  1308. int i;
  1309. /* check file header */
  1310. for (i = 0; avi_headers[i][0]; i++)
  1311. if (!memcmp(p->buf, avi_headers[i], 4) &&
  1312. !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
  1313. return AVPROBE_SCORE_MAX;
  1314. return 0;
  1315. }
  1316. AVInputFormat ff_avi_demuxer = {
  1317. .name = "avi",
  1318. .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
  1319. .priv_data_size = sizeof(AVIContext),
  1320. .read_probe = avi_probe,
  1321. .read_header = avi_read_header,
  1322. .read_packet = avi_read_packet,
  1323. .read_close = avi_read_close,
  1324. .read_seek = avi_read_seek,
  1325. };