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.

1626 lines
56KB

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