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.

1740 lines
60KB

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