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.

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