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.

1803 lines
61KB

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