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.

1106 lines
36KB

  1. /*
  2. * AVI demuxer
  3. * Copyright (c) 2001 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "avformat.h"
  22. #include "avi.h"
  23. #include "dv.h"
  24. #include "riff.h"
  25. #undef NDEBUG
  26. #include <assert.h>
  27. //#define DEBUG
  28. //#define DEBUG_SEEK
  29. typedef struct AVIStream {
  30. int64_t frame_offset; /* current frame (video) or byte (audio) counter
  31. (used to compute the pts) */
  32. int remaining;
  33. int packet_size;
  34. int scale;
  35. int rate;
  36. int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
  37. int64_t cum_len; /* temporary storage (used during seek) */
  38. int prefix; ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
  39. int prefix_count;
  40. uint32_t pal[256];
  41. int has_pal;
  42. } AVIStream;
  43. typedef struct {
  44. int64_t riff_end;
  45. int64_t movi_end;
  46. int64_t fsize;
  47. int64_t movi_list;
  48. int64_t last_pkt_pos;
  49. int index_loaded;
  50. int is_odml;
  51. int non_interleaved;
  52. int stream_index;
  53. DVDemuxContext* dv_demux;
  54. } AVIContext;
  55. static const char avi_headers[][8] = {
  56. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
  57. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
  58. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
  59. { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
  60. { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
  61. { 0 }
  62. };
  63. static int avi_load_index(AVFormatContext *s);
  64. static int guess_ni_flag(AVFormatContext *s);
  65. #ifdef DEBUG
  66. static void print_tag(const char *str, unsigned int tag, int size)
  67. {
  68. printf("%s: tag=%c%c%c%c size=0x%x\n",
  69. str, tag & 0xff,
  70. (tag >> 8) & 0xff,
  71. (tag >> 16) & 0xff,
  72. (tag >> 24) & 0xff,
  73. size);
  74. }
  75. #endif
  76. static int get_riff(AVIContext *avi, ByteIOContext *pb)
  77. {
  78. char header[8];
  79. int i;
  80. /* check RIFF header */
  81. get_buffer(pb, header, 4);
  82. avi->riff_end = get_le32(pb); /* RIFF chunk size */
  83. avi->riff_end += url_ftell(pb); /* RIFF chunk end */
  84. get_buffer(pb, header+4, 4);
  85. for(i=0; avi_headers[i][0]; i++)
  86. if(!memcmp(header, avi_headers[i], 8))
  87. break;
  88. if(!avi_headers[i][0])
  89. return -1;
  90. if(header[7] == 0x19)
  91. av_log(NULL, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
  92. return 0;
  93. }
  94. static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
  95. AVIContext *avi = s->priv_data;
  96. ByteIOContext *pb = s->pb;
  97. int longs_pre_entry= get_le16(pb);
  98. int index_sub_type = get_byte(pb);
  99. int index_type = get_byte(pb);
  100. int entries_in_use = get_le32(pb);
  101. int chunk_id = get_le32(pb);
  102. int64_t base = get_le64(pb);
  103. int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
  104. AVStream *st;
  105. AVIStream *ast;
  106. int i;
  107. int64_t last_pos= -1;
  108. int64_t filesize= url_fsize(s->pb);
  109. #ifdef DEBUG_SEEK
  110. av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
  111. longs_pre_entry,index_type, entries_in_use, chunk_id, base);
  112. #endif
  113. if(stream_id > s->nb_streams || stream_id < 0)
  114. return -1;
  115. st= s->streams[stream_id];
  116. ast = st->priv_data;
  117. if(index_sub_type)
  118. return -1;
  119. get_le32(pb);
  120. if(index_type && longs_pre_entry != 2)
  121. return -1;
  122. if(index_type>1)
  123. return -1;
  124. if(filesize > 0 && base >= filesize){
  125. av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
  126. if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
  127. base &= 0xFFFFFFFF;
  128. else
  129. return -1;
  130. }
  131. for(i=0; i<entries_in_use; i++){
  132. if(index_type){
  133. int64_t pos= get_le32(pb) + base - 8;
  134. int len = get_le32(pb);
  135. int key= len >= 0;
  136. len &= 0x7FFFFFFF;
  137. #ifdef DEBUG_SEEK
  138. av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
  139. #endif
  140. if(last_pos == pos || pos == base - 8)
  141. avi->non_interleaved= 1;
  142. if(last_pos != pos)
  143. av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, key ? AVINDEX_KEYFRAME : 0);
  144. if(ast->sample_size)
  145. ast->cum_len += len;
  146. else
  147. ast->cum_len ++;
  148. last_pos= pos;
  149. }else{
  150. int64_t offset, pos;
  151. int duration;
  152. offset = get_le64(pb);
  153. get_le32(pb); /* size */
  154. duration = get_le32(pb);
  155. pos = url_ftell(pb);
  156. url_fseek(pb, offset+8, SEEK_SET);
  157. read_braindead_odml_indx(s, frame_num);
  158. frame_num += duration;
  159. url_fseek(pb, pos, SEEK_SET);
  160. }
  161. }
  162. avi->index_loaded=1;
  163. return 0;
  164. }
  165. static void clean_index(AVFormatContext *s){
  166. int i;
  167. int64_t j;
  168. for(i=0; i<s->nb_streams; i++){
  169. AVStream *st = s->streams[i];
  170. AVIStream *ast = st->priv_data;
  171. int n= st->nb_index_entries;
  172. int max= ast->sample_size;
  173. int64_t pos, size, ts;
  174. if(n != 1 || ast->sample_size==0)
  175. continue;
  176. while(max < 1024) max+=max;
  177. pos= st->index_entries[0].pos;
  178. size= st->index_entries[0].size;
  179. ts= st->index_entries[0].timestamp;
  180. for(j=0; j<size; j+=max){
  181. av_add_index_entry(st, pos+j, ts + j/ast->sample_size, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
  182. }
  183. }
  184. }
  185. static int avi_read_tag(AVFormatContext *s, const char *key, unsigned int size)
  186. {
  187. ByteIOContext *pb = s->pb;
  188. uint8_t value[1024];
  189. int64_t i = url_ftell(pb);
  190. size += (size & 1);
  191. get_strz(pb, value, sizeof(value));
  192. url_fseek(pb, i+size, SEEK_SET);
  193. return av_metadata_set(&s->metadata, (const AVMetadataTag){key, value});
  194. }
  195. static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
  196. {
  197. AVIContext *avi = s->priv_data;
  198. ByteIOContext *pb = s->pb;
  199. uint32_t tag, tag1, handler;
  200. int codec_type, stream_index, frame_period, bit_rate;
  201. unsigned int size, nb_frames;
  202. int i;
  203. AVStream *st;
  204. AVIStream *ast = NULL;
  205. int avih_width=0, avih_height=0;
  206. int amv_file_format=0;
  207. avi->stream_index= -1;
  208. if (get_riff(avi, pb) < 0)
  209. return -1;
  210. avi->fsize = url_fsize(pb);
  211. if(avi->fsize<=0)
  212. avi->fsize= avi->riff_end;
  213. /* first list tag */
  214. stream_index = -1;
  215. codec_type = -1;
  216. frame_period = 0;
  217. for(;;) {
  218. if (url_feof(pb))
  219. goto fail;
  220. tag = get_le32(pb);
  221. size = get_le32(pb);
  222. #ifdef DEBUG
  223. print_tag("tag", tag, size);
  224. #endif
  225. switch(tag) {
  226. case MKTAG('L', 'I', 'S', 'T'):
  227. /* Ignored, except at start of video packets. */
  228. tag1 = get_le32(pb);
  229. #ifdef DEBUG
  230. print_tag("list", tag1, 0);
  231. #endif
  232. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  233. avi->movi_list = url_ftell(pb) - 4;
  234. if(size) avi->movi_end = avi->movi_list + size + (size & 1);
  235. else avi->movi_end = url_fsize(pb);
  236. #ifdef DEBUG
  237. printf("movi end=%"PRIx64"\n", avi->movi_end);
  238. #endif
  239. goto end_of_header;
  240. }
  241. break;
  242. case MKTAG('d', 'm', 'l', 'h'):
  243. avi->is_odml = 1;
  244. url_fskip(pb, size + (size & 1));
  245. break;
  246. case MKTAG('a', 'm', 'v', 'h'):
  247. amv_file_format=1;
  248. case MKTAG('a', 'v', 'i', 'h'):
  249. /* AVI header */
  250. /* using frame_period is bad idea */
  251. frame_period = get_le32(pb);
  252. bit_rate = get_le32(pb) * 8;
  253. get_le32(pb);
  254. avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
  255. url_fskip(pb, 2 * 4);
  256. get_le32(pb);
  257. get_le32(pb);
  258. avih_width=get_le32(pb);
  259. avih_height=get_le32(pb);
  260. url_fskip(pb, size - 10 * 4);
  261. break;
  262. case MKTAG('s', 't', 'r', 'h'):
  263. /* stream header */
  264. tag1 = get_le32(pb);
  265. handler = get_le32(pb); /* codec tag */
  266. if(tag1 == MKTAG('p', 'a', 'd', 's')){
  267. url_fskip(pb, size - 8);
  268. break;
  269. }else{
  270. stream_index++;
  271. st = av_new_stream(s, stream_index);
  272. if (!st)
  273. goto fail;
  274. ast = av_mallocz(sizeof(AVIStream));
  275. if (!ast)
  276. goto fail;
  277. st->priv_data = ast;
  278. }
  279. if(amv_file_format)
  280. tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
  281. #ifdef DEBUG
  282. print_tag("strh", tag1, -1);
  283. #endif
  284. if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
  285. int64_t dv_dur;
  286. /*
  287. * After some consideration -- I don't think we
  288. * have to support anything but DV in type1 AVIs.
  289. */
  290. if (s->nb_streams != 1)
  291. goto fail;
  292. if (handler != MKTAG('d', 'v', 's', 'd') &&
  293. handler != MKTAG('d', 'v', 'h', 'd') &&
  294. handler != MKTAG('d', 'v', 's', 'l'))
  295. goto fail;
  296. ast = s->streams[0]->priv_data;
  297. av_freep(&s->streams[0]->codec->extradata);
  298. av_freep(&s->streams[0]);
  299. s->nb_streams = 0;
  300. if (ENABLE_DV_DEMUXER) {
  301. avi->dv_demux = dv_init_demux(s);
  302. if (!avi->dv_demux)
  303. goto fail;
  304. }
  305. s->streams[0]->priv_data = ast;
  306. url_fskip(pb, 3 * 4);
  307. ast->scale = get_le32(pb);
  308. ast->rate = get_le32(pb);
  309. url_fskip(pb, 4); /* start time */
  310. dv_dur = get_le32(pb);
  311. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  312. dv_dur *= AV_TIME_BASE;
  313. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  314. }
  315. /*
  316. * else, leave duration alone; timing estimation in utils.c
  317. * will make a guess based on bitrate.
  318. */
  319. stream_index = s->nb_streams - 1;
  320. url_fskip(pb, size - 9*4);
  321. break;
  322. }
  323. assert(stream_index < s->nb_streams);
  324. st->codec->stream_codec_tag= handler;
  325. get_le32(pb); /* flags */
  326. get_le16(pb); /* priority */
  327. get_le16(pb); /* language */
  328. get_le32(pb); /* initial frame */
  329. ast->scale = get_le32(pb);
  330. ast->rate = get_le32(pb);
  331. if(!(ast->scale && ast->rate)){
  332. av_log(s, AV_LOG_WARNING, "scale/rate is %u/%u which is invalid. (This file has been generated by broken software.)\n", ast->scale, ast->rate);
  333. if(frame_period){
  334. ast->rate = 1000000;
  335. ast->scale = frame_period;
  336. }else{
  337. ast->rate = 25;
  338. ast->scale = 1;
  339. }
  340. }
  341. av_set_pts_info(st, 64, ast->scale, ast->rate);
  342. ast->cum_len=get_le32(pb); /* start */
  343. nb_frames = get_le32(pb);
  344. st->start_time = 0;
  345. st->duration = nb_frames;
  346. get_le32(pb); /* buffer size */
  347. get_le32(pb); /* quality */
  348. ast->sample_size = get_le32(pb); /* sample ssize */
  349. ast->cum_len *= FFMAX(1, ast->sample_size);
  350. // av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
  351. switch(tag1) {
  352. case MKTAG('v', 'i', 'd', 's'):
  353. codec_type = CODEC_TYPE_VIDEO;
  354. ast->sample_size = 0;
  355. break;
  356. case MKTAG('a', 'u', 'd', 's'):
  357. codec_type = CODEC_TYPE_AUDIO;
  358. break;
  359. case MKTAG('t', 'x', 't', 's'):
  360. //FIXME
  361. codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ? FIXME
  362. break;
  363. case MKTAG('d', 'a', 't', 's'):
  364. codec_type = CODEC_TYPE_DATA;
  365. break;
  366. default:
  367. av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
  368. goto fail;
  369. }
  370. ast->frame_offset= ast->cum_len;
  371. url_fskip(pb, size - 12 * 4);
  372. break;
  373. case MKTAG('s', 't', 'r', 'f'):
  374. /* stream header */
  375. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  376. url_fskip(pb, size);
  377. } else {
  378. st = s->streams[stream_index];
  379. switch(codec_type) {
  380. case CODEC_TYPE_VIDEO:
  381. if(amv_file_format){
  382. st->codec->width=avih_width;
  383. st->codec->height=avih_height;
  384. st->codec->codec_type = CODEC_TYPE_VIDEO;
  385. st->codec->codec_id = CODEC_ID_AMV;
  386. url_fskip(pb, size);
  387. break;
  388. }
  389. get_le32(pb); /* size */
  390. st->codec->width = get_le32(pb);
  391. st->codec->height = get_le32(pb);
  392. get_le16(pb); /* panes */
  393. st->codec->bits_per_coded_sample= get_le16(pb); /* depth */
  394. tag1 = get_le32(pb);
  395. get_le32(pb); /* ImageSize */
  396. get_le32(pb); /* XPelsPerMeter */
  397. get_le32(pb); /* YPelsPerMeter */
  398. get_le32(pb); /* ClrUsed */
  399. get_le32(pb); /* ClrImportant */
  400. if (tag1 == MKTAG('D', 'X', 'S', 'B')) {
  401. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  402. st->codec->codec_tag = tag1;
  403. st->codec->codec_id = CODEC_ID_XSUB;
  404. break;
  405. }
  406. if(size > 10*4 && size<(1<<30)){
  407. st->codec->extradata_size= size - 10*4;
  408. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  409. get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
  410. }
  411. if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  412. get_byte(pb);
  413. /* Extract palette from extradata if bpp <= 8. */
  414. /* This code assumes that extradata contains only palette. */
  415. /* This is true for all paletted codecs implemented in FFmpeg. */
  416. if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
  417. st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
  418. #ifdef WORDS_BIGENDIAN
  419. for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
  420. st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
  421. #else
  422. memcpy(st->codec->palctrl->palette, st->codec->extradata,
  423. FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
  424. #endif
  425. st->codec->palctrl->palette_changed = 1;
  426. }
  427. #ifdef DEBUG
  428. print_tag("video", tag1, 0);
  429. #endif
  430. st->codec->codec_type = CODEC_TYPE_VIDEO;
  431. st->codec->codec_tag = tag1;
  432. st->codec->codec_id = codec_get_id(codec_bmp_tags, tag1);
  433. st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
  434. // url_fskip(pb, size - 5 * 4);
  435. break;
  436. case CODEC_TYPE_AUDIO:
  437. get_wav_header(pb, st->codec, size);
  438. if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
  439. av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
  440. ast->sample_size= st->codec->block_align;
  441. }
  442. if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  443. url_fskip(pb, 1);
  444. /* Force parsing as several audio frames can be in
  445. * one packet and timestamps refer to packet start. */
  446. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  447. /* ADTS header is in extradata, AAC without header must be
  448. * stored as exact frames. Parser not needed and it will
  449. * fail. */
  450. if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
  451. st->need_parsing = AVSTREAM_PARSE_NONE;
  452. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  453. * audio in the header but have Axan as stream_code_tag. */
  454. if (st->codec->stream_codec_tag == ff_get_fourcc("Axan")){
  455. st->codec->codec_id = CODEC_ID_XAN_DPCM;
  456. st->codec->codec_tag = 0;
  457. }
  458. if (amv_file_format)
  459. st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
  460. break;
  461. default:
  462. st->codec->codec_type = CODEC_TYPE_DATA;
  463. st->codec->codec_id= CODEC_ID_NONE;
  464. st->codec->codec_tag= 0;
  465. url_fskip(pb, size);
  466. break;
  467. }
  468. }
  469. break;
  470. case MKTAG('i', 'n', 'd', 'x'):
  471. i= url_ftell(pb);
  472. if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
  473. read_braindead_odml_indx(s, 0);
  474. }
  475. url_fseek(pb, i+size, SEEK_SET);
  476. break;
  477. case MKTAG('v', 'p', 'r', 'p'):
  478. if(stream_index < (unsigned)s->nb_streams && size > 9*4){
  479. AVRational active, active_aspect;
  480. st = s->streams[stream_index];
  481. get_le32(pb);
  482. get_le32(pb);
  483. get_le32(pb);
  484. get_le32(pb);
  485. get_le32(pb);
  486. active_aspect.den= get_le16(pb);
  487. active_aspect.num= get_le16(pb);
  488. active.num = get_le32(pb);
  489. active.den = get_le32(pb);
  490. get_le32(pb); //nbFieldsPerFrame
  491. if(active_aspect.num && active_aspect.den && active.num && active.den){
  492. st->sample_aspect_ratio= av_div_q(active_aspect, active);
  493. //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
  494. }
  495. size -= 9*4;
  496. }
  497. url_fseek(pb, size, SEEK_CUR);
  498. break;
  499. case MKTAG('I', 'N', 'A', 'M'):
  500. avi_read_tag(s, "Title", size);
  501. break;
  502. case MKTAG('I', 'A', 'R', 'T'):
  503. avi_read_tag(s, "Artist", size);
  504. break;
  505. case MKTAG('I', 'C', 'O', 'P'):
  506. avi_read_tag(s, "Copyright", size);
  507. break;
  508. case MKTAG('I', 'C', 'M', 'T'):
  509. avi_read_tag(s, "Comment", size);
  510. break;
  511. case MKTAG('I', 'G', 'N', 'R'):
  512. avi_read_tag(s, "Genre", size);
  513. break;
  514. case MKTAG('I', 'P', 'R', 'D'):
  515. avi_read_tag(s, "Album", size);
  516. break;
  517. case MKTAG('I', 'P', 'R', 'T'):
  518. avi_read_tag(s, "Track", size);
  519. break;
  520. default:
  521. if(size > 1000000){
  522. av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
  523. "I will ignore it and try to continue anyway.\n");
  524. avi->movi_list = url_ftell(pb) - 4;
  525. avi->movi_end = url_fsize(pb);
  526. goto end_of_header;
  527. }
  528. /* skip tag */
  529. size += (size & 1);
  530. url_fskip(pb, size);
  531. break;
  532. }
  533. }
  534. end_of_header:
  535. /* check stream number */
  536. if (stream_index != s->nb_streams - 1) {
  537. fail:
  538. return -1;
  539. }
  540. if(!avi->index_loaded && !url_is_streamed(pb))
  541. avi_load_index(s);
  542. avi->index_loaded = 1;
  543. avi->non_interleaved |= guess_ni_flag(s);
  544. if(avi->non_interleaved) {
  545. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  546. clean_index(s);
  547. }
  548. return 0;
  549. }
  550. static int get_stream_idx(int *d){
  551. if( d[0] >= '0' && d[0] <= '9'
  552. && d[1] >= '0' && d[1] <= '9'){
  553. return (d[0] - '0') * 10 + (d[1] - '0');
  554. }else{
  555. return 100; //invalid stream ID
  556. }
  557. }
  558. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  559. {
  560. AVIContext *avi = s->priv_data;
  561. ByteIOContext *pb = s->pb;
  562. int n, d[8], size;
  563. int64_t i, sync;
  564. void* dstr;
  565. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  566. size = dv_get_packet(avi->dv_demux, pkt);
  567. if (size >= 0)
  568. return size;
  569. }
  570. if(avi->non_interleaved){
  571. int best_stream_index = 0;
  572. AVStream *best_st= NULL;
  573. AVIStream *best_ast;
  574. int64_t best_ts= INT64_MAX;
  575. int i;
  576. for(i=0; i<s->nb_streams; i++){
  577. AVStream *st = s->streams[i];
  578. AVIStream *ast = st->priv_data;
  579. int64_t ts= ast->frame_offset;
  580. if(ast->sample_size)
  581. ts /= ast->sample_size;
  582. ts= av_rescale(ts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
  583. // av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  584. if(ts < best_ts && st->nb_index_entries){
  585. best_ts= ts;
  586. best_st= st;
  587. best_stream_index= i;
  588. }
  589. }
  590. if(!best_st)
  591. return -1;
  592. best_ast = best_st->priv_data;
  593. best_ts= av_rescale(best_ts, best_st->time_base.den, AV_TIME_BASE * (int64_t)best_st->time_base.num); //FIXME a little ugly
  594. if(best_ast->remaining)
  595. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  596. else{
  597. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  598. if(i>=0)
  599. best_ast->frame_offset= best_st->index_entries[i].timestamp
  600. * FFMAX(1, best_ast->sample_size);
  601. }
  602. // av_log(NULL, AV_LOG_DEBUG, "%d\n", i);
  603. if(i>=0){
  604. int64_t pos= best_st->index_entries[i].pos;
  605. pos += best_ast->packet_size - best_ast->remaining;
  606. url_fseek(s->pb, pos + 8, SEEK_SET);
  607. // av_log(NULL, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  608. assert(best_ast->remaining <= best_ast->packet_size);
  609. avi->stream_index= best_stream_index;
  610. if(!best_ast->remaining)
  611. best_ast->packet_size=
  612. best_ast->remaining= best_st->index_entries[i].size;
  613. }
  614. }
  615. resync:
  616. if(avi->stream_index >= 0){
  617. AVStream *st= s->streams[ avi->stream_index ];
  618. AVIStream *ast= st->priv_data;
  619. int size;
  620. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  621. size= INT_MAX;
  622. else if(ast->sample_size < 32)
  623. size= 64*ast->sample_size;
  624. else
  625. size= ast->sample_size;
  626. if(size > ast->remaining)
  627. size= ast->remaining;
  628. avi->last_pkt_pos= url_ftell(pb);
  629. av_get_packet(pb, pkt, size);
  630. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  631. ast->has_pal=0;
  632. pkt->size += 4*256;
  633. pkt->data = av_realloc(pkt->data, pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  634. if(pkt->data)
  635. memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
  636. }
  637. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  638. dstr = pkt->destruct;
  639. size = dv_produce_packet(avi->dv_demux, pkt,
  640. pkt->data, pkt->size);
  641. pkt->destruct = dstr;
  642. pkt->flags |= PKT_FLAG_KEY;
  643. } else {
  644. /* XXX: How to handle B-frames in AVI? */
  645. pkt->dts = ast->frame_offset;
  646. // pkt->dts += ast->start;
  647. if(ast->sample_size)
  648. pkt->dts /= ast->sample_size;
  649. //av_log(NULL, AV_LOG_DEBUG, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n", pkt->dts, ast->frame_offset, ast->scale, ast->rate, ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
  650. pkt->stream_index = avi->stream_index;
  651. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  652. AVIndexEntry *e;
  653. int index;
  654. assert(st->index_entries);
  655. index= av_index_search_timestamp(st, pkt->dts, 0);
  656. e= &st->index_entries[index];
  657. if(index >= 0 && e->timestamp == ast->frame_offset){
  658. if (e->flags & AVINDEX_KEYFRAME)
  659. pkt->flags |= PKT_FLAG_KEY;
  660. }
  661. } else {
  662. pkt->flags |= PKT_FLAG_KEY;
  663. }
  664. if(ast->sample_size)
  665. ast->frame_offset += pkt->size;
  666. else
  667. ast->frame_offset++;
  668. }
  669. ast->remaining -= size;
  670. if(!ast->remaining){
  671. avi->stream_index= -1;
  672. ast->packet_size= 0;
  673. }
  674. return size;
  675. }
  676. memset(d, -1, sizeof(int)*8);
  677. for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
  678. int j;
  679. for(j=0; j<7; j++)
  680. d[j]= d[j+1];
  681. d[7]= get_byte(pb);
  682. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  683. n= get_stream_idx(d+2);
  684. //av_log(NULL, AV_LOG_DEBUG, "%X %X %X %X %X %X %X %X %"PRId64" %d %d\n", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  685. if(i + size > avi->fsize || d[0]<0)
  686. continue;
  687. //parse ix##
  688. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  689. //parse JUNK
  690. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  691. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  692. url_fskip(pb, size);
  693. //av_log(NULL, AV_LOG_DEBUG, "SKIP\n");
  694. goto resync;
  695. }
  696. n= get_stream_idx(d);
  697. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  698. continue;
  699. //parse ##dc/##wb
  700. if(n < s->nb_streams){
  701. AVStream *st;
  702. AVIStream *ast;
  703. st = s->streams[n];
  704. ast = st->priv_data;
  705. if(s->nb_streams>=2){
  706. AVStream *st1 = s->streams[1];
  707. AVIStream *ast1= st1->priv_data;
  708. //workaround for broken small-file-bug402.avi
  709. if( d[2] == 'w' && d[3] == 'b'
  710. && n==0
  711. && st ->codec->codec_type == CODEC_TYPE_VIDEO
  712. && st1->codec->codec_type == CODEC_TYPE_AUDIO
  713. && ast->prefix == 'd'*256+'c'
  714. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  715. ){
  716. n=1;
  717. st = st1;
  718. ast = ast1;
  719. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  720. }
  721. }
  722. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  723. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  724. || st->discard >= AVDISCARD_ALL){
  725. if(ast->sample_size) ast->frame_offset += pkt->size;
  726. else ast->frame_offset++;
  727. url_fskip(pb, size);
  728. goto resync;
  729. }
  730. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  731. int k = get_byte(pb);
  732. int last = (k + get_byte(pb) - 1) & 0xFF;
  733. get_le16(pb); //flags
  734. for (; k <= last; k++)
  735. ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
  736. ast->has_pal= 1;
  737. goto resync;
  738. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  739. d[2]*256+d[3] == ast->prefix /*||
  740. (d[2] == 'd' && d[3] == 'c') ||
  741. (d[2] == 'w' && d[3] == 'b')*/) {
  742. //av_log(NULL, AV_LOG_DEBUG, "OK\n");
  743. if(d[2]*256+d[3] == ast->prefix)
  744. ast->prefix_count++;
  745. else{
  746. ast->prefix= d[2]*256+d[3];
  747. ast->prefix_count= 0;
  748. }
  749. avi->stream_index= n;
  750. ast->packet_size= size + 8;
  751. ast->remaining= size;
  752. {
  753. uint64_t pos= url_ftell(pb) - 8;
  754. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  755. av_add_index_entry(st, pos, ast->frame_offset / FFMAX(1, ast->sample_size), size, 0, AVINDEX_KEYFRAME);
  756. }
  757. }
  758. goto resync;
  759. }
  760. }
  761. }
  762. return -1;
  763. }
  764. /* XXX: We make the implicit supposition that the positions are sorted
  765. for each stream. */
  766. static int avi_read_idx1(AVFormatContext *s, int size)
  767. {
  768. AVIContext *avi = s->priv_data;
  769. ByteIOContext *pb = s->pb;
  770. int nb_index_entries, i;
  771. AVStream *st;
  772. AVIStream *ast;
  773. unsigned int index, tag, flags, pos, len;
  774. unsigned last_pos= -1;
  775. nb_index_entries = size / 16;
  776. if (nb_index_entries <= 0)
  777. return -1;
  778. /* Read the entries and sort them in each stream component. */
  779. for(i = 0; i < nb_index_entries; i++) {
  780. tag = get_le32(pb);
  781. flags = get_le32(pb);
  782. pos = get_le32(pb);
  783. len = get_le32(pb);
  784. #if defined(DEBUG_SEEK)
  785. av_log(NULL, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  786. i, tag, flags, pos, len);
  787. #endif
  788. if(i==0 && pos > avi->movi_list)
  789. avi->movi_list= 0; //FIXME better check
  790. pos += avi->movi_list;
  791. index = ((tag & 0xff) - '0') * 10;
  792. index += ((tag >> 8) & 0xff) - '0';
  793. if (index >= s->nb_streams)
  794. continue;
  795. st = s->streams[index];
  796. ast = st->priv_data;
  797. #if defined(DEBUG_SEEK)
  798. av_log(NULL, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  799. #endif
  800. if(last_pos == pos)
  801. avi->non_interleaved= 1;
  802. else
  803. av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  804. if(ast->sample_size)
  805. ast->cum_len += len;
  806. else
  807. ast->cum_len ++;
  808. last_pos= pos;
  809. }
  810. return 0;
  811. }
  812. static int guess_ni_flag(AVFormatContext *s){
  813. int i;
  814. int64_t last_start=0;
  815. int64_t first_end= INT64_MAX;
  816. for(i=0; i<s->nb_streams; i++){
  817. AVStream *st = s->streams[i];
  818. int n= st->nb_index_entries;
  819. if(n <= 0)
  820. continue;
  821. if(st->index_entries[0].pos > last_start)
  822. last_start= st->index_entries[0].pos;
  823. if(st->index_entries[n-1].pos < first_end)
  824. first_end= st->index_entries[n-1].pos;
  825. }
  826. return last_start > first_end;
  827. }
  828. static int avi_load_index(AVFormatContext *s)
  829. {
  830. AVIContext *avi = s->priv_data;
  831. ByteIOContext *pb = s->pb;
  832. uint32_t tag, size;
  833. int64_t pos= url_ftell(pb);
  834. url_fseek(pb, avi->movi_end, SEEK_SET);
  835. #ifdef DEBUG_SEEK
  836. printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
  837. #endif
  838. for(;;) {
  839. if (url_feof(pb))
  840. break;
  841. tag = get_le32(pb);
  842. size = get_le32(pb);
  843. #ifdef DEBUG_SEEK
  844. printf("tag=%c%c%c%c size=0x%x\n",
  845. tag & 0xff,
  846. (tag >> 8) & 0xff,
  847. (tag >> 16) & 0xff,
  848. (tag >> 24) & 0xff,
  849. size);
  850. #endif
  851. switch(tag) {
  852. case MKTAG('i', 'd', 'x', '1'):
  853. if (avi_read_idx1(s, size) < 0)
  854. goto skip;
  855. else
  856. goto the_end;
  857. break;
  858. default:
  859. skip:
  860. size += (size & 1);
  861. url_fskip(pb, size);
  862. break;
  863. }
  864. }
  865. the_end:
  866. url_fseek(pb, pos, SEEK_SET);
  867. return 0;
  868. }
  869. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  870. {
  871. AVIContext *avi = s->priv_data;
  872. AVStream *st;
  873. int i, index;
  874. int64_t pos;
  875. if (!avi->index_loaded) {
  876. /* we only load the index on demand */
  877. avi_load_index(s);
  878. avi->index_loaded = 1;
  879. }
  880. assert(stream_index>= 0);
  881. st = s->streams[stream_index];
  882. index= av_index_search_timestamp(st, timestamp, flags);
  883. if(index<0)
  884. return -1;
  885. /* find the position */
  886. pos = st->index_entries[index].pos;
  887. timestamp = st->index_entries[index].timestamp;
  888. // av_log(NULL, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  889. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  890. /* One and only one real stream for DV in AVI, and it has video */
  891. /* offsets. Calling with other stream indexes should have failed */
  892. /* the av_index_search_timestamp call above. */
  893. assert(stream_index == 0);
  894. /* Feed the DV video stream version of the timestamp to the */
  895. /* DV demux so it can synthesize correct timestamps. */
  896. dv_offset_reset(avi->dv_demux, timestamp);
  897. url_fseek(s->pb, pos, SEEK_SET);
  898. avi->stream_index= -1;
  899. return 0;
  900. }
  901. for(i = 0; i < s->nb_streams; i++) {
  902. AVStream *st2 = s->streams[i];
  903. AVIStream *ast2 = st2->priv_data;
  904. ast2->packet_size=
  905. ast2->remaining= 0;
  906. if (st2->nb_index_entries <= 0)
  907. continue;
  908. // assert(st2->codec->block_align);
  909. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  910. index = av_index_search_timestamp(
  911. st2,
  912. av_rescale(timestamp, st2->time_base.den*(int64_t)st->time_base.num, st->time_base.den * (int64_t)st2->time_base.num),
  913. flags | AVSEEK_FLAG_BACKWARD);
  914. if(index<0)
  915. index=0;
  916. if(!avi->non_interleaved){
  917. while(index>0 && st2->index_entries[index].pos > pos)
  918. index--;
  919. while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
  920. index++;
  921. }
  922. // av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
  923. /* extract the current frame number */
  924. ast2->frame_offset = st2->index_entries[index].timestamp;
  925. if(ast2->sample_size)
  926. ast2->frame_offset *=ast2->sample_size;
  927. }
  928. /* do the seek */
  929. url_fseek(s->pb, pos, SEEK_SET);
  930. avi->stream_index= -1;
  931. return 0;
  932. }
  933. static int avi_read_close(AVFormatContext *s)
  934. {
  935. int i;
  936. AVIContext *avi = s->priv_data;
  937. for(i=0;i<s->nb_streams;i++) {
  938. AVStream *st = s->streams[i];
  939. av_free(st->codec->palctrl);
  940. }
  941. if (avi->dv_demux)
  942. av_free(avi->dv_demux);
  943. return 0;
  944. }
  945. static int avi_probe(AVProbeData *p)
  946. {
  947. int i;
  948. /* check file header */
  949. for(i=0; avi_headers[i][0]; i++)
  950. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  951. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  952. return AVPROBE_SCORE_MAX;
  953. return 0;
  954. }
  955. AVInputFormat avi_demuxer = {
  956. "avi",
  957. NULL_IF_CONFIG_SMALL("AVI format"),
  958. sizeof(AVIContext),
  959. avi_probe,
  960. avi_read_header,
  961. avi_read_packet,
  962. avi_read_close,
  963. avi_read_seek,
  964. };