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.

1601 lines
53KB

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