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.

1615 lines
55KB

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