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.

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