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;
62 #ifndef ST_DEFINEBITSJPEG
63 #define ST_DEFINEBITSJPEG 6
68 struct options_t options[] =
80 int args_callback_option(char*name,char*val)
82 if(!strcmp(name, "V")) {
83 printf("avi2swf - part of %s %s\n", PACKAGE, VERSION);
86 else if(!strcmp(name, "o")) {
90 else if(!strcmp(name, "n")) {
91 lastframe = atoi(val);
94 else if(!strcmp(name, "s")) {
95 firstframe = atoi(val);
98 else if(!strcmp(name, "p")) {
102 else if(!strcmp(name, "d")) {
103 scale = atoi(val)/100.0;
104 if(scale>1.0 || scale<=0) {
105 fprintf(stderr, "Scale must be in the range 1-100!\n");
110 else if(!strcmp(name, "z")) {
114 fprintf(stderr, "Unknown option: -%s\n", name);
117 int args_callback_longoption(char*name,char*val)
119 return args_long2shortoption(options, name, val);
121 void args_callback_usage(char*name)
123 printf("\nUsage: %s file.avi\n", name);
124 printf("\t-h , --help\t\t Print help and exit\n");
125 printf("\t-o , --output filename\t Specify output filename\n");
126 printf("\t-n , --num frames\t Number of frames to encode\n");
127 printf("\t-s , --start frame\t First frame to encode\n");
128 printf("\t-d , --scale factor\t Scale to factor percent\n");
129 printf("\t-p , --flip\t\t Turn movie upside down\n");
130 printf("\t-V , --version\t\t Print program version and exit\n");
133 int args_callback_command(char*name,char*val)
136 fprintf(stderr, "Only one file allowed. You supplied at least two. (%s and %s)\n",
143 /* id allocation/deallocation */
145 unsigned int idtab_pos=1;
148 while(idtab[idtab_pos] || !idtab_pos)
158 void makeshape(int file, int id, int gfxid, int width, int height)
167 tag = swf_InsertTag(NULL, ST_DEFINESHAPE);
169 rgb.b = rgb.g = rgb.r = 0xff;
171 ls = swf_ShapeAddLineStyle(s,20,&rgb);
172 swf_GetMatrix(NULL,&m);
176 fs = swf_ShapeAddBitmapFillStyle(s,&m,gfxid,0);
177 swf_SetU16(tag,id); // ID
184 swf_SetShapeStyles(tag,s);
185 swf_ShapeCountBits(s,NULL,NULL);
186 swf_SetShapeBits(tag,s);
188 swf_ShapeSetAll(tag,s,0,0,lines?ls:0,fs,0);
190 swf_ShapeSetLine(tag,s,width*20,0);
191 swf_ShapeSetLine(tag,s,0,height*20);
192 swf_ShapeSetLine(tag,s,-width*20,0);
193 swf_ShapeSetLine(tag,s,0,-height*20);
194 swf_ShapeSetEnd(tag);
195 filesize += swf_WriteTag(file, tag);
200 void setshape(int file,int id,int depth,int x,int y,CXFORM*cx)
204 m.sx = 0x10000; m.sy = 0x10000;
208 if(cx && !((cx->a0!=256)||(cx->r0!=256)||(cx->g0!=256)||(cx->b0!=256)
209 ||(cx->a1|cx->r1|cx->g1|cx->b1))) cx = 0;
210 tag = swf_InsertTag(NULL,ST_PLACEOBJECT2);
211 swf_ObjectPlace(tag,id,depth,&m,cx,0);
212 filesize += swf_WriteTag(file, tag);
220 // static int xblocksize;
221 // static int yblocksize;
234 class GfxBlockCache {
237 char*expire; //0=block's free
246 GfxBlockCache(int file)
249 size = xblocks*yblocks*cache_size;
250 printf("initializing cache (%d entries)\n", size);
251 list = new GfxBlock[size];
252 expire = new char[size];
254 memset(expire,0,size);
255 memset(list,0,sizeof(GfxBlock)*size);
256 memset(ids,0,sizeof(int)*size);
261 void insert(GfxBlock*block, int gfxid)
271 // cache full- don't insert item
275 free(list[pos].data);
277 //TODO: free this in the SWF, also
279 list[pos].data=(U8*)malloc(block->len);
280 memcpy(list[pos].data,block->data,block->len);
281 list[pos].len = block->len;
282 expire[pos] = cache_size;
285 int find(GfxBlock*block, CXFORM*cxform)
287 //TODO: do least square regression here to derive cxform
295 int t = (block->len);
296 U8*ptr1 = block->data;
297 U8*ptr2 = list[s].data;
299 // notice: we treat r,g,b as equal here.
301 int a = (*ptr1++)-(*ptr2++);
304 if(bestsum < 0 || bestsum > sum2) {
313 best = bestsum/block->len;
319 expire[bestid]= cache_size;
342 printf("destroying cache...\n");
344 printf("hits:%d (%02d%%)\n", hits, hits*100/(hits+misses));
345 printf("misses:%d (%02d%%)\n", misses, misses*100/(hits+misses));
348 if(expire[t] && list[t].data)
356 class GfxBlockEncoder {
364 void init(int depth, int posx,int posy, int sizex, int sizey)
366 this->basedepth = depth;
371 this->depth[0] = this->depth[1] = this->depth[2] = -1;
375 /* clear everything in the block */
381 tag = swf_InsertTag(NULL, ST_REMOVEOBJECT2);
382 swf_SetU16(tag, basedepth+t); //depth
383 filesize += swf_WriteTag(file, tag);
388 void writeiframe(int file, GfxBlock*block)
392 int gfxid = get_free_id();
393 int shapeid = get_free_id();
395 //memset(data,0,sizex*sizey*3);
396 TAG*tag = swf_InsertTag(NULL, ST_DEFINEBITS);
397 JPEGBITS * jb = swf_SetJPEGBitsStart(tag,sizex,sizey,jpeg_quality);
398 tag->len = 0; //bad hack
399 swf_SetU16(tag, gfxid);
402 swf_SetJPEGBitsLine(jb,&block->data[y*sizex*3]);
403 swf_SetJPEGBitsFinish(jb);
404 filesize += swf_WriteTag(file, tag);
407 cache->insert(block, shapeid);
409 makeshape(file, shapeid, gfxid, sizex, sizey);
410 setshape(file, shapeid, basedepth+1, posx, posy, 0);
413 void writereference(int file, int shapeid, CXFORM*form)
415 if(depth[1]!=shapeid)
418 setshape(file, shapeid, basedepth+1, posx, posy, form);
422 void compress(int file, GfxBlock*block)
425 int id = cache->find(block, &form);
427 writeiframe(file, block);
429 writereference(file, id, &form);
434 void initdisplay(int file)
440 for(t=0;t<xblocks;t++)
441 blocks[t].clear(file);
446 xblocksize = (width/3)&~7;
447 yblocksize = (height/2)&~7;
448 xblocks = width/xblocksize;
449 yblocks = height/yblocksize;
450 printf("%dx%d blocks of size %dx%d\n", xblocks,yblocks, xblocksize, yblocksize);
451 printf("cutting lower %d lines, right %d columns\n",
452 height-yblocks*yblocksize, width-xblocks*xblocksize);
453 blocks = new GfxBlockEncoder[xblocks*yblocks];
454 blockbuffer = new U8[xblocksize*yblocksize*4]; //should be 3
455 cache = new GfxBlockCache(file);
457 for(t=0;t<xblocks*yblocks;t++) {
459 (t%xblocks)*xblocksize,
460 (t/xblocks)*yblocksize,
461 xblocksize, yblocksize);
464 TAG*tag = swf_InsertTag(NULL, ST_JPEGTABLES);
465 JPEGBITS * jpeg = swf_SetJPEGBitsStart(tag, xblocksize, yblocksize, jpeg_quality);
466 filesize += swf_WriteTag(file, tag);
471 void destroydisplay(int file)
484 short int* sound_buffer;
488 IAviReadStream* astream;
491 unsigned samples_read, bytes_read;
493 short int tmpbuf[4096];
494 ret = astream->ReadFrames(tmpbuf, 4096*sizeof(short int),
495 4096, samples_read, bytes_read);
497 printf("couldn't read %d samples\n", mp3_block_size);
501 samples_read = bytes_read/sizeof(short int);
502 for(t=0;t<samples_read/2;t++) {
503 sound_buffer[write_pos+t] = tmpbuf[t*2];
505 write_pos += samples_read/2;
507 if(write_pos >= mp3_block_size*8)
509 if(write_pos > mp3_block_size*8)
510 memcpy(&sound_buffer[0],&sound_buffer[mp3_block_size*8],write_pos - mp3_block_size*8);
511 write_pos %= (mp3_block_size*8);
516 SoundReader(IAviReadStream*astream)
518 this->astream = astream;
521 this->mp3_block_size = 2304;
522 this->sound_buffer = new short int[mp3_block_size*16];
530 if(read_pos<=write_pos)
531 return write_pos-read_pos;
533 return (write_pos+mp3_block_size*8)-read_pos;
535 short int* readFrame()
538 while(available()<mp3_block_size) {
542 read_pos += mp3_block_size;
543 read_pos %= mp3_block_size*8;
544 return &sound_buffer[tmp];
549 static int mp3_block_size = 2304;
551 static int do_video = 1;
552 static int do_audio = 1;
554 int main (int argc,char ** argv)
557 IAviReadFile* player;
558 IAviReadStream* astream;
559 IAviReadStream* vstream;
561 double samplesperframe;
569 processargs(argc, argv);
570 lastframe += firstframe;
574 memset(idtab, 0, sizeof(idtab));
576 player = CreateIAviReadFile(filename);
577 astream = player->GetStream(0, AviStream::Audio);
578 vstream = player->GetStream(0, AviStream::Video);
585 int dwMicroSecPerFrame = 0;
586 player->GetFileHeader(&head);
587 printf("fps: %d\n", 1000000/head.dwMicroSecPerFrame);
588 printf("frames: %d\n", head.dwTotalFrames);
589 printf("streams: %d\n", head.dwStreams);
590 printf("width: %d\n", head.dwWidth);
591 printf("height: %d\n", head.dwHeight);
592 printf("sound: %u samples (%f seconds)\n", astream->GetEndPos(),
593 astream->GetEndTime());
594 oldwidth = head.dwWidth;
595 oldheight = head.dwHeight;
596 dwMicroSecPerFrame = head.dwMicroSecPerFrame;
597 samplesperframe = astream->GetEndPos()/astream->GetEndTime()*head.dwMicroSecPerFrame/1000000;
598 samplerate = (int)(astream->GetEndPos()/astream->GetEndTime());
599 fps = 1000000.0/dwMicroSecPerFrame;
601 StreamInfo*audioinfo;
602 StreamInfo*videoinfo;
605 videoinfo = vstream->GetStreamInfo();
606 oldwidth = videoinfo->GetVideoWidth();
607 oldheight = videoinfo->GetVideoHeight();
608 fps = (double)(videoinfo->GetFps());
613 audioinfo = astream->GetStreamInfo();
614 samplerate = audioinfo->GetAudioSamplesPerSec();
615 samplesperframe = audioinfo->GetAudioSamplesPerSec()/videoinfo->GetFps();
619 width = (int)(oldwidth*scale);
620 height = (int)(oldheight*scale);
623 vstream -> StartStreaming();
626 astream -> StartStreaming();
627 printf("%f framerate\n", fps);
628 printf("%f samples/frame\n", samplesperframe);
629 printf("%d samplerate\n", samplerate);
633 file = open("__tmp__.swf", O_WRONLY|O_CREAT|O_TRUNC, 0644);
635 file = open(outputfilename, O_WRONLY|O_CREAT|O_TRUNC, 0644);
637 memset(&swf, 0, sizeof(swf));
638 swf.frameRate = (int)(fps*256);
640 swf.fileSize = 0x0fffffff;
641 swf.frameCount = lastframe - firstframe;
648 filesize += swf_WriteHeader(file, &swf);
650 tag = swf_InsertTag(NULL, ST_SETBACKGROUNDCOLOR);
651 swf_SetU8(tag,0); //black
654 filesize += swf_WriteTag(file, tag);
657 tag = swf_InsertTag(NULL, ST_SOUNDSTREAMHEAD2);
658 swf_SetSoundStreamHead(tag, (int)samplesperframe/4);
659 filesize += swf_WriteTag(file, tag);
665 double movie_sound_pos = 0;
666 int mp3_sound_pos = 0;
671 astream->GetAudioFormatInfo(&wave,0);
673 printf("nChannels:%d\n", wave.nChannels);
674 printf("nSamplesPerSec:%d\n", wave.nSamplesPerSec);
675 printf("nAvgBytesPerSec:%d\n", wave.nAvgBytesPerSec);
676 printf("nBlockAlign:%d\n", wave.nBlockAlign);
677 printf("wBitsPerSample:%d\n", wave.wBitsPerSample);
678 printf("cbSize:%d\n", wave.cbSize);
681 SoundReader* sound = new SoundReader(astream);
684 if(vstream->ReadFrame()<0) {
689 if(frame < firstframe)
691 movie_sound_pos += samplesperframe;
693 while(mp3_sound_pos<movie_sound_pos) {
694 short int* samples = sound->readFrame();
695 mp3_sound_pos += mp3_block_size;
697 printf("\rskipping frame %d",frame);
700 if(frame == firstframe)
705 printf("\rconvert frame %d",frame);
709 movie_sound_pos += samplesperframe;
713 while(mp3_sound_pos<movie_sound_pos) {
714 // rawplay -s 44100 -f s16_le -c 2 samples.test
715 short int* samples = sound->readFrame();
718 if(first) { //first run
719 tag = swf_InsertTag(NULL, ST_SOUNDSTREAMBLOCK);
720 swf_SetSoundStreamBlock(tag, samples, 1);
722 swf_SetSoundStreamBlock(tag, samples, 0);
725 mp3_sound_pos += mp3_block_size;
727 if(mp3_sound_pos>=movie_sound_pos) { // last run
728 filesize += swf_WriteTag(file, tag);
736 CImage*img = vstream->GetFrame();
738 U8*data = img->Data();
739 int bpp = img->Bpp();
748 /* some movies have changing dimensions */
749 if(img->Width() != oldwidth ||
750 img->Height() != oldheight) {
752 oldwidth = img->Width();
753 oldheight = img->Height();
754 width = (int)(oldwidth*scale);
755 height = (int)(oldheight*scale);
759 for(yy=0;yy<yblocks;yy++)
760 for(xx=0;xx<xblocks;xx++)
763 for(y=0;y<yblocksize;y++) {
764 /* some avifile versions flip the image some don't. Maybe this is
765 even movie dependent. We just let the user decide which side's up. */
768 mydata = img->At(oldheight-(int)((yy*yblocksize+y)*reziscale));
770 mydata = img->At((int)((yy*yblocksize+y)*reziscale));
772 for(x=0;x<xblocksize;x++) {
773 blockbuffer[(y*xblocksize+x)*3+2] = mydata[((int)(((xx*xblocksize+x)*reziscale)))*3+0];
774 blockbuffer[(y*xblocksize+x)*3+1] = mydata[((int)(((xx*xblocksize+x)*reziscale)))*3+1];
775 blockbuffer[(y*xblocksize+x)*3+0] = mydata[((int)(((xx*xblocksize+x)*reziscale)))*3+2];
779 b.data = blockbuffer;
780 b.len = xblocksize*yblocksize*3;
781 blocks[yy*xblocks+xx].compress(file, &b);
784 tag = swf_InsertTag(NULL, ST_SHOWFRAME);
785 filesize += swf_WriteTag(file, tag);
791 if(frame == lastframe)
796 destroydisplay(file);
798 tag = swf_InsertTag(NULL, ST_END);
799 filesize += swf_WriteTag(file, tag);
806 fi=fopen("tmp.swf", "r+");
808 fi=fopen(outputfilename, "r+");
812 fseek(fi,4,SEEK_SET);
814 f = filesize ;fwrite(&f,1,1,fi);
815 f = filesize >> 8 ;fwrite(&f,1,1,fi);
816 f = filesize >> 16;fwrite(&f,1,1,fi);
817 f = filesize >> 24;fwrite(&f,1,1,fi);
823 snprintf(buffer, 1024, "swfcombine -dz __tmp__.swf -o %s", outputfilename);
824 printf("%s\n", buffer);
826 sprintf(buffer, "rm __tmp__.swf");
827 printf("%s\n", buffer);