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.

1534 lines
51KB

  1. /*
  2. * AVI demuxer
  3. * Copyright (c) 2001 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include <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. avi->non_interleaved |= guess_ni_flag(s);
  707. for (i = 0; i < s->nb_streams; i++) {
  708. AVStream *st = s->streams[i];
  709. if (st->nb_index_entries)
  710. break;
  711. }
  712. if (i == s->nb_streams && avi->non_interleaved) {
  713. av_log(s, AV_LOG_WARNING,
  714. "Non-interleaved AVI without index, switching to interleaved\n");
  715. avi->non_interleaved = 0;
  716. }
  717. if (avi->non_interleaved) {
  718. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  719. clean_index(s);
  720. }
  721. ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
  722. ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
  723. return 0;
  724. }
  725. static int read_gab2_sub(AVStream *st, AVPacket *pkt)
  726. {
  727. if (pkt->size >= 7 &&
  728. !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
  729. uint8_t desc[256];
  730. int score = AVPROBE_SCORE_EXTENSION, ret;
  731. AVIStream *ast = st->priv_data;
  732. AVInputFormat *sub_demuxer;
  733. AVRational time_base;
  734. AVIOContext *pb = avio_alloc_context(pkt->data + 7,
  735. pkt->size - 7,
  736. 0, NULL, NULL, NULL, NULL);
  737. AVProbeData pd;
  738. unsigned int desc_len = avio_rl32(pb);
  739. if (desc_len > pb->buf_end - pb->buf_ptr)
  740. goto error;
  741. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  742. avio_skip(pb, desc_len - ret);
  743. if (*desc)
  744. av_dict_set(&st->metadata, "title", desc, 0);
  745. avio_rl16(pb); /* flags? */
  746. avio_rl32(pb); /* data size */
  747. pd = (AVProbeData) { .buf = pb->buf_ptr,
  748. .buf_size = pb->buf_end - pb->buf_ptr };
  749. if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
  750. goto error;
  751. if (!(ast->sub_ctx = avformat_alloc_context()))
  752. goto error;
  753. ast->sub_ctx->pb = pb;
  754. if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
  755. ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
  756. *st->codec = *ast->sub_ctx->streams[0]->codec;
  757. ast->sub_ctx->streams[0]->codec->extradata = NULL;
  758. time_base = ast->sub_ctx->streams[0]->time_base;
  759. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  760. }
  761. ast->sub_buffer = pkt->data;
  762. memset(pkt, 0, sizeof(*pkt));
  763. return 1;
  764. error:
  765. av_freep(&pb);
  766. }
  767. return 0;
  768. }
  769. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  770. AVPacket *pkt)
  771. {
  772. AVIStream *ast, *next_ast = next_st->priv_data;
  773. int64_t ts, next_ts, ts_min = INT64_MAX;
  774. AVStream *st, *sub_st = NULL;
  775. int i;
  776. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  777. AV_TIME_BASE_Q);
  778. for (i = 0; i < s->nb_streams; i++) {
  779. st = s->streams[i];
  780. ast = st->priv_data;
  781. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  782. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  783. if (ts <= next_ts && ts < ts_min) {
  784. ts_min = ts;
  785. sub_st = st;
  786. }
  787. }
  788. }
  789. if (sub_st) {
  790. ast = sub_st->priv_data;
  791. *pkt = ast->sub_pkt;
  792. pkt->stream_index = sub_st->index;
  793. if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  794. ast->sub_pkt.data = NULL;
  795. }
  796. return sub_st;
  797. }
  798. static int get_stream_idx(int *d)
  799. {
  800. if (d[0] >= '0' && d[0] <= '9' &&
  801. d[1] >= '0' && d[1] <= '9') {
  802. return (d[0] - '0') * 10 + (d[1] - '0');
  803. } else {
  804. return 100; // invalid stream ID
  805. }
  806. }
  807. static int avi_sync(AVFormatContext *s, int exit_early)
  808. {
  809. AVIContext *avi = s->priv_data;
  810. AVIOContext *pb = s->pb;
  811. int n;
  812. unsigned int d[8];
  813. unsigned int size;
  814. int64_t i, sync;
  815. start_sync:
  816. memset(d, -1, sizeof(d));
  817. for (i = sync = avio_tell(pb); !pb->eof_reached; i++) {
  818. int j;
  819. for (j = 0; j < 7; j++)
  820. d[j] = d[j + 1];
  821. d[7] = avio_r8(pb);
  822. size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
  823. n = get_stream_idx(d + 2);
  824. av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
  825. d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  826. if (i + (uint64_t)size > avi->fsize || d[0] > 127)
  827. continue;
  828. // parse ix##
  829. if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
  830. // parse JUNK
  831. (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
  832. (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) {
  833. avio_skip(pb, size);
  834. goto start_sync;
  835. }
  836. // parse stray LIST
  837. if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
  838. avio_skip(pb, 4);
  839. goto start_sync;
  840. }
  841. n = avi->dv_demux ? 0 : get_stream_idx(d);
  842. if (!((i - avi->last_pkt_pos) & 1) &&
  843. get_stream_idx(d + 1) < s->nb_streams)
  844. continue;
  845. // detect ##ix chunk and skip
  846. if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
  847. avio_skip(pb, size);
  848. goto start_sync;
  849. }
  850. // parse ##dc/##wb
  851. if (n < s->nb_streams) {
  852. AVStream *st;
  853. AVIStream *ast;
  854. st = s->streams[n];
  855. ast = st->priv_data;
  856. if (s->nb_streams >= 2) {
  857. AVStream *st1 = s->streams[1];
  858. AVIStream *ast1 = st1->priv_data;
  859. // workaround for broken small-file-bug402.avi
  860. if (d[2] == 'w' && d[3] == 'b' && n == 0 &&
  861. st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  862. st1->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  863. ast->prefix == 'd' * 256 + 'c' &&
  864. (d[2] * 256 + d[3] == ast1->prefix ||
  865. !ast1->prefix_count)) {
  866. n = 1;
  867. st = st1;
  868. ast = ast1;
  869. av_log(s, AV_LOG_WARNING,
  870. "Invalid stream + prefix combination, assuming audio.\n");
  871. }
  872. }
  873. if (!avi->dv_demux &&
  874. ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
  875. // FIXME: needs a little reordering
  876. (st->discard >= AVDISCARD_NONKEY &&
  877. !(pkt->flags & AV_PKT_FLAG_KEY)) */
  878. || st->discard >= AVDISCARD_ALL)) {
  879. if (!exit_early) {
  880. ast->frame_offset += get_duration(ast, size);
  881. }
  882. avio_skip(pb, size);
  883. goto start_sync;
  884. }
  885. if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
  886. int k = avio_r8(pb);
  887. int last = (k + avio_r8(pb) - 1) & 0xFF;
  888. avio_rl16(pb); // flags
  889. // b + (g << 8) + (r << 16);
  890. for (; k <= last; k++)
  891. ast->pal[k] = avio_rb32(pb) >> 8;
  892. ast->has_pal = 1;
  893. goto start_sync;
  894. } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
  895. d[2] < 128 && d[3] < 128) ||
  896. d[2] * 256 + d[3] == ast->prefix /* ||
  897. (d[2] == 'd' && d[3] == 'c') ||
  898. (d[2] == 'w' && d[3] == 'b') */) {
  899. if (exit_early)
  900. return 0;
  901. if (d[2] * 256 + d[3] == ast->prefix)
  902. ast->prefix_count++;
  903. else {
  904. ast->prefix = d[2] * 256 + d[3];
  905. ast->prefix_count = 0;
  906. }
  907. avi->stream_index = n;
  908. ast->packet_size = size + 8;
  909. ast->remaining = size;
  910. if (size || !ast->sample_size) {
  911. uint64_t pos = avio_tell(pb) - 8;
  912. if (!st->index_entries || !st->nb_index_entries ||
  913. st->index_entries[st->nb_index_entries - 1].pos < pos) {
  914. av_add_index_entry(st, pos, ast->frame_offset, size,
  915. 0, AVINDEX_KEYFRAME);
  916. }
  917. }
  918. return 0;
  919. }
  920. }
  921. }
  922. return AVERROR_EOF;
  923. }
  924. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  925. {
  926. AVIContext *avi = s->priv_data;
  927. AVIOContext *pb = s->pb;
  928. int err;
  929. #if FF_API_DESTRUCT_PACKET
  930. void *dstr;
  931. #endif
  932. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  933. int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
  934. if (size >= 0)
  935. return size;
  936. else
  937. goto resync;
  938. }
  939. if (avi->non_interleaved) {
  940. int best_stream_index = 0;
  941. AVStream *best_st = NULL;
  942. AVIStream *best_ast;
  943. int64_t best_ts = INT64_MAX;
  944. int i;
  945. for (i = 0; i < s->nb_streams; i++) {
  946. AVStream *st = s->streams[i];
  947. AVIStream *ast = st->priv_data;
  948. int64_t ts = ast->frame_offset;
  949. int64_t last_ts;
  950. if (!st->nb_index_entries)
  951. continue;
  952. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  953. if (!ast->remaining && ts > last_ts)
  954. continue;
  955. ts = av_rescale_q(ts, st->time_base,
  956. (AVRational) { FFMAX(1, ast->sample_size),
  957. AV_TIME_BASE });
  958. av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
  959. st->time_base.num, st->time_base.den, ast->frame_offset);
  960. if (ts < best_ts) {
  961. best_ts = ts;
  962. best_st = st;
  963. best_stream_index = i;
  964. }
  965. }
  966. if (!best_st)
  967. return AVERROR_EOF;
  968. best_ast = best_st->priv_data;
  969. best_ts = av_rescale_q(best_ts,
  970. (AVRational) { FFMAX(1, best_ast->sample_size),
  971. AV_TIME_BASE },
  972. best_st->time_base);
  973. if (best_ast->remaining) {
  974. i = av_index_search_timestamp(best_st,
  975. best_ts,
  976. AVSEEK_FLAG_ANY |
  977. AVSEEK_FLAG_BACKWARD);
  978. } else {
  979. i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  980. if (i >= 0)
  981. best_ast->frame_offset = best_st->index_entries[i].timestamp;
  982. }
  983. if (i >= 0) {
  984. int64_t pos = best_st->index_entries[i].pos;
  985. pos += best_ast->packet_size - best_ast->remaining;
  986. avio_seek(s->pb, pos + 8, SEEK_SET);
  987. assert(best_ast->remaining <= best_ast->packet_size);
  988. avi->stream_index = best_stream_index;
  989. if (!best_ast->remaining)
  990. best_ast->packet_size =
  991. best_ast->remaining = best_st->index_entries[i].size;
  992. }
  993. }
  994. resync:
  995. if (avi->stream_index >= 0) {
  996. AVStream *st = s->streams[avi->stream_index];
  997. AVIStream *ast = st->priv_data;
  998. int size, err;
  999. if (get_subtitle_pkt(s, st, pkt))
  1000. return 0;
  1001. // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  1002. if (ast->sample_size <= 1)
  1003. size = INT_MAX;
  1004. else if (ast->sample_size < 32)
  1005. // arbitrary multiplier to avoid tiny packets for raw PCM data
  1006. size = 1024 * ast->sample_size;
  1007. else
  1008. size = ast->sample_size;
  1009. if (size > ast->remaining)
  1010. size = ast->remaining;
  1011. avi->last_pkt_pos = avio_tell(pb);
  1012. err = av_get_packet(pb, pkt, size);
  1013. if (err < 0)
  1014. return err;
  1015. if (ast->has_pal && pkt->data && pkt->size < (unsigned)INT_MAX / 2) {
  1016. uint8_t *pal;
  1017. pal = av_packet_new_side_data(pkt,
  1018. AV_PKT_DATA_PALETTE,
  1019. AVPALETTE_SIZE);
  1020. if (!pal) {
  1021. av_log(s, AV_LOG_ERROR,
  1022. "Failed to allocate data for palette\n");
  1023. } else {
  1024. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  1025. ast->has_pal = 0;
  1026. }
  1027. }
  1028. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1029. AVBufferRef *avbuf = pkt->buf;
  1030. #if FF_API_DESTRUCT_PACKET
  1031. FF_DISABLE_DEPRECATION_WARNINGS
  1032. dstr = pkt->destruct;
  1033. FF_ENABLE_DEPRECATION_WARNINGS
  1034. #endif
  1035. size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
  1036. pkt->data, pkt->size);
  1037. #if FF_API_DESTRUCT_PACKET
  1038. FF_DISABLE_DEPRECATION_WARNINGS
  1039. pkt->destruct = dstr;
  1040. FF_ENABLE_DEPRECATION_WARNINGS
  1041. #endif
  1042. pkt->buf = avbuf;
  1043. pkt->flags |= AV_PKT_FLAG_KEY;
  1044. if (size < 0)
  1045. av_free_packet(pkt);
  1046. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1047. !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
  1048. ast->frame_offset++;
  1049. avi->stream_index = -1;
  1050. ast->remaining = 0;
  1051. goto resync;
  1052. } else {
  1053. /* XXX: How to handle B-frames in AVI? */
  1054. pkt->dts = ast->frame_offset;
  1055. // pkt->dts += ast->start;
  1056. if (ast->sample_size)
  1057. pkt->dts /= ast->sample_size;
  1058. av_dlog(s,
  1059. "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d "
  1060. "base:%d st:%d size:%d\n",
  1061. pkt->dts,
  1062. ast->frame_offset,
  1063. ast->scale,
  1064. ast->rate,
  1065. ast->sample_size,
  1066. AV_TIME_BASE,
  1067. avi->stream_index,
  1068. size);
  1069. pkt->stream_index = avi->stream_index;
  1070. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1071. AVIndexEntry *e;
  1072. int index;
  1073. assert(st->index_entries);
  1074. index = av_index_search_timestamp(st, ast->frame_offset, 0);
  1075. e = &st->index_entries[index];
  1076. if (index >= 0 && e->timestamp == ast->frame_offset)
  1077. if (e->flags & AVINDEX_KEYFRAME)
  1078. pkt->flags |= AV_PKT_FLAG_KEY;
  1079. } else {
  1080. pkt->flags |= AV_PKT_FLAG_KEY;
  1081. }
  1082. ast->frame_offset += get_duration(ast, pkt->size);
  1083. }
  1084. ast->remaining -= err;
  1085. if (!ast->remaining) {
  1086. avi->stream_index = -1;
  1087. ast->packet_size = 0;
  1088. }
  1089. return 0;
  1090. }
  1091. if ((err = avi_sync(s, 0)) < 0)
  1092. return err;
  1093. goto resync;
  1094. }
  1095. /* XXX: We make the implicit supposition that the positions are sorted
  1096. * for each stream. */
  1097. static int avi_read_idx1(AVFormatContext *s, int size)
  1098. {
  1099. AVIContext *avi = s->priv_data;
  1100. AVIOContext *pb = s->pb;
  1101. int nb_index_entries, i;
  1102. AVStream *st;
  1103. AVIStream *ast;
  1104. unsigned int index, tag, flags, pos, len, first_packet = 1;
  1105. unsigned last_pos = -1;
  1106. int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
  1107. nb_index_entries = size / 16;
  1108. if (nb_index_entries <= 0)
  1109. return AVERROR_INVALIDDATA;
  1110. idx1_pos = avio_tell(pb);
  1111. avio_seek(pb, avi->movi_list + 4, SEEK_SET);
  1112. if (avi_sync(s, 1) == 0)
  1113. first_packet_pos = avio_tell(pb) - 8;
  1114. avi->stream_index = -1;
  1115. avio_seek(pb, idx1_pos, SEEK_SET);
  1116. /* Read the entries and sort them in each stream component. */
  1117. for (i = 0; i < nb_index_entries; i++) {
  1118. tag = avio_rl32(pb);
  1119. flags = avio_rl32(pb);
  1120. pos = avio_rl32(pb);
  1121. len = avio_rl32(pb);
  1122. av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  1123. i, tag, flags, pos, len);
  1124. index = ((tag & 0xff) - '0') * 10;
  1125. index += (tag >> 8 & 0xff) - '0';
  1126. if (index >= s->nb_streams)
  1127. continue;
  1128. st = s->streams[index];
  1129. ast = st->priv_data;
  1130. if (first_packet && first_packet_pos && len) {
  1131. data_offset = first_packet_pos - pos;
  1132. first_packet = 0;
  1133. }
  1134. pos += data_offset;
  1135. av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1136. if (pb->eof_reached)
  1137. return AVERROR_INVALIDDATA;
  1138. if (last_pos == pos)
  1139. avi->non_interleaved = 1;
  1140. else if (len || !ast->sample_size)
  1141. av_add_index_entry(st, pos, ast->cum_len, len, 0,
  1142. (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1143. ast->cum_len += get_duration(ast, len);
  1144. last_pos = pos;
  1145. }
  1146. return 0;
  1147. }
  1148. static int guess_ni_flag(AVFormatContext *s)
  1149. {
  1150. int i;
  1151. int64_t last_start = 0;
  1152. int64_t first_end = INT64_MAX;
  1153. int64_t oldpos = avio_tell(s->pb);
  1154. for (i = 0; i < s->nb_streams; i++) {
  1155. AVStream *st = s->streams[i];
  1156. int n = st->nb_index_entries;
  1157. unsigned int size;
  1158. if (n <= 0)
  1159. continue;
  1160. if (n >= 2) {
  1161. int64_t pos = st->index_entries[0].pos;
  1162. avio_seek(s->pb, pos + 4, SEEK_SET);
  1163. size = avio_rl32(s->pb);
  1164. if (pos + size > st->index_entries[1].pos)
  1165. last_start = INT64_MAX;
  1166. }
  1167. if (st->index_entries[0].pos > last_start)
  1168. last_start = st->index_entries[0].pos;
  1169. if (st->index_entries[n - 1].pos < first_end)
  1170. first_end = st->index_entries[n - 1].pos;
  1171. }
  1172. avio_seek(s->pb, oldpos, SEEK_SET);
  1173. return last_start > first_end;
  1174. }
  1175. static int avi_load_index(AVFormatContext *s)
  1176. {
  1177. AVIContext *avi = s->priv_data;
  1178. AVIOContext *pb = s->pb;
  1179. uint32_t tag, size;
  1180. int64_t pos = avio_tell(pb);
  1181. int ret = -1;
  1182. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1183. goto the_end; // maybe truncated file
  1184. av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1185. for (;;) {
  1186. if (pb->eof_reached)
  1187. break;
  1188. tag = avio_rl32(pb);
  1189. size = avio_rl32(pb);
  1190. av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
  1191. tag & 0xff,
  1192. (tag >> 8) & 0xff,
  1193. (tag >> 16) & 0xff,
  1194. (tag >> 24) & 0xff,
  1195. size);
  1196. if (tag == MKTAG('i', 'd', 'x', '1') &&
  1197. avi_read_idx1(s, size) >= 0) {
  1198. ret = 0;
  1199. break;
  1200. }
  1201. size += (size & 1);
  1202. if (avio_skip(pb, size) < 0)
  1203. break; // something is wrong here
  1204. }
  1205. the_end:
  1206. avio_seek(pb, pos, SEEK_SET);
  1207. return ret;
  1208. }
  1209. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1210. {
  1211. AVIStream *ast2 = st2->priv_data;
  1212. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1213. av_free_packet(&ast2->sub_pkt);
  1214. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1215. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1216. ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1217. }
  1218. static int avi_read_seek(AVFormatContext *s, int stream_index,
  1219. int64_t timestamp, int flags)
  1220. {
  1221. AVIContext *avi = s->priv_data;
  1222. AVStream *st;
  1223. int i, index;
  1224. int64_t pos;
  1225. AVIStream *ast;
  1226. /* Does not matter which stream is requested dv in avi has the
  1227. * stream information in the first video stream.
  1228. */
  1229. if (avi->dv_demux)
  1230. stream_index = 0;
  1231. if (!avi->index_loaded) {
  1232. /* we only load the index on demand */
  1233. avi_load_index(s);
  1234. avi->index_loaded = 1;
  1235. }
  1236. st = s->streams[stream_index];
  1237. ast = st->priv_data;
  1238. index = av_index_search_timestamp(st,
  1239. timestamp * FFMAX(ast->sample_size, 1),
  1240. flags);
  1241. if (index < 0)
  1242. return AVERROR_INVALIDDATA;
  1243. /* find the position */
  1244. pos = st->index_entries[index].pos;
  1245. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1246. av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
  1247. timestamp, index, st->index_entries[index].timestamp);
  1248. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1249. /* One and only one real stream for DV in AVI, and it has video */
  1250. /* offsets. Calling with other stream indexes should have failed */
  1251. /* the av_index_search_timestamp call above. */
  1252. /* Feed the DV video stream version of the timestamp to the */
  1253. /* DV demux so it can synthesize correct timestamps. */
  1254. ff_dv_offset_reset(avi->dv_demux, timestamp);
  1255. avio_seek(s->pb, pos, SEEK_SET);
  1256. avi->stream_index = -1;
  1257. return 0;
  1258. }
  1259. for (i = 0; i < s->nb_streams; i++) {
  1260. AVStream *st2 = s->streams[i];
  1261. AVIStream *ast2 = st2->priv_data;
  1262. ast2->packet_size =
  1263. ast2->remaining = 0;
  1264. if (ast2->sub_ctx) {
  1265. seek_subtitle(st, st2, timestamp);
  1266. continue;
  1267. }
  1268. if (st2->nb_index_entries <= 0)
  1269. continue;
  1270. // assert(st2->codec->block_align);
  1271. assert((int64_t)st2->time_base.num * ast2->rate ==
  1272. (int64_t)st2->time_base.den * ast2->scale);
  1273. index = av_index_search_timestamp(st2,
  1274. av_rescale_q(timestamp,
  1275. st->time_base,
  1276. st2->time_base) *
  1277. FFMAX(ast2->sample_size, 1),
  1278. flags | AVSEEK_FLAG_BACKWARD);
  1279. if (index < 0)
  1280. index = 0;
  1281. if (!avi->non_interleaved) {
  1282. while (index > 0 && st2->index_entries[index].pos > pos)
  1283. index--;
  1284. while (index + 1 < st2->nb_index_entries &&
  1285. st2->index_entries[index].pos < pos)
  1286. index++;
  1287. }
  1288. av_dlog(s, "%"PRId64" %d %"PRId64"\n",
  1289. timestamp, index, st2->index_entries[index].timestamp);
  1290. /* extract the current frame number */
  1291. ast2->frame_offset = st2->index_entries[index].timestamp;
  1292. }
  1293. /* do the seek */
  1294. avio_seek(s->pb, pos, SEEK_SET);
  1295. avi->stream_index = -1;
  1296. return 0;
  1297. }
  1298. static int avi_read_close(AVFormatContext *s)
  1299. {
  1300. int i;
  1301. AVIContext *avi = s->priv_data;
  1302. for (i = 0; i < s->nb_streams; i++) {
  1303. AVStream *st = s->streams[i];
  1304. AVIStream *ast = st->priv_data;
  1305. if (ast) {
  1306. if (ast->sub_ctx) {
  1307. av_freep(&ast->sub_ctx->pb);
  1308. avformat_close_input(&ast->sub_ctx);
  1309. }
  1310. av_free(ast->sub_buffer);
  1311. av_free_packet(&ast->sub_pkt);
  1312. }
  1313. }
  1314. av_free(avi->dv_demux);
  1315. return 0;
  1316. }
  1317. static int avi_probe(AVProbeData *p)
  1318. {
  1319. int i;
  1320. /* check file header */
  1321. for (i = 0; avi_headers[i][0]; i++)
  1322. if (!memcmp(p->buf, avi_headers[i], 4) &&
  1323. !memcmp(p->buf + 8, avi_headers[i] + 4, 4))
  1324. return AVPROBE_SCORE_MAX;
  1325. return 0;
  1326. }
  1327. AVInputFormat ff_avi_demuxer = {
  1328. .name = "avi",
  1329. .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
  1330. .priv_data_size = sizeof(AVIContext),
  1331. .read_probe = avi_probe,
  1332. .read_header = avi_read_header,
  1333. .read_packet = avi_read_packet,
  1334. .read_close = avi_read_close,
  1335. .read_seek = avi_read_seek,
  1336. };