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.

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