2 Convert avi movie files into swf.
4 Part of the swftools package.
6 Copyright (c) 2001 Matthias Kramm <kramm@quiss.org>
8 This file is distributed under the GPL, see file COPYING for details */
13 #include "../lib/rfxswf.h"
14 #include "../lib/args.h"
17 #include <avifile/version.h>
18 #if (AVIFILE_MAJOR_VERSION == 0) && (AVIFILE_MINOR_VERSION>=6)
23 #include <StreamInfo.h>
37 37 bytes per shape (rectangle)
38 8-12 bytes per placeobject
39 4 bytes per removeobject2
40 696+ bytes per definejpeg2 (576 jpegtables)
41 576 bytes per jpegtables
42 122+ bytes per definejpeg
44 blocks*140 = minimal bytes per frames
45 5000/140 = maximal blocks with framerate 5000
50 static int cache_size=38; //in frames
52 static char * filename = 0;
53 static char * outputfilename = "output.swf";
54 static unsigned int firstframe = 0;
55 static unsigned int lastframe = 0x7fffffff;
57 static int jpeg_quality = 20;
60 static double scale = 1.0;
63 #ifndef ST_DEFINEBITSJPEG
64 #define ST_DEFINEBITSJPEG 6
69 struct options_t options[] =
81 int args_callback_option(char*name,char*val)
83 if(!strcmp(name, "V")) {
84 printf("avi2swf - part of %s %s\n", PACKAGE, VERSION);
87 else if(!strcmp(name, "o")) {
91 else if(!strcmp(name, "n")) {
92 lastframe = atoi(val);
95 else if(!strcmp(name, "s")) {
96 firstframe = atoi(val);
99 else if(!strcmp(name, "p")) {
103 else if(!strcmp(name, "d")) {
104 scale = atoi(val)/100.0;
105 if(scale>1.0 || scale<=0) {
106 fprintf(stderr, "Scale must be in the range 1-100!\n");
111 else if(!strcmp(name, "z")) {
115 fprintf(stderr, "Unknown option: -%s\n", name);
118 int args_callback_longoption(char*name,char*val)
120 return args_long2shortoption(options, name, val);
122 void args_callback_usage(char*name)
124 printf("\nUsage: %s file.avi\n", name);
125 printf("\t-h , --help\t\t Print help and exit\n");
126 printf("\t-o , --output filename\t Specify output filename\n");
127 printf("\t-n , --num frames\t Number of frames to encode\n");
128 printf("\t-s , --start frame\t First frame to encode\n");
129 printf("\t-d , --scale factor\t Scale to factor percent\n");
130 printf("\t-p , --flip\t\t Turn movie upside down\n");
131 printf("\t-V , --version\t\t Print program version and exit\n");
134 int args_callback_command(char*name,char*val)
137 fprintf(stderr, "Only one file allowed. You supplied at least two. (%s and %s)\n",
144 /* id allocation/deallocation */
146 unsigned int idtab_pos=1;
149 while(idtab[idtab_pos] || !idtab_pos)
159 void makeshape(int file, int id, int gfxid, int width, int height)
168 tag = swf_InsertTag(NULL, ST_DEFINESHAPE);
170 rgb.b = rgb.g = rgb.r = 0xff;
172 ls = swf_ShapeAddLineStyle(s,20,&rgb);
173 swf_GetMatrix(NULL,&m);
177 fs = swf_ShapeAddBitmapFillStyle(s,&m,gfxid,0);
178 swf_SetU16(tag,id); // ID
185 swf_SetShapeStyles(tag,s);
186 swf_ShapeCountBits(s,NULL,NULL);
187 swf_SetShapeBits(tag,s);
189 swf_ShapeSetAll(tag,s,0,0,lines?ls:0,fs,0);
191 swf_ShapeSetLine(tag,s,width*20,0);
192 swf_ShapeSetLine(tag,s,0,height*20);
193 swf_ShapeSetLine(tag,s,-width*20,0);
194 swf_ShapeSetLine(tag,s,0,-height*20);
195 swf_ShapeSetEnd(tag);
196 filesize += swf_WriteTag(file, tag);
201 void setshape(int file,int id,int depth,int x,int y,CXFORM*cx)
205 m.sx = 0x10000; m.sy = 0x10000;
209 if(cx && !((cx->a0!=256)||(cx->r0!=256)||(cx->g0!=256)||(cx->b0!=256)
210 ||(cx->a1|cx->r1|cx->g1|cx->b1))) cx = 0;
211 tag = swf_InsertTag(NULL,ST_PLACEOBJECT2);
212 swf_ObjectPlace(tag,id,depth,&m,cx,0);
213 filesize += swf_WriteTag(file, tag);
221 // static int xblocksize;
222 // static int yblocksize;
235 class GfxBlockCache {
238 char*expire; //0=block's free
247 GfxBlockCache(int file)
250 size = xblocks*yblocks*cache_size;
251 printf("initializing cache (%d entries)\n", size);
252 list = new GfxBlock[size];
253 expire = new char[size];
255 memset(expire,0,size);
256 memset(list,0,sizeof(GfxBlock)*size);
257 memset(ids,0,sizeof(int)*size);
262 void insert(GfxBlock*block, int gfxid)
272 // cache full- don't insert item
276 free(list[pos].data);
278 //TODO: free this in the SWF, also
280 list[pos].data=(U8*)malloc(block->len);
281 memcpy(list[pos].data,block->data,block->len);
282 list[pos].len = block->len;
283 expire[pos] = cache_size;
286 int find(GfxBlock*block, CXFORM*cxform)
288 //TODO: do least square regression here to derive cxform
296 int t = (block->len);
297 U8*ptr1 = block->data;
298 U8*ptr2 = list[s].data;
300 // notice: we treat r,g,b as equal here.
302 int a = (*ptr1++)-(*ptr2++);
305 if(bestsum < 0 || bestsum > sum2) {
314 best = bestsum/block->len;
320 expire[bestid]= cache_size;
343 printf("destroying cache...\n");
345 printf("hits:%d (%02d%%)\n", hits, hits*100/(hits+misses));
346 printf("misses:%d (%02d%%)\n", misses, misses*100/(hits+misses));
349 if(expire[t] && list[t].data)
357 class GfxBlockEncoder {
365 void init(int depth, int posx,int posy, int sizex, int sizey)
367 this->basedepth = depth;
372 this->depth[0] = this->depth[1] = this->depth[2] = -1;
376 /* clear everything in the block */
382 tag = swf_InsertTag(NULL, ST_REMOVEOBJECT2);
383 swf_SetU16(tag, basedepth+t); //depth
384 filesize += swf_WriteTag(file, tag);
389 void writeiframe(int file, GfxBlock*block)
393 int gfxid = get_free_id();
394 int shapeid = get_free_id();
396 //memset(data,0,sizex*sizey*3);
397 TAG*tag = swf_InsertTag(NULL, ST_DEFINEBITS);
398 JPEGBITS * jb = swf_SetJPEGBitsStart(tag,sizex,sizey,jpeg_quality);
399 tag->len = 0; //bad hack
400 swf_SetU16(tag, gfxid);
403 swf_SetJPEGBitsLine(jb,&block->data[y*sizex*3]);
404 swf_SetJPEGBitsFinish(jb);
405 filesize += swf_WriteTag(file, tag);
408 cache->insert(block, shapeid);
410 makeshape(file, shapeid, gfxid, sizex, sizey);
411 setshape(file, shapeid, basedepth+1, posx, posy, 0);
414 void writereference(int file, int shapeid, CXFORM*form)
416 if(depth[1]!=shapeid)
419 setshape(file, shapeid, basedepth+1, posx, posy, form);
423 void compress(int file, GfxBlock*block)
426 int id = cache->find(block, &form);
428 writeiframe(file, block);
430 writereference(file, id, &form);
435 void initdisplay(int file)
441 for(t=0;t<xblocks;t++)
442 blocks[t].clear(file);
447 xblocksize = (width/3)&~7;
448 yblocksize = (height/2)&~7;
449 xblocks = width/xblocksize;
450 yblocks = height/yblocksize;
451 printf("%dx%d blocks of size %dx%d\n", xblocks,yblocks, xblocksize, yblocksize);
452 printf("cutting lower %d lines, right %d columns\n",
453 height-yblocks*yblocksize, width-xblocks*xblocksize);
454 blocks = new GfxBlockEncoder[xblocks*yblocks];
455 blockbuffer = new U8[xblocksize*yblocksize*4]; //should be 3
456 cache = new GfxBlockCache(file);
458 for(t=0;t<xblocks*yblocks;t++) {
460 (t%xblocks)*xblocksize,
461 (t/xblocks)*yblocksize,
462 xblocksize, yblocksize);
465 TAG*tag = swf_InsertTag(NULL, ST_JPEGTABLES);
466 JPEGBITS * jpeg = swf_SetJPEGBitsStart(tag, xblocksize, yblocksize, jpeg_quality);
467 filesize += swf_WriteTag(file, tag);
472 void destroydisplay(int file)
485 short int* sound_buffer;
489 IAviReadStream* astream;
492 unsigned samples_read, bytes_read;
494 short int tmpbuf[4096];
495 ret = astream->ReadFrames(tmpbuf, 4096*sizeof(short int),
496 4096, samples_read, bytes_read);
498 printf("couldn't read %d samples\n", mp3_block_size);
502 samples_read = bytes_read/sizeof(short int);
503 for(t=0;t<samples_read/2;t++) {
504 sound_buffer[write_pos+t] = tmpbuf[t*2];
506 write_pos += samples_read/2;
508 if(write_pos >= mp3_block_size*8)
510 if(write_pos > mp3_block_size*8)
511 memcpy(&sound_buffer[0],&sound_buffer[mp3_block_size*8],write_pos - mp3_block_size*8);
512 write_pos %= (mp3_block_size*8);
517 SoundReader(IAviReadStream*astream)
519 this->astream = astream;
522 this->mp3_block_size = 2304;
523 this->sound_buffer = new short int[mp3_block_size*16];
531 if(read_pos<=write_pos)
532 return write_pos-read_pos;
534 return (write_pos+mp3_block_size*8)-read_pos;
536 short int* readFrame()
539 while(available()<mp3_block_size) {
543 read_pos += mp3_block_size;
544 read_pos %= mp3_block_size*8;
545 return &sound_buffer[tmp];
550 static int mp3_block_size = 2304;
552 static int do_video = 1;
553 static int do_audio = 1;
555 int main (int argc,char ** argv)
558 IAviReadFile* player;
559 IAviReadStream* astream;
560 IAviReadStream* vstream;
562 double samplesperframe;
570 processargs(argc, argv);
571 lastframe += firstframe;
575 memset(idtab, 0, sizeof(idtab));
577 player = CreateIAviReadFile(filename);
578 astream = player->GetStream(0, AviStream::Audio);
579 vstream = player->GetStream(0, AviStream::Video);
586 int dwMicroSecPerFrame = 0;
587 player->GetFileHeader(&head);
588 printf("fps: %d\n", 1000000/head.dwMicroSecPerFrame);
589 printf("frames: %d\n", head.dwTotalFrames);
590 printf("streams: %d\n", head.dwStreams);
591 printf("width: %d\n", head.dwWidth);
592 printf("height: %d\n", head.dwHeight);
593 printf("sound: %u samples (%f seconds)\n", astream->GetEndPos(),
594 astream->GetEndTime());
595 oldwidth = head.dwWidth;
596 oldheight = head.dwHeight;
597 dwMicroSecPerFrame = head.dwMicroSecPerFrame;
598 samplesperframe = astream->GetEndPos()/astream->GetEndTime()*head.dwMicroSecPerFrame/1000000;
599 samplerate = (int)(astream->GetEndPos()/astream->GetEndTime());
600 fps = 1000000.0/dwMicroSecPerFrame;
602 StreamInfo*audioinfo;
603 StreamInfo*videoinfo;
606 videoinfo = vstream->GetStreamInfo();
607 oldwidth = videoinfo->GetVideoWidth();
608 oldheight = videoinfo->GetVideoHeight();
609 fps = (double)(videoinfo->GetFps());
614 audioinfo = astream->GetStreamInfo();
615 samplerate = audioinfo->GetAudioSamplesPerSec();
616 samplesperframe = audioinfo->GetAudioSamplesPerSec()/videoinfo->GetFps();
620 width = (int)(oldwidth*scale);
621 height = (int)(oldheight*scale);
624 vstream -> StartStreaming();
627 astream -> StartStreaming();
628 printf("%f framerate\n", fps);
629 printf("%f samples/frame\n", samplesperframe);
630 printf("%d samplerate\n", samplerate);
634 file = open("__tmp__.swf", O_WRONLY|O_CREAT|O_TRUNC, 0644);
636 file = open(outputfilename, O_WRONLY|O_CREAT|O_TRUNC, 0644);
638 memset(&swf, 0, sizeof(swf));
639 swf.frameRate = (int)(fps*256);
641 swf.fileSize = 0x0fffffff;
642 swf.frameCount = lastframe - firstframe;
649 filesize += swf_WriteHeader(file, &swf);
651 tag = swf_InsertTag(NULL, ST_SETBACKGROUNDCOLOR);
652 swf_SetU8(tag,0); //black
655 filesize += swf_WriteTag(file, tag);
658 tag = swf_InsertTag(NULL, ST_SOUNDSTREAMHEAD2);
659 swf_SetSoundStreamHead(tag, (int)samplesperframe/4);
660 filesize += swf_WriteTag(file, tag);
666 double movie_sound_pos = 0;
667 int mp3_sound_pos = 0;
672 astream->GetAudioFormatInfo(&wave,0);
674 printf("nChannels:%d\n", wave.nChannels);
675 printf("nSamplesPerSec:%d\n", wave.nSamplesPerSec);
676 printf("nAvgBytesPerSec:%d\n", wave.nAvgBytesPerSec);
677 printf("nBlockAlign:%d\n", wave.nBlockAlign);
678 printf("wBitsPerSample:%d\n", wave.wBitsPerSample);
679 printf("cbSize:%d\n", wave.cbSize);
682 SoundReader* sound = new SoundReader(astream);
685 if(vstream->ReadFrame()<0) {
690 if(frame < firstframe)
692 movie_sound_pos += samplesperframe;
694 while(mp3_sound_pos<movie_sound_pos) {
695 short int* samples = sound->readFrame();
696 mp3_sound_pos += mp3_block_size;
698 printf("\rskipping frame %d",frame);
701 if(frame == firstframe)
706 printf("\rconvert frame %d",frame);
710 movie_sound_pos += samplesperframe;
714 while(mp3_sound_pos<movie_sound_pos) {
715 // rawplay -s 44100 -f s16_le -c 2 samples.test
716 short int* samples = sound->readFrame();
719 if(first) { //first run
720 tag = swf_InsertTag(NULL, ST_SOUNDSTREAMBLOCK);
721 swf_SetSoundStreamBlock(tag, samples, 1);
723 swf_SetSoundStreamBlock(tag, samples, 0);
726 mp3_sound_pos += mp3_block_size;
728 if(mp3_sound_pos>=movie_sound_pos) { // last run
729 filesize += swf_WriteTag(file, tag);
737 CImage*img = vstream->GetFrame();
739 U8*data = img->Data();
740 int bpp = img->Bpp();
749 /* some movies have changing dimensions */
750 if(img->Width() != oldwidth ||
751 img->Height() != oldheight) {
753 oldwidth = img->Width();
754 oldheight = img->Height();
755 width = (int)(oldwidth*scale);
756 height = (int)(oldheight*scale);
760 for(yy=0;yy<yblocks;yy++)
761 for(xx=0;xx<xblocks;xx++)
764 for(y=0;y<yblocksize;y++) {
765 /* some avifile versions flip the image some don't. Maybe this is
766 even movie dependent. We just let the user decide which side's up. */
769 mydata = img->At(oldheight-(int)((yy*yblocksize+y)*reziscale));
771 mydata = img->At((int)((yy*yblocksize+y)*reziscale));
773 for(x=0;x<xblocksize;x++) {
774 blockbuffer[(y*xblocksize+x)*3+2] = mydata[((int)(((xx*xblocksize+x)*reziscale)))*3+0];
775 blockbuffer[(y*xblocksize+x)*3+1] = mydata[((int)(((xx*xblocksize+x)*reziscale)))*3+1];
776 blockbuffer[(y*xblocksize+x)*3+0] = mydata[((int)(((xx*xblocksize+x)*reziscale)))*3+2];
780 b.data = blockbuffer;
781 b.len = xblocksize*yblocksize*3;
782 blocks[yy*xblocks+xx].compress(file, &b);
785 tag = swf_InsertTag(NULL, ST_SHOWFRAME);
786 filesize += swf_WriteTag(file, tag);
792 if(frame == lastframe)
797 destroydisplay(file);
799 tag = swf_InsertTag(NULL, ST_END);
800 filesize += swf_WriteTag(file, tag);
807 fi=fopen("tmp.swf", "r+");
809 fi=fopen(outputfilename, "r+");
813 fseek(fi,4,SEEK_SET);
815 f = filesize ;fwrite(&f,1,1,fi);
816 f = filesize >> 8 ;fwrite(&f,1,1,fi);
817 f = filesize >> 16;fwrite(&f,1,1,fi);
818 f = filesize >> 24;fwrite(&f,1,1,fi);
824 snprintf(buffer, 1024, "swfcombine -dz __tmp__.swf -o %s", outputfilename);
825 printf("%s\n", buffer);
827 sprintf(buffer, "rm __tmp__.swf");
828 printf("%s\n", buffer);