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"
16 #include <avifile/version.h>
17 #if (AVIFILE_MAJOR_VERSION == 0) && (AVIFILE_MINOR_VERSION==6)
22 #include <StreamInfo.h>
36 37 bytes per shape (rectangle)
37 8-12 bytes per placeobject
38 4 bytes per removeobject2
39 696+ bytes per definejpeg2 (576 jpegtables)
40 576 bytes per jpegtables
41 122+ bytes per definejpeg
43 blocks*140 = minimal bytes per frames
44 5000/140 = maximal blocks with framerate 5000
49 static int cache_size=38; //in frames
51 static char * filename = 0;
52 static char * outputfilename = "output.swf";
53 static unsigned int firstframe = 0;
54 static unsigned int lastframe = 0x7fffffff;
56 static int jpeg_quality = 20;
59 static double scale = 1.0;
61 #ifndef ST_DEFINEBITSJPEG
62 #define ST_DEFINEBITSJPEG 6
67 struct options_t options[] =
78 int args_callback_option(char*name,char*val)
80 if(!strcmp(name, "V")) {
81 printf("avi2swf - part of %s %s\n", PACKAGE, VERSION);
84 else if(!strcmp(name, "o")) {
88 else if(!strcmp(name, "n")) {
89 lastframe = atoi(val);
92 else if(!strcmp(name, "s")) {
93 firstframe = atoi(val);
96 else if(!strcmp(name, "d")) {
97 scale = atoi(val)/100.0;
98 if(scale>1.0 || scale<=0) {
99 fprintf(stderr, "Scale must be in the range 1-100!\n");
104 else if(!strcmp(name, "z")) {
108 fprintf(stderr, "Unknown option: -%s\n", name);
111 int args_callback_longoption(char*name,char*val)
113 return args_long2shortoption(options, name, val);
115 void args_callback_usage(char*name)
117 printf("\nUsage: %s file.avi\n", name);
118 printf("\t-h , --help\t\t Print help and exit\n");
119 printf("\t-o , --output filename\t Specify output filename\n");
120 printf("\t-n , --num frames\t Number of frames to encode\n");
121 printf("\t-s , --start frame\t First frame to encode\n");
122 printf("\t-d , --scale factor\t Scale to factor percent\n");
123 printf("\t-V , --version\t\t Print program version and exit\n");
126 int args_callback_command(char*name,char*val)
129 fprintf(stderr, "Only one file allowed. You supplied at least two. (%s and %s)\n",
136 /* id allocation/deallocation */
138 unsigned int idtab_pos=1;
141 while(idtab[idtab_pos] || !idtab_pos)
151 void makeshape(int file, int id, int gfxid, int width, int height)
160 tag = swf_InsertTag(NULL, ST_DEFINESHAPE);
162 rgb.b = rgb.g = rgb.r = 0xff;
164 ls = swf_ShapeAddLineStyle(s,20,&rgb);
165 swf_GetMatrix(NULL,&m);
169 fs = swf_ShapeAddBitmapFillStyle(s,&m,gfxid,0);
170 swf_SetU16(tag,id); // ID
177 swf_SetShapeStyles(tag,s);
178 swf_ShapeCountBits(s,NULL,NULL);
179 swf_SetShapeBits(tag,s);
181 swf_ShapeSetAll(tag,s,0,0,lines?ls:0,fs,0);
183 swf_ShapeSetLine(tag,s,width*20,0);
184 swf_ShapeSetLine(tag,s,0,height*20);
185 swf_ShapeSetLine(tag,s,-width*20,0);
186 swf_ShapeSetLine(tag,s,0,-height*20);
187 swf_ShapeSetEnd(tag);
188 filesize += swf_WriteTag(file, tag);
193 void setshape(int file,int id,int depth,int x,int y,CXFORM*cx)
197 m.sx = 0x10000; m.sy = 0x10000;
201 if(cx && !((cx->a0!=256)||(cx->r0!=256)||(cx->g0!=256)||(cx->b0!=256)
202 ||(cx->a1|cx->r1|cx->g1|cx->b1))) cx = 0;
203 tag = swf_InsertTag(NULL,ST_PLACEOBJECT2);
204 swf_ObjectPlace(tag,id,depth,&m,cx,0);
205 filesize += swf_WriteTag(file, tag);
213 // static int xblocksize;
214 // static int yblocksize;
227 class GfxBlockCache {
230 char*expire; //0=block's free
239 GfxBlockCache(int file)
242 size = xblocks*yblocks*cache_size;
243 printf("initializing cache (%d entries)\n", size);
244 list = new GfxBlock[size];
245 expire = new char[size];
247 memset(expire,0,size);
248 memset(list,0,sizeof(GfxBlock)*size);
249 memset(ids,0,sizeof(int)*size);
254 void insert(GfxBlock*block, int gfxid)
264 // cache full- don't insert item
268 free(list[pos].data);
270 //TODO: free this in the SWF, also
272 list[pos].data=(U8*)malloc(block->len);
273 memcpy(list[pos].data,block->data,block->len);
274 list[pos].len = block->len;
275 expire[pos] = cache_size;
278 int find(GfxBlock*block, CXFORM*cxform)
280 //TODO: do least square regression here to derive cxform
288 int t = (block->len);
289 U8*ptr1 = block->data;
290 U8*ptr2 = list[s].data;
292 // notice: we treat r,g,b as equal here.
294 int a = (*ptr1++)-(*ptr2++);
297 if(bestsum < 0 || bestsum > sum2) {
306 best = bestsum/block->len;
312 expire[bestid]= cache_size;
335 printf("destroying cache...\n");
337 printf("hits:%d (%02d%%)\n", hits, hits*100/(hits+misses));
338 printf("misses:%d (%02d%%)\n", misses, misses*100/(hits+misses));
341 if(expire[t] && list[t].data)
349 class GfxBlockEncoder {
357 void init(int depth, int posx,int posy, int sizex, int sizey)
359 this->basedepth = depth;
364 this->depth[0] = this->depth[1] = this->depth[2] = -1;
368 /* clear everything in the block */
374 tag = swf_InsertTag(NULL, ST_REMOVEOBJECT2);
375 swf_SetU16(tag, basedepth+t); //depth
376 filesize += swf_WriteTag(file, tag);
381 void writeiframe(int file, GfxBlock*block)
385 int gfxid = get_free_id();
386 int shapeid = get_free_id();
388 //memset(data,0,sizex*sizey*3);
389 TAG*tag = swf_InsertTag(NULL, ST_DEFINEBITS);
390 JPEGBITS * jb = swf_SetJPEGBitsStart(tag,sizex,sizey,jpeg_quality);
391 tag->len = 0; //bad hack
392 swf_SetU16(tag, gfxid);
395 swf_SetJPEGBitsLine(jb,&block->data[y*sizex*3]);
396 swf_SetJPEGBitsFinish(jb);
397 filesize += swf_WriteTag(file, tag);
400 cache->insert(block, shapeid);
402 makeshape(file, shapeid, gfxid, sizex, sizey);
403 setshape(file, shapeid, basedepth+1, posx, posy, 0);
406 void writereference(int file, int shapeid, CXFORM*form)
408 if(depth[1]!=shapeid)
411 setshape(file, shapeid, basedepth+1, posx, posy, form);
415 void compress(int file, GfxBlock*block)
418 int id = cache->find(block, &form);
420 writeiframe(file, block);
422 writereference(file, id, &form);
427 void initdisplay(int file)
433 for(t=0;t<xblocks;t++)
434 blocks[t].clear(file);
439 xblocksize = (width/3)&~7;
440 yblocksize = (height/2)&~7;
441 xblocks = width/xblocksize;
442 yblocks = height/yblocksize;
443 printf("%dx%d blocks of size %dx%d\n", xblocks,yblocks, xblocksize, yblocksize);
444 printf("cutting lower %d lines, right %d columns\n",
445 height-yblocks*yblocksize, width-xblocks*xblocksize);
446 blocks = new GfxBlockEncoder[xblocks*yblocks];
447 blockbuffer = new U8[xblocksize*yblocksize*4]; //should be 3
448 cache = new GfxBlockCache(file);
450 for(t=0;t<xblocks*yblocks;t++) {
452 (t%xblocks)*xblocksize,
453 (t/xblocks)*yblocksize,
454 xblocksize, yblocksize);
457 TAG*tag = swf_InsertTag(NULL, ST_JPEGTABLES);
458 JPEGBITS * jpeg = swf_SetJPEGBitsStart(tag, xblocksize, yblocksize, jpeg_quality);
459 filesize += swf_WriteTag(file, tag);
464 void destroydisplay(int file)
477 short int* sound_buffer;
481 IAviReadStream* astream;
484 unsigned samples_read, bytes_read;
486 short int tmpbuf[4096];
487 ret = astream->ReadFrames(tmpbuf, 4096*sizeof(short int),
488 4096, samples_read, bytes_read);
490 printf("couldn't read %d samples\n", mp3_block_size);
494 samples_read = bytes_read/sizeof(short int);
495 for(t=0;t<samples_read/2;t++) {
496 sound_buffer[write_pos+t] = tmpbuf[t*2];
498 write_pos += samples_read/2;
500 if(write_pos >= mp3_block_size*8)
502 if(write_pos > mp3_block_size*8)
503 memcpy(&sound_buffer[0],&sound_buffer[mp3_block_size*8],write_pos - mp3_block_size*8);
504 write_pos %= (mp3_block_size*8);
509 SoundReader(IAviReadStream*astream)
511 this->astream = astream;
514 this->mp3_block_size = 2304;
515 this->sound_buffer = new short int[mp3_block_size*16];
523 if(read_pos<=write_pos)
524 return write_pos-read_pos;
526 return (write_pos+mp3_block_size*8)-read_pos;
528 short int* readFrame()
531 while(available()<mp3_block_size) {
535 read_pos += mp3_block_size;
536 read_pos %= mp3_block_size*8;
537 return &sound_buffer[tmp];
542 static int mp3_block_size = 2304;
544 static int do_video = 1;
545 static int do_audio = 1;
547 int main (int argc,char ** argv)
550 IAviReadFile* player;
551 IAviReadStream* astream;
552 IAviReadStream* vstream;
554 double samplesperframe;
562 processargs(argc, argv);
563 lastframe += firstframe;
567 memset(idtab, 0, sizeof(idtab));
569 player = CreateIAviReadFile(filename);
570 astream = player->GetStream(0, AviStream::Audio);
571 vstream = player->GetStream(0, AviStream::Video);
578 int dwMicroSecPerFrame = 0;
579 player->GetFileHeader(&head);
580 printf("fps: %d\n", 1000000/head.dwMicroSecPerFrame);
581 printf("frames: %d\n", head.dwTotalFrames);
582 printf("streams: %d\n", head.dwStreams);
583 printf("width: %d\n", head.dwWidth);
584 printf("height: %d\n", head.dwHeight);
585 printf("sound: %u samples (%f seconds)\n", astream->GetEndPos(),
586 astream->GetEndTime());
587 oldwidth = head.dwWidth;
588 oldheight = head.dwHeight;
589 dwMicroSecPerFrame = head.dwMicroSecPerFrame;
590 samplesperframe = astream->GetEndPos()/astream->GetEndTime()*head.dwMicroSecPerFrame/1000000;
591 samplerate = (int)(astream->GetEndPos()/astream->GetEndTime());
592 fps = 1000000.0/dwMicroSecPerFrame;
594 StreamInfo*audioinfo;
595 StreamInfo*videoinfo;
598 videoinfo = vstream->GetStreamInfo();
599 oldwidth = videoinfo->GetVideoWidth();
600 oldheight = videoinfo->GetVideoHeight();
601 fps = (double)(videoinfo->GetFps());
606 audioinfo = astream->GetStreamInfo();
607 samplerate = audioinfo->GetAudioSamplesPerSec();
608 samplesperframe = audioinfo->GetAudioSamplesPerSec()/videoinfo->GetFps();
612 width = (int)(oldwidth*scale);
613 height = (int)(oldheight*scale);
616 vstream -> StartStreaming();
619 astream -> StartStreaming();
620 printf("%f framerate\n", fps);
621 printf("%f samples/frame\n", samplesperframe);
622 printf("%d samplerate\n", samplerate);
626 file = open("__tmp__.swf", O_WRONLY|O_CREAT|O_TRUNC, 0644);
628 file = open(outputfilename, O_WRONLY|O_CREAT|O_TRUNC, 0644);
630 memset(&swf, 0, sizeof(swf));
631 swf.frameRate = (int)(fps*256);
633 swf.fileSize = 0x0fffffff;
634 swf.frameCount = lastframe - firstframe;
641 filesize += swf_WriteHeader(file, &swf);
643 tag = swf_InsertTag(NULL, ST_SETBACKGROUNDCOLOR);
644 swf_SetU8(tag,0); //black
647 filesize += swf_WriteTag(file, tag);
650 tag = swf_InsertTag(NULL, ST_SOUNDSTREAMHEAD2);
651 swf_SetSoundStreamHead(tag, (int)samplesperframe/4);
652 filesize += swf_WriteTag(file, tag);
658 double movie_sound_pos = 0;
659 int mp3_sound_pos = 0;
664 astream->GetAudioFormatInfo(&wave,0);
666 printf("nChannels:%d\n", wave.nChannels);
667 printf("nSamplesPerSec:%d\n", wave.nSamplesPerSec);
668 printf("nAvgBytesPerSec:%d\n", wave.nAvgBytesPerSec);
669 printf("nBlockAlign:%d\n", wave.nBlockAlign);
670 printf("wBitsPerSample:%d\n", wave.wBitsPerSample);
671 printf("cbSize:%d\n", wave.cbSize);
674 SoundReader* sound = new SoundReader(astream);
677 if(vstream->ReadFrame()<0) {
682 if(frame < firstframe)
684 movie_sound_pos += samplesperframe;
686 while(mp3_sound_pos<movie_sound_pos) {
687 short int* samples = sound->readFrame();
688 mp3_sound_pos += mp3_block_size;
690 printf("\rskipping frame %d",frame);
693 if(frame == firstframe)
698 printf("\rconvert frame %d",frame);
702 movie_sound_pos += samplesperframe;
706 while(mp3_sound_pos<movie_sound_pos) {
707 // rawplay -s 44100 -f s16_le -c 2 samples.test
708 short int* samples = sound->readFrame();
711 if(first) { //first run
712 tag = swf_InsertTag(NULL, ST_SOUNDSTREAMBLOCK);
713 swf_SetSoundStreamBlock(tag, samples, 1);
715 swf_SetSoundStreamBlock(tag, samples, 0);
718 mp3_sound_pos += mp3_block_size;
720 if(mp3_sound_pos>=movie_sound_pos) { // last run
721 filesize += swf_WriteTag(file, tag);
729 CImage*img = vstream->GetFrame();
731 U8*data = img->Data();
732 int bpp = img->Bpp();
741 /* some movies have changing dimensions */
742 if(img->Width() != oldwidth ||
743 img->Height() != oldheight) {
745 oldwidth = img->Width();
746 oldheight = img->Height();
747 width = (int)(oldwidth*scale);
748 height = (int)(oldheight*scale);
752 for(yy=0;yy<yblocks;yy++)
753 for(xx=0;xx<xblocks;xx++)
756 for(y=0;y<yblocksize;y++) {
758 U8*mydata = img->At(oldheight-(int)((yy*yblocksize+y)*reziscale));
760 U8*mydata = img->At((int)((yy*yblocksize+y)*reziscale));
762 for(x=0;x<xblocksize;x++) {
763 blockbuffer[(y*xblocksize+x)*3+2] = mydata[((int)(((xx*xblocksize+x)*reziscale)))*3+0];
764 blockbuffer[(y*xblocksize+x)*3+1] = mydata[((int)(((xx*xblocksize+x)*reziscale)))*3+1];
765 blockbuffer[(y*xblocksize+x)*3+0] = mydata[((int)(((xx*xblocksize+x)*reziscale)))*3+2];
769 b.data = blockbuffer;
770 b.len = xblocksize*yblocksize*3;
771 blocks[yy*xblocks+xx].compress(file, &b);
774 tag = swf_InsertTag(NULL, ST_SHOWFRAME);
775 filesize += swf_WriteTag(file, tag);
781 if(frame == lastframe)
786 destroydisplay(file);
788 tag = swf_InsertTag(NULL, ST_END);
789 filesize += swf_WriteTag(file, tag);
796 fi=fopen("tmp.swf", "r+");
798 fi=fopen(outputfilename, "r+");
802 fseek(fi,4,SEEK_SET);
804 f = filesize ;fwrite(&f,1,1,fi);
805 f = filesize >> 8 ;fwrite(&f,1,1,fi);
806 f = filesize >> 16;fwrite(&f,1,1,fi);
807 f = filesize >> 24;fwrite(&f,1,1,fi);
813 snprintf(buffer, 1024, "swfcombine -dz __tmp__.swf -o %s", outputfilename);
814 printf("%s\n", buffer);
816 sprintf(buffer, "rm __tmp__.swf");
817 printf("%s\n", buffer);