reversed the order of r,g,b in the 16 bit conversion.
[swftools.git] / avi2swf / videoreader_vfw.cc
1 /* videoreader_vfw.cc
2    Read avi files using Video For Windows (vfw).
3
4    Part of the swftools package.
5    
6    Copyright (c) 2004 Matthias Kramm <kramm@quiss.org>
7  
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
21
22 #include "videoreader.h"
23 #ifdef WIN32
24 #include <windows.h>
25 #include <vfw.h>
26 #include <stdlib.h>
27 #include <stdio.h>
28
29 typedef struct _videoreader_vfw_internal { 
30     //video:
31     PAVISTREAM vs;
32     //audio:
33     PAVISTREAM as;
34
35     PGETFRAME getframe;
36     IAVIFile* avifile;
37     BITMAPINFOHEADER bitmap;
38     WAVEFORMATEX waveformat;
39
40     int video_pos;
41     int video_end;
42
43     int audio_pos;
44     int audio_end;
45
46     float fps;
47     int width,height;
48
49     int samplerate;
50     int channels;
51
52     int flip;
53 } videoreader_vfw_internal_t;
54
55 static int avifile_initialized = 0;
56 static int verbose;
57
58 #define _TRACE_ {printf("vfw: %s: %d (%s)\n",__FILE__,__LINE__,__func__);fflush(stdout);}
59
60 static bool videoreader_vfw_eof(videoreader_t* vr)
61 {
62     videoreader_vfw_internal_t* i = (videoreader_vfw_internal_t*)vr->internal;
63     return (i->video_pos >= i->video_end);
64 }
65
66 static int bitmap_to_rgba(BITMAPINFOHEADER*bi, void*buffer, const int dest_width, const int dest_height, int flip)
67 {
68     UCHAR*data = (UCHAR*)(bi+1); // actual bitmap data starts after the header
69
70     if(bi->biPlanes!=1 || bi->biCompression!=0 || bi->biBitCount%4!=0) {
71         /* unsupported format */
72         fprintf(stderr, "bitmap_to_rgba: unsupported format: biPlanes=%d, biCompression=%d biBitCount=%d\n",
73                 bi->biPlanes, bi->biCompression, bi->biBitCount);
74         return 0;
75     }
76     
77     ULONG*dest = (ULONG*)buffer;
78
79     int width = bi->biWidth;
80     int height = bi->biHeight;
81     if(dest_width != width || dest_height != height) {
82         /* TODO: size conversion */
83         fprintf(stderr, "size mismatch: %dx%d != %dx%d\n", width, height, dest_width, dest_height);
84         return 0;
85     }
86
87     /* convert the various image types to RGBA-
88        TODO: is there some way to let the Windows API do this? */
89     int bytesperpixel = ((bi->biWidth*bi->biBitCount)+7)&~7;
90     int linex = ((bytesperpixel/8)+3)&~3;
91     memset(dest, 255, dest_width*dest_height*4);//pre-fill alpha channel
92
93     const int starty = flip? 0 : dest_height-1;
94     const int endy   = flip? dest_height : -1;
95     const int yinc   = flip? 1 : -1;
96
97     if(verbose) {
98         printf("vfw: Convering scanlines %d to %d from bpp %d, %d stepping, flip=%d\n", starty, endy, bi->biBitCount, yinc, flip);
99     }
100
101     if(bi->biBitCount==1) {
102         UCHAR*img = data;
103         int y;
104         for(y=starty;y!=endy;y+=yinc) {
105             UCHAR*line = &img[linex*y];
106             int x;
107             for(x=0;x<dest_width;x++) {
108                 *dest++ = 255*((line[x/8]>>(x&7))&1);
109             }
110         }
111     } else if(bi->biBitCount==4) {
112         UCHAR*img = &data[bi->biClrUsed*4];
113         UCHAR*pal = data;
114         int y;
115         for(y=starty;y!=endy;y+=yinc) {
116             UCHAR*line = &img[linex*y];
117             int x;
118             for(x=0;x<dest_width/2;x++) {
119                 *dest++ = 255|pal[(line[0]>>4)<<2|0]<<8|pal[(line[0]>>4)<<2|1]<<16|pal[(line[0]>>4)<<2|2]<<24;
120                 *dest++ = 255|pal[(line[0]&0x0f)<<2|0]<<8|pal[(line[0]&0x0f)<<2|1]<<16|pal[(line[0]&0x0f)<<2|2]<<24;
121                 line++;
122             }
123         }
124     } else if(bi->biBitCount==8) {
125         UCHAR*img = &data[bi->biClrUsed*4];
126         UCHAR*pal = data;
127         int y;
128         for(y=starty;y!=endy;y+=yinc) {
129             UCHAR*line = &img[linex*y];
130             int x;
131             for(x=0;x<dest_width;x++) {
132                 *dest++ = 255|pal[line[0]*4+2]<<8|pal[line[0]*4+1]<<16|pal[line[0]*4+0]<<24;
133                 line++;
134             }
135         }
136     } else if(bi->biBitCount==16) {
137         UCHAR*img = data;
138         int y;
139         for(y=starty;y!=endy;y+=yinc) {
140             UCHAR*line = &img[linex*y];
141             int x;
142             for(x=0;x<dest_width;x++) {
143                 USHORT c = line[0]|line[1]<<8;
144                 *dest++ = 255|(c&0x1f)<<(24+3)|(c>>5&0x1f)<<(16+3)|(c>>10&0x1f)<<(8+3);
145                 line+=2;
146             }
147         }
148     } else if(bi->biBitCount==24) {
149         UCHAR*img = data;
150         int y;
151         for(y=starty;y!=endy;y+=yinc) {
152             UCHAR*line = &img[linex*y];
153             int x;
154             for(x=0;x<dest_width;x++) {
155                 *dest++ = 255|line[2]<<8|line[1]<<16|line[0]<<24;
156                 line+=3;
157             }
158         }
159     } else if(bi->biBitCount==32) {
160         UCHAR*img = data;
161         int y;
162         for(y=starty;y!=endy;y+=yinc) {
163             UCHAR*line = &img[linex*y];
164             int x;
165             for(x=0;x<dest_width;x++) {
166                 *dest++ = 255|line[0]<<8|line[1]<<16|line[2]<<24;
167                 line+=4;
168             }
169         }
170     } else {
171         fprintf(stderr, "Unsupported format: bitcount=%d\n", bi->biBitCount);
172         return 0;
173     }
174     return 1;
175 }
176
177 static int videoreader_vfw_getimage(videoreader_t* vr, void*buffer)
178 {
179     videoreader_vfw_internal_t* i = (videoreader_vfw_internal_t*)vr->internal;
180
181     if(videoreader_vfw_eof(vr))
182         return 0;
183
184     LPBITMAPINFOHEADER bi;
185     bi = (LPBITMAPINFOHEADER)AVIStreamGetFrame(i->getframe, i->video_pos);
186         
187     i->video_pos++;
188     vr->frame++;
189
190     if(!bi) {
191         fprintf(stderr, "AVIStreamGetFrame failed\n");
192         return 0;
193     }
194     
195     if(!bitmap_to_rgba(bi, buffer, i->width, i->height, i->flip)) {
196         fprintf(stderr, "couldn't convert bitmap to RGBA.\n");
197         return 0;
198     }
199     return i->width*i->height*4;
200 }
201
202 static int readAudioBlock(videoreader_vfw_internal_t* i, void*buf, int len)
203 {
204     LONG bytes;
205     LONG samples;
206     AVIStreamRead(i->as, i->audio_pos, len/(2*i->waveformat.nChannels), buf, len, &bytes, &samples);
207     i->audio_pos += samples;
208     return bytes;
209 }
210
211 static int videoreader_vfw_getsamples(videoreader_t* vr, void*buf, int num)
212 {
213     videoreader_vfw_internal_t* i = (videoreader_vfw_internal_t*)vr->internal;
214    
215     switch(i->waveformat.wBitsPerSample) {
216         case 1: {
217             int len = readAudioBlock(i, buf, num);
218             int t = len-1;
219             do {
220                 ((SHORT*)buf)[t] = ((((BYTE*)buf)[t>>3])>>(t&7))<<15;
221             } while(--t>=0);
222             return len*8;
223         }
224         case 8: {
225             int len = readAudioBlock(i, buf, num);
226             int t = len-1;
227             do {
228                 ((SHORT*)buf)[t] = (((BYTE*)buf)[t]<<8)^0x8000;
229             } while(--t>=0);
230             return len*2;
231         }
232         case 16: {
233             return readAudioBlock(i, buf, num);
234         }
235         default: {
236             return 0;
237         }
238     }
239 }
240
241 static void videoreader_vfw_close(videoreader_t* vr)
242 {
243     videoreader_vfw_internal_t* i = (videoreader_vfw_internal_t*)vr->internal;
244
245     AVIStreamGetFrameClose(i->getframe);
246     if(i->vs) {
247         AVIStreamRelease(i->vs); i->vs = 0;
248     }
249     if(i->as) {
250         AVIStreamRelease(i->as); i->vs = 0;
251     }
252     AVIFileRelease(i->avifile); i->avifile = 0;
253     
254     AVIFileExit(); avifile_initialized=0;
255
256     free(vr->internal); vr->internal = 0;
257 }
258
259 static void videoreader_vfw_setparameter(videoreader_t*vr, char*name, char*value)
260 {
261     videoreader_vfw_internal_t* i = (videoreader_vfw_internal_t*)vr->internal;
262     if(!strcmp(name, "flip")) {
263         i->flip = atoi(value);
264     } else if(!strcmp(name, "verbose")) {
265         verbose = atoi(value);
266     }
267 }
268
269 int videoreader_vfw_open(videoreader_t* vr, char* filename)
270 {
271     memset(vr, 0, sizeof(videoreader_t));
272     if(!filename) {
273         /* codec query */
274         return 1;
275     }
276
277     videoreader_vfw_internal_t* i = (videoreader_vfw_internal_t*)malloc(sizeof(videoreader_vfw_internal_t));
278     memset(i, 0, sizeof(videoreader_vfw_internal_t));
279
280     vr->internal = i;
281     vr->eof = videoreader_vfw_eof;
282     vr->getimage = videoreader_vfw_getimage;
283     vr->getsamples = videoreader_vfw_getsamples;
284     vr->close = videoreader_vfw_close;
285     vr->setparameter = videoreader_vfw_setparameter;
286
287     if(!avifile_initialized) {
288         AVIFileInit();
289     }
290     if(AVIFileOpen(&i->avifile, filename, OF_SHARE_DENY_WRITE, 0)) {
291         fprintf(stderr, "Couldn't open %s\n", filename);
292         return -1;
293     }
294     AVIFILEINFO info;
295     AVIFileInfo(i->avifile, &info, sizeof(info));
296    
297     /* calculate framerate */
298     i->fps = (double)info.dwRate/(double)info.dwScale;
299
300     if(verbose) {
301         printf("vfw: file %s has %f fps, and %d streams\n", i->fps, info.dwStreams);
302     }
303
304     unsigned int t=0;
305     while(t<info.dwStreams) {
306         PAVISTREAM stream;
307         if(AVIFileGetStream(i->avifile, &stream, streamtypeANY, t) != AVIERR_OK || !stream)
308             break; //video_end of (working) streams
309
310         AVISTREAMINFO streaminfo;
311         AVIStreamInfo(stream, &streaminfo, sizeof(streaminfo));
312
313         if (streaminfo.fccType == streamtypeVIDEO) {
314             /* video stream */
315
316             BITMAPINFOHEADER bitmap;
317             LONG size = sizeof(bitmap);
318             AVIStreamReadFormat(stream, 0, &bitmap, &size);
319
320             if(1) {
321                 i->bitmap = bitmap;
322                 i->vs = stream;
323                 i->width = bitmap.biWidth;
324                 i->height = bitmap.biHeight;
325             } else {
326                 fprintf(stderr, "Ignoring video stream: %dx%d compression=%d planes=%d\n", 
327                         bitmap.biWidth, bitmap.biHeight,
328                         bitmap.biCompression,bitmap.biPlanes);
329             }
330         }
331         else if (streaminfo.fccType == streamtypeAUDIO) {
332             /* audio stream */
333
334             WAVEFORMATEX waveformat;
335             LONG size = sizeof(waveformat);
336             AVIStreamReadFormat(stream, 0, &waveformat, &size);
337
338             if(waveformat.wBitsPerSample == 16 || 
339                waveformat.wBitsPerSample == 8 ||
340                waveformat.wBitsPerSample == 1
341                ) {
342                 i->waveformat = waveformat;
343                 i->as = stream;
344                 i->channels = waveformat.nChannels;
345                 i->samplerate = waveformat.nSamplesPerSec;
346             } else {
347                 fprintf(stderr, "Ignoring audio stream: bitspersample=%d\n", waveformat.wBitsPerSample);
348             }
349         }
350         t++;
351     }
352
353     if(i->vs) {
354         if(verbose) {
355             printf("vfw: video stream: %dx%d, %.2f\n", i->width, i->height, i->fps);
356         }
357         vr->width = i->width;
358         vr->height = i->height;
359         vr->fps = i->fps;
360     } else {
361         fprintf(stderr, "AVIReader: Warning: No video stream\n");
362     }
363     if(i->as) {
364         if(verbose) {
365             printf("vfw: audio stream: %d channels, %d samples/sec", i->channels, i->samplerate);
366         }
367         vr->channels = i->channels;
368         vr->samplerate = i->samplerate;
369     } else {
370         fprintf(stderr, "AVIReader: Warning: No audio stream\n");
371     }
372     
373     i->getframe = AVIStreamGetFrameOpen(i->vs, 0);
374     if(!i->getframe) {
375         fprintf(stderr, "Couldn't initialize AVIStream for %s- codec missing?\n", filename);
376         return -1;
377     }
378     
379     i->video_pos = AVIStreamStart(i->vs);
380     i->video_end = AVIStreamEnd(i->vs);
381     i->audio_pos = 0;
382     i->audio_end = 0x7fffffff;
383
384     return 0;
385 }
386
387 #else //WIN32
388
389 int videoreader_vfw_open(videoreader_t* vr, char* filename)
390 {
391     return -1;
392 }
393
394 #endif //WIN32
395