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.

1100 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. else
  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(ByteIOContext *pb, char *buf, int maxlen, unsigned int size)
  186. {
  187. int64_t i = url_ftell(pb);
  188. size += (size & 1);
  189. get_strz(pb, buf, maxlen);
  190. url_fseek(pb, i+size, SEEK_SET);
  191. return 0;
  192. }
  193. static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
  194. {
  195. AVIContext *avi = s->priv_data;
  196. ByteIOContext *pb = s->pb;
  197. uint32_t tag, tag1, handler;
  198. int codec_type, stream_index, frame_period, bit_rate;
  199. unsigned int size, nb_frames;
  200. int i;
  201. AVStream *st;
  202. AVIStream *ast = NULL;
  203. char str_track[4];
  204. int avih_width=0, avih_height=0;
  205. int amv_file_format=0;
  206. avi->stream_index= -1;
  207. if (get_riff(avi, pb) < 0)
  208. return -1;
  209. avi->fsize = url_fsize(pb);
  210. if(avi->fsize<=0)
  211. avi->fsize= avi->riff_end;
  212. /* first list tag */
  213. stream_index = -1;
  214. codec_type = -1;
  215. frame_period = 0;
  216. for(;;) {
  217. if (url_feof(pb))
  218. goto fail;
  219. tag = get_le32(pb);
  220. size = get_le32(pb);
  221. #ifdef DEBUG
  222. print_tag("tag", tag, size);
  223. #endif
  224. switch(tag) {
  225. case MKTAG('L', 'I', 'S', 'T'):
  226. /* Ignored, except at start of video packets. */
  227. tag1 = get_le32(pb);
  228. #ifdef DEBUG
  229. print_tag("list", tag1, 0);
  230. #endif
  231. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  232. avi->movi_list = url_ftell(pb) - 4;
  233. if(size) avi->movi_end = avi->movi_list + size + (size & 1);
  234. else avi->movi_end = url_fsize(pb);
  235. #ifdef DEBUG
  236. printf("movi end=%"PRIx64"\n", avi->movi_end);
  237. #endif
  238. goto end_of_header;
  239. }
  240. break;
  241. case MKTAG('d', 'm', 'l', 'h'):
  242. avi->is_odml = 1;
  243. url_fskip(pb, size + (size & 1));
  244. break;
  245. case MKTAG('a', 'm', 'v', 'h'):
  246. amv_file_format=1;
  247. case MKTAG('a', 'v', 'i', 'h'):
  248. /* AVI header */
  249. /* using frame_period is bad idea */
  250. frame_period = get_le32(pb);
  251. bit_rate = get_le32(pb) * 8;
  252. get_le32(pb);
  253. avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
  254. url_fskip(pb, 2 * 4);
  255. get_le32(pb);
  256. get_le32(pb);
  257. avih_width=get_le32(pb);
  258. avih_height=get_le32(pb);
  259. url_fskip(pb, size - 10 * 4);
  260. break;
  261. case MKTAG('s', 't', 'r', 'h'):
  262. /* stream header */
  263. tag1 = get_le32(pb);
  264. handler = get_le32(pb); /* codec tag */
  265. if(tag1 == MKTAG('p', 'a', 'd', 's')){
  266. url_fskip(pb, size - 8);
  267. break;
  268. }else{
  269. stream_index++;
  270. st = av_new_stream(s, stream_index);
  271. if (!st)
  272. goto fail;
  273. ast = av_mallocz(sizeof(AVIStream));
  274. if (!ast)
  275. goto fail;
  276. st->priv_data = ast;
  277. }
  278. if(amv_file_format)
  279. tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
  280. #ifdef DEBUG
  281. print_tag("strh", tag1, -1);
  282. #endif
  283. if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
  284. int64_t dv_dur;
  285. /*
  286. * After some consideration -- I don't think we
  287. * have to support anything but DV in type1 AVIs.
  288. */
  289. if (s->nb_streams != 1)
  290. goto fail;
  291. if (handler != MKTAG('d', 'v', 's', 'd') &&
  292. handler != MKTAG('d', 'v', 'h', 'd') &&
  293. handler != MKTAG('d', 'v', 's', 'l'))
  294. goto fail;
  295. ast = s->streams[0]->priv_data;
  296. av_freep(&s->streams[0]->codec->extradata);
  297. av_freep(&s->streams[0]);
  298. s->nb_streams = 0;
  299. if (ENABLE_DV_DEMUXER) {
  300. avi->dv_demux = dv_init_demux(s);
  301. if (!avi->dv_demux)
  302. goto fail;
  303. }
  304. s->streams[0]->priv_data = ast;
  305. url_fskip(pb, 3 * 4);
  306. ast->scale = get_le32(pb);
  307. ast->rate = get_le32(pb);
  308. url_fskip(pb, 4); /* start time */
  309. dv_dur = get_le32(pb);
  310. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  311. dv_dur *= AV_TIME_BASE;
  312. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  313. }
  314. /*
  315. * else, leave duration alone; timing estimation in utils.c
  316. * will make a guess based on bitrate.
  317. */
  318. stream_index = s->nb_streams - 1;
  319. url_fskip(pb, size - 9*4);
  320. break;
  321. }
  322. assert(stream_index < s->nb_streams);
  323. st->codec->stream_codec_tag= handler;
  324. get_le32(pb); /* flags */
  325. get_le16(pb); /* priority */
  326. get_le16(pb); /* language */
  327. get_le32(pb); /* initial frame */
  328. ast->scale = get_le32(pb);
  329. ast->rate = get_le32(pb);
  330. if(!(ast->scale && ast->rate)){
  331. 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);
  332. if(frame_period){
  333. ast->rate = 1000000;
  334. ast->scale = frame_period;
  335. }else{
  336. ast->rate = 25;
  337. ast->scale = 1;
  338. }
  339. }
  340. av_set_pts_info(st, 64, ast->scale, ast->rate);
  341. ast->cum_len=get_le32(pb); /* start */
  342. nb_frames = get_le32(pb);
  343. st->start_time = 0;
  344. st->duration = nb_frames;
  345. get_le32(pb); /* buffer size */
  346. get_le32(pb); /* quality */
  347. ast->sample_size = get_le32(pb); /* sample ssize */
  348. ast->cum_len *= FFMAX(1, ast->sample_size);
  349. // av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
  350. switch(tag1) {
  351. case MKTAG('v', 'i', 'd', 's'):
  352. codec_type = CODEC_TYPE_VIDEO;
  353. ast->sample_size = 0;
  354. break;
  355. case MKTAG('a', 'u', 'd', 's'):
  356. codec_type = CODEC_TYPE_AUDIO;
  357. break;
  358. case MKTAG('t', 'x', 't', 's'):
  359. //FIXME
  360. codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ? FIXME
  361. break;
  362. case MKTAG('d', 'a', 't', 's'):
  363. codec_type = CODEC_TYPE_DATA;
  364. break;
  365. default:
  366. av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
  367. goto fail;
  368. }
  369. ast->frame_offset= ast->cum_len;
  370. url_fskip(pb, size - 12 * 4);
  371. break;
  372. case MKTAG('s', 't', 'r', 'f'):
  373. /* stream header */
  374. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  375. url_fskip(pb, size);
  376. } else {
  377. st = s->streams[stream_index];
  378. switch(codec_type) {
  379. case CODEC_TYPE_VIDEO:
  380. if(amv_file_format){
  381. st->codec->width=avih_width;
  382. st->codec->height=avih_height;
  383. st->codec->codec_type = CODEC_TYPE_VIDEO;
  384. st->codec->codec_id = CODEC_ID_AMV;
  385. url_fskip(pb, size);
  386. break;
  387. }
  388. get_le32(pb); /* size */
  389. st->codec->width = get_le32(pb);
  390. st->codec->height = get_le32(pb);
  391. get_le16(pb); /* panes */
  392. st->codec->bits_per_coded_sample= get_le16(pb); /* depth */
  393. tag1 = get_le32(pb);
  394. get_le32(pb); /* ImageSize */
  395. get_le32(pb); /* XPelsPerMeter */
  396. get_le32(pb); /* YPelsPerMeter */
  397. get_le32(pb); /* ClrUsed */
  398. get_le32(pb); /* ClrImportant */
  399. if (tag1 == MKTAG('D', 'X', 'S', 'B')) {
  400. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  401. st->codec->codec_tag = tag1;
  402. st->codec->codec_id = CODEC_ID_XSUB;
  403. break;
  404. }
  405. if(size > 10*4 && size<(1<<30)){
  406. st->codec->extradata_size= size - 10*4;
  407. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  408. get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
  409. }
  410. if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  411. get_byte(pb);
  412. /* Extract palette from extradata if bpp <= 8. */
  413. /* This code assumes that extradata contains only palette. */
  414. /* This is true for all paletted codecs implemented in FFmpeg. */
  415. if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
  416. st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
  417. #ifdef WORDS_BIGENDIAN
  418. for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
  419. st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
  420. #else
  421. memcpy(st->codec->palctrl->palette, st->codec->extradata,
  422. FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
  423. #endif
  424. st->codec->palctrl->palette_changed = 1;
  425. }
  426. #ifdef DEBUG
  427. print_tag("video", tag1, 0);
  428. #endif
  429. st->codec->codec_type = CODEC_TYPE_VIDEO;
  430. st->codec->codec_tag = tag1;
  431. st->codec->codec_id = codec_get_id(codec_bmp_tags, tag1);
  432. st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
  433. // url_fskip(pb, size - 5 * 4);
  434. break;
  435. case CODEC_TYPE_AUDIO:
  436. get_wav_header(pb, st->codec, size);
  437. if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
  438. av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
  439. ast->sample_size= st->codec->block_align;
  440. }
  441. if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  442. url_fskip(pb, 1);
  443. /* Force parsing as several audio frames can be in
  444. * one packet and timestamps refer to packet start. */
  445. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  446. /* ADTS header is in extradata, AAC without header must be
  447. * stored as exact frames. Parser not needed and it will
  448. * fail. */
  449. if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
  450. st->need_parsing = AVSTREAM_PARSE_NONE;
  451. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  452. * audio in the header but have Axan as stream_code_tag. */
  453. if (st->codec->stream_codec_tag == ff_get_fourcc("Axan")){
  454. st->codec->codec_id = CODEC_ID_XAN_DPCM;
  455. st->codec->codec_tag = 0;
  456. }
  457. if (amv_file_format)
  458. st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
  459. break;
  460. default:
  461. st->codec->codec_type = CODEC_TYPE_DATA;
  462. st->codec->codec_id= CODEC_ID_NONE;
  463. st->codec->codec_tag= 0;
  464. url_fskip(pb, size);
  465. break;
  466. }
  467. }
  468. break;
  469. case MKTAG('i', 'n', 'd', 'x'):
  470. i= url_ftell(pb);
  471. if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
  472. read_braindead_odml_indx(s, 0);
  473. }
  474. url_fseek(pb, i+size, SEEK_SET);
  475. break;
  476. case MKTAG('v', 'p', 'r', 'p'):
  477. if(stream_index < (unsigned)s->nb_streams && size > 9*4){
  478. AVRational active, active_aspect;
  479. st = s->streams[stream_index];
  480. get_le32(pb);
  481. get_le32(pb);
  482. get_le32(pb);
  483. get_le32(pb);
  484. get_le32(pb);
  485. active_aspect.den= get_le16(pb);
  486. active_aspect.num= get_le16(pb);
  487. active.num = get_le32(pb);
  488. active.den = get_le32(pb);
  489. get_le32(pb); //nbFieldsPerFrame
  490. if(active_aspect.num && active_aspect.den && active.num && active.den){
  491. st->sample_aspect_ratio= av_div_q(active_aspect, active);
  492. //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
  493. }
  494. size -= 9*4;
  495. }
  496. url_fseek(pb, size, SEEK_CUR);
  497. break;
  498. case MKTAG('I', 'N', 'A', 'M'):
  499. avi_read_tag(pb, s->title, sizeof(s->title), size);
  500. break;
  501. case MKTAG('I', 'A', 'R', 'T'):
  502. avi_read_tag(pb, s->author, sizeof(s->author), size);
  503. break;
  504. case MKTAG('I', 'C', 'O', 'P'):
  505. avi_read_tag(pb, s->copyright, sizeof(s->copyright), size);
  506. break;
  507. case MKTAG('I', 'C', 'M', 'T'):
  508. avi_read_tag(pb, s->comment, sizeof(s->comment), size);
  509. break;
  510. case MKTAG('I', 'G', 'N', 'R'):
  511. avi_read_tag(pb, s->genre, sizeof(s->genre), size);
  512. break;
  513. case MKTAG('I', 'P', 'R', 'D'):
  514. avi_read_tag(pb, s->album, sizeof(s->album), size);
  515. break;
  516. case MKTAG('I', 'P', 'R', 'T'):
  517. avi_read_tag(pb, str_track, sizeof(str_track), size);
  518. sscanf(str_track, "%d", &s->track);
  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. // av_log(NULL, AV_LOG_DEBUG, "%d\n", i);
  599. if(i>=0){
  600. int64_t pos= best_st->index_entries[i].pos;
  601. pos += best_ast->packet_size - best_ast->remaining;
  602. url_fseek(s->pb, pos + 8, SEEK_SET);
  603. // av_log(NULL, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  604. assert(best_ast->remaining <= best_ast->packet_size);
  605. avi->stream_index= best_stream_index;
  606. if(!best_ast->remaining)
  607. best_ast->packet_size=
  608. best_ast->remaining= best_st->index_entries[i].size;
  609. }
  610. }
  611. resync:
  612. if(avi->stream_index >= 0){
  613. AVStream *st= s->streams[ avi->stream_index ];
  614. AVIStream *ast= st->priv_data;
  615. int size;
  616. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  617. size= INT_MAX;
  618. else if(ast->sample_size < 32)
  619. size= 64*ast->sample_size;
  620. else
  621. size= ast->sample_size;
  622. if(size > ast->remaining)
  623. size= ast->remaining;
  624. avi->last_pkt_pos= url_ftell(pb);
  625. av_get_packet(pb, pkt, size);
  626. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  627. ast->has_pal=0;
  628. pkt->size += 4*256;
  629. pkt->data = av_realloc(pkt->data, pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
  630. if(pkt->data)
  631. memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
  632. }
  633. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  634. dstr = pkt->destruct;
  635. size = dv_produce_packet(avi->dv_demux, pkt,
  636. pkt->data, pkt->size);
  637. pkt->destruct = dstr;
  638. pkt->flags |= PKT_FLAG_KEY;
  639. } else {
  640. /* XXX: How to handle B-frames in AVI? */
  641. pkt->dts = ast->frame_offset;
  642. // pkt->dts += ast->start;
  643. if(ast->sample_size)
  644. pkt->dts /= ast->sample_size;
  645. //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);
  646. pkt->stream_index = avi->stream_index;
  647. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  648. AVIndexEntry *e;
  649. int index;
  650. assert(st->index_entries);
  651. index= av_index_search_timestamp(st, pkt->dts, 0);
  652. e= &st->index_entries[index];
  653. if(index >= 0 && e->timestamp == ast->frame_offset){
  654. if (e->flags & AVINDEX_KEYFRAME)
  655. pkt->flags |= PKT_FLAG_KEY;
  656. }
  657. } else {
  658. pkt->flags |= PKT_FLAG_KEY;
  659. }
  660. if(ast->sample_size)
  661. ast->frame_offset += pkt->size;
  662. else
  663. ast->frame_offset++;
  664. }
  665. ast->remaining -= size;
  666. if(!ast->remaining){
  667. avi->stream_index= -1;
  668. ast->packet_size= 0;
  669. }
  670. return size;
  671. }
  672. memset(d, -1, sizeof(int)*8);
  673. for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
  674. int j;
  675. for(j=0; j<7; j++)
  676. d[j]= d[j+1];
  677. d[7]= get_byte(pb);
  678. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  679. n= get_stream_idx(d+2);
  680. //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);
  681. if(i + size > avi->fsize || d[0]<0)
  682. continue;
  683. //parse ix##
  684. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  685. //parse JUNK
  686. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  687. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  688. url_fskip(pb, size);
  689. //av_log(NULL, AV_LOG_DEBUG, "SKIP\n");
  690. goto resync;
  691. }
  692. n= get_stream_idx(d);
  693. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  694. continue;
  695. //parse ##dc/##wb
  696. if(n < s->nb_streams){
  697. AVStream *st;
  698. AVIStream *ast;
  699. st = s->streams[n];
  700. ast = st->priv_data;
  701. if(s->nb_streams>=2){
  702. AVStream *st1 = s->streams[1];
  703. AVIStream *ast1= st1->priv_data;
  704. //workaround for broken small-file-bug402.avi
  705. if( d[2] == 'w' && d[3] == 'b'
  706. && n==0
  707. && st ->codec->codec_type == CODEC_TYPE_VIDEO
  708. && st1->codec->codec_type == CODEC_TYPE_AUDIO
  709. && ast->prefix == 'd'*256+'c'
  710. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  711. ){
  712. n=1;
  713. st = st1;
  714. ast = ast1;
  715. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  716. }
  717. }
  718. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  719. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  720. || st->discard >= AVDISCARD_ALL){
  721. if(ast->sample_size) ast->frame_offset += pkt->size;
  722. else ast->frame_offset++;
  723. url_fskip(pb, size);
  724. goto resync;
  725. }
  726. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  727. int k = get_byte(pb);
  728. int last = (k + get_byte(pb) - 1) & 0xFF;
  729. get_le16(pb); //flags
  730. for (; k <= last; k++)
  731. ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
  732. ast->has_pal= 1;
  733. goto resync;
  734. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  735. d[2]*256+d[3] == ast->prefix /*||
  736. (d[2] == 'd' && d[3] == 'c') ||
  737. (d[2] == 'w' && d[3] == 'b')*/) {
  738. //av_log(NULL, AV_LOG_DEBUG, "OK\n");
  739. if(d[2]*256+d[3] == ast->prefix)
  740. ast->prefix_count++;
  741. else{
  742. ast->prefix= d[2]*256+d[3];
  743. ast->prefix_count= 0;
  744. }
  745. avi->stream_index= n;
  746. ast->packet_size= size + 8;
  747. ast->remaining= size;
  748. {
  749. uint64_t pos= url_ftell(pb) - 8;
  750. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  751. av_add_index_entry(st, pos, ast->frame_offset / FFMAX(1, ast->sample_size), size, 0, AVINDEX_KEYFRAME);
  752. }
  753. }
  754. goto resync;
  755. }
  756. }
  757. }
  758. return -1;
  759. }
  760. /* XXX: We make the implicit supposition that the positions are sorted
  761. for each stream. */
  762. static int avi_read_idx1(AVFormatContext *s, int size)
  763. {
  764. AVIContext *avi = s->priv_data;
  765. ByteIOContext *pb = s->pb;
  766. int nb_index_entries, i;
  767. AVStream *st;
  768. AVIStream *ast;
  769. unsigned int index, tag, flags, pos, len;
  770. unsigned last_pos= -1;
  771. nb_index_entries = size / 16;
  772. if (nb_index_entries <= 0)
  773. return -1;
  774. /* Read the entries and sort them in each stream component. */
  775. for(i = 0; i < nb_index_entries; i++) {
  776. tag = get_le32(pb);
  777. flags = get_le32(pb);
  778. pos = get_le32(pb);
  779. len = get_le32(pb);
  780. #if defined(DEBUG_SEEK)
  781. av_log(NULL, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  782. i, tag, flags, pos, len);
  783. #endif
  784. if(i==0 && pos > avi->movi_list)
  785. avi->movi_list= 0; //FIXME better check
  786. pos += avi->movi_list;
  787. index = ((tag & 0xff) - '0') * 10;
  788. index += ((tag >> 8) & 0xff) - '0';
  789. if (index >= s->nb_streams)
  790. continue;
  791. st = s->streams[index];
  792. ast = st->priv_data;
  793. #if defined(DEBUG_SEEK)
  794. av_log(NULL, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  795. #endif
  796. if(last_pos == pos)
  797. avi->non_interleaved= 1;
  798. else
  799. av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  800. if(ast->sample_size)
  801. ast->cum_len += len;
  802. else
  803. ast->cum_len ++;
  804. last_pos= pos;
  805. }
  806. return 0;
  807. }
  808. static int guess_ni_flag(AVFormatContext *s){
  809. int i;
  810. int64_t last_start=0;
  811. int64_t first_end= INT64_MAX;
  812. for(i=0; i<s->nb_streams; i++){
  813. AVStream *st = s->streams[i];
  814. int n= st->nb_index_entries;
  815. if(n <= 0)
  816. continue;
  817. if(st->index_entries[0].pos > last_start)
  818. last_start= st->index_entries[0].pos;
  819. if(st->index_entries[n-1].pos < first_end)
  820. first_end= st->index_entries[n-1].pos;
  821. }
  822. return last_start > first_end;
  823. }
  824. static int avi_load_index(AVFormatContext *s)
  825. {
  826. AVIContext *avi = s->priv_data;
  827. ByteIOContext *pb = s->pb;
  828. uint32_t tag, size;
  829. int64_t pos= url_ftell(pb);
  830. url_fseek(pb, avi->movi_end, SEEK_SET);
  831. #ifdef DEBUG_SEEK
  832. printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
  833. #endif
  834. for(;;) {
  835. if (url_feof(pb))
  836. break;
  837. tag = get_le32(pb);
  838. size = get_le32(pb);
  839. #ifdef DEBUG_SEEK
  840. printf("tag=%c%c%c%c size=0x%x\n",
  841. tag & 0xff,
  842. (tag >> 8) & 0xff,
  843. (tag >> 16) & 0xff,
  844. (tag >> 24) & 0xff,
  845. size);
  846. #endif
  847. switch(tag) {
  848. case MKTAG('i', 'd', 'x', '1'):
  849. if (avi_read_idx1(s, size) < 0)
  850. goto skip;
  851. else
  852. goto the_end;
  853. break;
  854. default:
  855. skip:
  856. size += (size & 1);
  857. url_fskip(pb, size);
  858. break;
  859. }
  860. }
  861. the_end:
  862. url_fseek(pb, pos, SEEK_SET);
  863. return 0;
  864. }
  865. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  866. {
  867. AVIContext *avi = s->priv_data;
  868. AVStream *st;
  869. int i, index;
  870. int64_t pos;
  871. if (!avi->index_loaded) {
  872. /* we only load the index on demand */
  873. avi_load_index(s);
  874. avi->index_loaded = 1;
  875. }
  876. assert(stream_index>= 0);
  877. st = s->streams[stream_index];
  878. index= av_index_search_timestamp(st, timestamp, flags);
  879. if(index<0)
  880. return -1;
  881. /* find the position */
  882. pos = st->index_entries[index].pos;
  883. timestamp = st->index_entries[index].timestamp;
  884. // av_log(NULL, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  885. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  886. /* One and only one real stream for DV in AVI, and it has video */
  887. /* offsets. Calling with other stream indexes should have failed */
  888. /* the av_index_search_timestamp call above. */
  889. assert(stream_index == 0);
  890. /* Feed the DV video stream version of the timestamp to the */
  891. /* DV demux so it can synthesize correct timestamps. */
  892. dv_offset_reset(avi->dv_demux, timestamp);
  893. url_fseek(s->pb, pos, SEEK_SET);
  894. avi->stream_index= -1;
  895. return 0;
  896. }
  897. for(i = 0; i < s->nb_streams; i++) {
  898. AVStream *st2 = s->streams[i];
  899. AVIStream *ast2 = st2->priv_data;
  900. ast2->packet_size=
  901. ast2->remaining= 0;
  902. if (st2->nb_index_entries <= 0)
  903. continue;
  904. // assert(st2->codec->block_align);
  905. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  906. index = av_index_search_timestamp(
  907. st2,
  908. av_rescale(timestamp, st2->time_base.den*(int64_t)st->time_base.num, st->time_base.den * (int64_t)st2->time_base.num),
  909. flags | AVSEEK_FLAG_BACKWARD);
  910. if(index<0)
  911. index=0;
  912. if(!avi->non_interleaved){
  913. while(index>0 && st2->index_entries[index].pos > pos)
  914. index--;
  915. while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
  916. index++;
  917. }
  918. // av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
  919. /* extract the current frame number */
  920. ast2->frame_offset = st2->index_entries[index].timestamp;
  921. if(ast2->sample_size)
  922. ast2->frame_offset *=ast2->sample_size;
  923. }
  924. /* do the seek */
  925. url_fseek(s->pb, pos, SEEK_SET);
  926. avi->stream_index= -1;
  927. return 0;
  928. }
  929. static int avi_read_close(AVFormatContext *s)
  930. {
  931. int i;
  932. AVIContext *avi = s->priv_data;
  933. for(i=0;i<s->nb_streams;i++) {
  934. AVStream *st = s->streams[i];
  935. av_free(st->codec->palctrl);
  936. }
  937. if (avi->dv_demux)
  938. av_free(avi->dv_demux);
  939. return 0;
  940. }
  941. static int avi_probe(AVProbeData *p)
  942. {
  943. int i;
  944. /* check file header */
  945. for(i=0; avi_headers[i][0]; i++)
  946. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  947. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  948. return AVPROBE_SCORE_MAX;
  949. return 0;
  950. }
  951. AVInputFormat avi_demuxer = {
  952. "avi",
  953. NULL_IF_CONFIG_SMALL("AVI format"),
  954. sizeof(AVIContext),
  955. avi_probe,
  956. avi_read_header,
  957. avi_read_packet,
  958. avi_read_close,
  959. avi_read_seek,
  960. };