예제 #1
0
/**
    \fn setupVideo
    \brief prepare video (copy or process)
*/
ADM_videoStream *admSaver::setupVideo(void)
{
    ADM_videoStream *video=NULL;
    // Video Stream
    if(!videoEncoderIndex) // Copy
    {
        aviInfo info;
        video_body->getVideoInfo(&info);

        uint8_t *extra;
        uint32_t extraLen;
        video_body->getExtraHeaderData(&extraLen,&extra);
//#warning do something better
        ADM_videoStreamCopy *copy=NULL;
        if(isH264Compatible(info.fcc))
        {
            if(muxer->preferH264AnnexB())
            {
                ADM_info("The video stream is H264\n");
                ADM_info("The muxer prefers AnnexB H264 bitstream\n");
            }
        }
        if(isH264Compatible(info.fcc) && !extraLen && !muxer->preferH264AnnexB())
        {
            ADM_info("Probably AnnexB bitstream\n");
            copy=new ADM_videoStreamCopyFromAnnexB(markerA,markerB);
        }else   
        {
            copy=new ADM_videoStreamCopy(markerA,markerB);
        }
        video=copy;
        // In that case, get the real time and update audio with it...
        // Because we might have go back in time to catch the first intra
        startAudioTime=copy->getStartTime();
      
        
    }else
    {
        // 1- create filter chain
        //******************************

        chain=createVideoFilterChain(markerA,markerB);
        if(!chain)
        {
                GUI_Error_HIG("Video","Cannot instantiante video Chain");
                return NULL;
        }
        // 2- Create Encoder
        //********************
        int sz=chain->size();
        ADM_assert(sz);
        ADM_coreVideoFilter  *last;
        last=(*chain)[sz-1]; // Grab last filter
        ADM_coreVideoEncoder *encoder=createVideoEncoderFromIndex(last,videoEncoderIndex,muxer->useGlobalHeader()); // FIXME GLOBAL HEADERS
        if(!encoder)
        {
           GUI_Error_HIG("Video","Cannot create encoder");
           return NULL;
        }
        // 3 dual Pass ?
        //*****************
        if(encoder->isDualPass())
        {
            encoder=handleFirstPass(encoder); // Do pass 1 and switch to pass 2
            if(!encoder)
            {
                printf("[Save] cannot create encoder for pass 2\n");
                return NULL;
            }
        }
        if(encoder->setup()==false)
        {
            GUI_Error_HIG("Video","Cannot setup codec. Bitrate too low ?");
            delete encoder;
            encoder=NULL;
            return NULL;
        }
        video= new ADM_videoStreamProcess(encoder);
        if(!video)
        {
                GUI_Error_HIG("Video","Cannot create encoder");
                delete encoder;
                return NULL;
        }
    }  
    return video;
}
예제 #2
0
bool muxerFlv::open(const char *file, ADM_videoStream *s,uint32_t nbAudioTrack,ADM_audioStream **a)
{
    uint32_t fcc=s->getFCC();
    bool r=true;
    char *fileTitle=NULL;

     if(fourCC::check(fcc,(uint8_t *)"FLV1") || isVP6Compatible(fcc))
     {

     }else
        {
            GUI_Error_HIG("Unsupported","Only FLV1 & VP6 supported for video");
            return false;
        }

    if(nbAudioTrack)
        for(int i=0;i<nbAudioTrack;i++)
        {
            uint32_t acc=a[i]->getInfo()->encoding;
            if(acc!=WAV_MP2 && acc!=WAV_MP3 && acc!=WAV_AAC)
            {
                GUI_Error_HIG("Unsupported","Only AAC & mpegaudio supported for audio");
                return false;
            }
            uint32_t fq=a[i]->getInfo()->frequency;
            if(fq!=44100 &&fq!=22050 && fq!=11025)
            {
                GUI_Error_HIG("Unsupported","Only 44.1, 22.050 and 11.025 kHz supported");
                return false;
            }


        }

    if(false==setupMuxer("flv",file))
    {
        printf("[FLV] Failed to open muxer\n");
        return false;
    }

   if(initVideo(s)==false)
    {
        printf("[FLV] Failed to init video\n");
        return false;
    }

    AVCodecContext *c = video_st->codec;
    AVDictionary *dict = NULL;

    rescaleFps(s->getAvgFps1000(),&(c->time_base));
    video_st->time_base=c->time_base;
    
    
    c->gop_size=15;

    if(initAudio(nbAudioTrack,a)==false)
    {
        printf("[FLV] Failed to init audio\n");
        return false;
    }

        int er=avio_open(&(oc->pb), file, AVIO_FLAG_WRITE);
        if (er)
        {
            ADM_error("[Flv]: Failed to open file :%s, er=%d\n",file,er);
            r=false;
            goto finish;
        }

		char buf[64];

        snprintf(buf, sizeof(buf), "%d", AV_TIME_BASE / 10);
        av_dict_set(&dict, "preload", buf, 0);
        av_dict_set(&dict, "max_delay", buf, 0);
		av_dict_set(&dict, "muxrate", "10080000", 0);

        if (avformat_write_header(oc, &dict) < 0)
        {
            printf("[Flv Muxer] Muxer rejected the parameters\n");
            r=false;
            goto finish;
        }
        initialized=true;
finish:
        vStream=s;
        aStreams=a;
        nbAStreams=nbAudioTrack;
        return r;
}
예제 #3
0
//_______________________________________________
uint8_t ADM_ogmWrite::save(const char *name)
{

uint8_t *bufr;
uint32_t len,flags;
uint8_t error=0;


		_fd=fopen(name,"wb");
		if(!_fd)
		{
                        GUI_Error_HIG(QT_TR_NOOP("File error"), QT_TR_NOOP("Cannot open \"%s\" for writing."), name);
			return 0;
		}

		videoStream=new ogm_page(_fd,1);
	
		encoding_gui=new DIA_encoding(25000);
                encoding_gui->setContainer("OGM");
		//______________ Write headers..._____________________
		
		if(!initVideo(name))
		{
			fclose(_fd);
			_fd=NULL;
                        GUI_Error_HIG(QT_TR_NOOP("Could not initialize video"), NULL);
			return 0;
		
		}
		if(!initAudio())
		{
			fclose(_fd);
			_fd=NULL;
                        GUI_Error_HIG(QT_TR_NOOP("Could not initialize audio"), NULL);
			return 0;
		
		}

		encoding_gui->setFps(_fps1000);
		encoding_gui->reset();
		// ___________________Then body_______________________
                uint32_t j=0;
		for( j=0;j<_togo && !error;j++)
		{
			if(!encoding_gui->isAlive())
			{
				error=1;
				continue;
			}
			if(!writeVideo(j)) error=1;
			if(!writeAudio(j)) error=1;
		}
                if(abs(j-_togo)<3 && error) error=0; // might be caused by late B frame
		delete encoding_gui;
		encoding_gui=NULL;
		//________________ Flush______________________
		videoStream->flush();
		endAudio();
		//deleteAudioFilters();
		// ____________Close____________________
		fclose(_fd);
		_fd=NULL;

	return !error;
}
예제 #4
0
//______________________________________
//
// Open and get the headears/index built
// along way
//______________________________________
uint8_t    OpenDMLHeader::open(const char *name)
{
uint8_t badAvi=0;
uint32_t rd;

	printf("** opening OpenDML files **");	
        
	_fd=fopen(name,"rb");
	if(!_fd)
	{
		printf("\n cannot open %s \n",name);
		return 0;
	}
        myName=ADM_strdup(name);
#define CLR(x)              memset(& x,0,sizeof(  x));

              CLR( _videostream);
              CLR( _mainaviheader);
	      _isvideopresent=1;
	      _isaudiopresent=0;    	     	      	 	      
	      
		_nbTrack=0;
		riffParser *parser=new riffParser(name);
		
		if(MKFCC('R','I','F','F')!=(rd=parser->read32()))
			{
				printf("Not riff\n");badAvi=1;
				printf("%lx != %lx\n",rd,MKFCC('R','I','F','F'));
			}
		parser->read32();
		if(MKFCC('A','V','I',' ')!=parser->read32())
			{
				printf("Not Avi\n");badAvi=1;
			}
		
		if(!badAvi)
			{
				walk(parser);	
			
			}					
		delete parser;
		aprintf("Found %d tracks\n:-----------\n",_nbTrack);
		// check if it looks like a correct avi
		if(!_nbTrack) badAvi=1;
		
		// if we are up to here -> good avi :)
		if(badAvi)
		{
			printf("FAIL\n");
			return 0;
		}
		// now read up each parts...
		//____________________________
		
#ifdef __WIN32
                
#define DUMP_TRACK(i) aprintf(" at %I64u (%I64x) size : %I64u (%I64x)\n", \
                                _Tracks[i].strh.offset,\
                                _Tracks[i].strh.offset,\
                                _Tracks[i].strh.size,\
                                _Tracks[i].strh.size);

#else
                
#define DUMP_TRACK(i) aprintf(" at %llu (%llx) size : %llu (%llx)\n", \
				_Tracks[i].strh.offset,\
				_Tracks[i].strh.offset,\
				_Tracks[i].strh.size,\
				_Tracks[i].strh.size);
#endif								
		for(uint32_t i=0;i<_nbTrack;i++)
		{
			DUMP_TRACK(i);		
		}		
		
		uint32_t vidTrack=0xff;
		// search wich track is the video one
		// and load it to _videoheader
		
		for(uint32_t i=0;i<_nbTrack;i++)
		{
			fseeko(_fd,_Tracks[i].strh.offset,SEEK_SET);
			if(_Tracks[i].strh.size!=sizeof(_videostream))
			{
				printf("Mmm(1) we have a bogey here, size mismatch : %"LLU"\n",_Tracks[i].strh.size);
				printf("expected %d\n",sizeof(_videostream));
				if(_Tracks[i].strh.size<sizeof(_videostream)-8) // RECT is not mandatory
				{
                                  GUI_Error_HIG(QT_TR_NOOP("Malformed header"), NULL);
					return 0;
				}		
				printf("Trying to continue anyway\n");			
			}
			fread(&_videostream,sizeof(_videostream),1,_fd);
#ifdef ADM_BIG_ENDIAN
				Endian_AviStreamHeader(&_videostream);
#endif
			if(_videostream.fccType==MKFCC('v','i','d','s'))
				{
					vidTrack=i;
					printf("Video track is %ld\n",i);
					break;
				}		
		}
		if(0xff==vidTrack)
		{
			printf("Could not identify video track!");
			return 0;
		}
		
		// STOP HERE -> Alex <-
		//return 0;
		// STOP HERE -> Alex <-
		
		
		
									

		// then bih stuff
		int32_t extra;
//		_fd=fopen(name,"rb");
		
		fseeko(_fd,_Tracks[vidTrack].strf.offset,SEEK_SET);		
		extra=_Tracks[vidTrack].strf.size-sizeof(_video_bih);
		if(extra<0)
		{	
			printf("bih is not big enough (%lu/%lu)!\n",_Tracks[vidTrack].strf.size,sizeof(_video_bih));
			return 0;
		}
		fread(&_video_bih,sizeof(_video_bih),1,_fd);
#ifdef ADM_BIG_ENDIAN
		Endian_BitMapInfo(&_video_bih);
#endif
		if(extra>0)
		{				
			_videoExtraLen=extra;		
			_videoExtraData=new uint8_t [extra];
			fread(_videoExtraData,extra,1,_fd);
		}
		_isvideopresent=1;
		//--------------------------------------------------
		//	Read audio trak info, select if there is
		//	several
		//--------------------------------------------------
		// and audio track
		if(_mainaviheader.dwStreams>=2)
		{
			// which one is the audio track, is there several ?
			if(!(_nbAudioTracks=countAudioTrack()))
                        {
                                printf("Weird, there is no audio track, but more than one stream...\n");
                        }			
                        else
                        {
                          uint32_t run=0,audio=0;
                          odmlAudioTrack *track;

                          _audioTracks=new odmlAudioTrack[_nbAudioTracks]; 
                          while(audio<_nbAudioTracks)
                          {
                                        ADM_assert(run<_nbTrack);

                                        track=&(_audioTracks[audio]);
                                        fseeko(_fd,_Tracks[run].strh.offset,SEEK_SET);
                                        if(_Tracks[run].strh.size != sizeof(_audiostream))
                                        {
                                                printf("Mmm(2) we have a bogey here, size mismatch : %"LLU"\n",_Tracks[run].strh.size);
                                                printf("expected %d\n",sizeof(_audiostream));
                                                if(_Tracks[run].strh.size<sizeof(_audiostream)-8)
                                                {
                                                  GUI_Error_HIG(QT_TR_NOOP("Malformed header"), NULL);
                                                        return 0;
                                                }
                                                printf("Trying to continue anyway\n");			
                                        }
                                        fread(track->avistream,sizeof(_audiostream),1,_fd);
#ifdef ADM_BIG_ENDIAN
                                        Endian_AviStreamHeader(track->avistream);
#endif
                                        if(track->avistream->fccType!=MKFCC('a','u','d','s'))
                                        {	
                                                printf("Not an audio track!\n");
                                                run++;
                                                continue;
                                        }
                                        // now read extra stuff
                                        fseeko(_fd,_Tracks[run].strf.offset,SEEK_SET);		
                                        extra=_Tracks[run].strf.size-sizeof(WAVHeader);
                                        if(extra<0)
                                        {	
                                                printf("WavHeader is not big enough (%lu/%lu)!\n",
                                                _Tracks[run].strf.size,sizeof(WAVHeader));
                                                return 0;
                                        }
                                        fread(track->wavHeader,sizeof(WAVHeader),1,_fd);				
#ifdef ADM_BIG_ENDIAN
                                        Endian_WavHeader(track->wavHeader);
#endif
                                        if(extra>2)
                                        {
                                                fgetc(_fd);fgetc(_fd);
                                                extra-=2;
                                                track->extraDataLen=extra;		
                                                track->extraData=new uint8_t [extra];
                                                fread(track->extraData,extra,1,_fd);
                                        }
                                        track->trackNum=run;
                                        audio++;
                                        run++;
                           }	
                        }
                }
		
		// now look at the index stuff
		// there could be 3 cases:
		// 1- It is a openDML index, meta index  + several smaller index
		// 2- It is a legacy index (type 1 , most common)
		// 3- It is a broken index or no index at all
		//
		// If it is a openDML index we will find a "indx" field in the Tracks
		// Else we will find it in _regularIndex Track
		// Since openDML often also have a regular index we will try open DML first
		
		uint8_t ret=0;
		Dump();
		
		// take the size of riff header and actual file size
		uint64_t riffSize;
		fseeko(_fd,0,SEEK_END);		
		_fileSize=ftello(_fd);
		fseeko(_fd,0,SEEK_SET);
		read32();
		riffSize=(uint64_t )read32();
				
		
		// 1st case, we have an avi < 4 Gb
		// potentially avi type 1	
#if 0	
		if((_fileSize<4*1024*1024*1024LL)&&
                	// if riff size is ~ fileSize try regular index
			 (abs(riffSize-_fileSize)<1024*1024))
#endif

#define HAS(x) if(x) printf(#x" : yes\n"); else printf(#x" : no\n");
                // If there is no openDML index
                HAS( _regularIndex.offset);
                HAS( _Tracks[vidTrack].indx.offset);
                if(!ret && _regularIndex.offset &&!_Tracks[vidTrack].indx.offset) 
        // try regular avi if a idx1 field is there (avi index)
                        ret=indexRegular(vidTrack);

                if (!ret && _Tracks[vidTrack].indx.offset)	// Try openDML if a index field is there (openDML)
                        ret=indexODML(vidTrack);
                if(!ret) 
                {
                        printf("Could not index it properly...\n");
                        return 0;

                }
                if(!_nbAudioTracks)
                {
                         _isaudiopresent=0;
                }
                else
                {
                        // build audio stream
                        odmlAudioTrack *track;
                        // Check it is not a weird DV file
                        if(fourCC::check(_video_bih.biCompression,(uint8_t *)"dvsd"))
                        {
                             for(int i=0;i<_nbAudioTracks;i++)
                             {
                                    track=&(_audioTracks[i]);
                                    WAVHeader *hdr=  track->wavHeader;
                                    if(!hdr->frequency)
                                    {
                                            printf("Fixing audio track to be PCM\n");
                                            hdr->frequency=48000;
                                            //hdr->channels=2;
                                            hdr->byterate=48000*hdr->channels*2;
                                            hdr->blockalign=2*hdr->channels;
                                    }
                             }

                        }
                        for(int i=0;i<_nbAudioTracks;i++)
                        {
                                track=&(_audioTracks[i]);
                                _audioTracks[i].track= new AVDMAviAudioStream(track->index,
                                                track->nbChunks,
                                                myName,
                                                track->wavHeader,
                                                0,
                                                track->extraDataLen,track->extraData);
                        }
                }
                if(!_video_bih.biCompression && fourCC::check(_videostream.fccHandler,(uint8_t*)"DIB "))
                  {
                        _videostream.fccHandler=_video_bih.biCompression=fourCC::get((uint8_t*)"DIB ");
                  }
                else
                _videostream.fccHandler=_video_bih.biCompression;
                printf("\nOpenDML file successfully read..\n");
                return ret;
}
예제 #5
0
/**
    \fn initializeAudio
    \brief Initialize audio
*/
bool  GUIPlayback::initializeAudio(void)

{
    uint32_t state,latency, preload;
    uint32_t small_;
    uint32_t channels,frequency;

    wavbuf = 0;
    uint64_t startPts=firstPts;
    int32_t shift=0; // unit is ms, + => delay audio, -=> advance audio
    
    // if audio shift is activated, take it into account
    //
    EditableAudioTrack *ed=video_body->getDefaultEditableAudioTrack();
    if(!ed)
        return false;
    if(ed->audioEncodingConfig.shiftEnabled)
        shift=ed->audioEncodingConfig.shiftInMs;
    playbackAudio = createPlaybackFilter(startPts,shift);
    if(!playbackAudio) 
    {
        ADM_info("No audio\n");
        return false;
    }

    channels= playbackAudio->getInfo()->channels;
    frequency=playbackAudio->getInfo()->frequency;
    preload=  (frequency * channels)/5;	// 200 ms preload
    // 4 sec buffer..
    wavbuf =  (float *)  ADM_alloc((20*sizeof(float)*preload)); // 4 secs buffers
    ADM_assert(wavbuf);
    // Read a at least one block to have the proper channel mapping
    uint32_t fill=0;
    AUD_Status status;
    small_ = playbackAudio->fill(channels, wavbuf,&status);
    fill+=small_;
    // Call it twice to be sure it is properly setup
     state = AVDM_AudioSetup(frequency,  channels ,playbackAudio->getChannelMapping());
     AVDM_AudioClose();
     state = AVDM_AudioSetup(frequency,  channels ,playbackAudio->getChannelMapping());
     latency=AVDM_GetLayencyMs();
     printf("[Playback] Latency : %d ms\n",latency);
     audioLatency=latency; // ms -> us
      if (!state)
      {
          GUI_Error_HIG(QT_TR_NOOP("Trouble initializing audio device"), NULL);
          cleanupAudio();
          return false;
      }
    while(fill<preload)
    {
      if (!(small_ = playbackAudio->fill(preload-fill, wavbuf+fill,&status)))
      {
        break;
      }
      fill+=small_;
    }
    nbSamplesSent = fill/channels;  // In sample
    AVDM_AudioPlay(wavbuf, fill);
    // Let audio latency sets in...
    ticktock.reset();
    uint32_t slice=(frequency * channels)/100; // 10 ms
    // pump data until latency is over
    updateVu();
    #if 0
    while(ticktock.getElapsedMS()<latency)
    {
        if(AVDM_getMsFullness()<AUDIO_PRELOAD)
        {
          if (!(small_ = playbackAudio->fill(slice, wavbuf,&status)))
          {
            printf("[Playback] Compensating for latency failed\n");
            break;
          }
          AVDM_AudioPlay(wavbuf, slice);
        }
       ADM_usleep(10*1000);
       updateVu();
    }
    #endif
    printf("[Playback] Latency is now %u\n",ticktock.getElapsedMS());
    return true;
}
예제 #6
0
//______________________________________
//
// Open and index the (small) h263
//
//______________________________________
uint8_t    h263Header::open(char *name)
{
	uint32_t w,h,res=255,nbImg=0;
	uint32_t word;
	uint32_t delta;
	uint32_t pts;
	uint32_t last_pts=0;
	uint32_t i=0;
	uint32_t pos=0;
	uint8_t intra=0;//,size;

	_fd=fopen(name,"rb");
	if(!_fd) return 0;

	// first pass to scan  # of frame
	// ___________________________________
	bitsReader *parser=new bitsReader();

	if(!parser->open(name))
			{
				printf("\n error parsing h263\n");
				delete parser;
				return 0;
			}
	while( parser->sync())
	{
		parser->read(8,&pts);
		parser->read(8,&word);
		delta=256+pts-last_pts;
		delta &=0xff;
		if(!nbImg) delta=0;
		if(((word&0xc0)==0x80) && ( delta<MAX_DELTA))
		{
			last_pts=pts;
			nbImg++;
		}
	}

	printf("\n Pass1 over \n\n");
	printf("\n Found : %ld frames \n",nbImg);
	delete parser;parser=NULL;

	parser=new bitsReader();
	if(!parser->open(name))
			{
				printf("\n error parsing h263\n");
				delete parser;
				return 0;
			}
	_idx=new h263Entry[nbImg+1];
	ADM_assert(_idx);

	last_pts=0;
	nbImg=0;
	// second pass, index it
	//___________________
	while( parser->sync())
	{

		parser->read(8,&pts);
		parser->read(8,&word);
		delta=256+pts-last_pts;
		delta &=0xff;
		if(!nbImg) delta=0;
		//++++++++++++++PTYPE++++++++++++
		if(((word&0xc0)==0x80) && ( abs(delta)<MAX_DELTA))
		{
		last_pts=pts;
		nbImg++;
		pos=parser->getPos()-5;
#ifdef H263_VERBOSE
		printf("\n[+PSC+] at 0x%x\n",pos);
		printf("[-TR--] %x\n",pts);
		printf("[PTYPE] %04x \n",word);
#endif	
		if(word&0x40) printf("\t Split Screen\n");
		if(word&0x20) printf("\t Document Camera indicator \n");
		if(word&0x10) printf("\t Full Picture Freeze Release \n");
		word&=7;
		printf ("%s",resolution[word]);
		res=word;
		if(word!=7) // no extended
			{
	
				if(parser->read1bit()) 
				{
					printf("\tInter\n");intra=0;
				}
				else
				{
					printf("\tIntra\n");intra=1;
				}
			//	TWOPT("\tINTER\n","\tINTRA\n");
				ONEOPT("\tUnrestricted MV\n");
				ONEOPT("\tSAC MV\n");
				ONEOPT("\tAdv prediction mode (4mv)\n");
				ONEOPT("\tPB frames\n");
			}	
		else
			{ // ------------------OPPTYPE---------------------
		  	parser->read(3,&word);
		  	printf("\t\t UFEP: %lx\n",word);
		  	if(word==1)
		  	{
		  		parser->read(3,&word);
				printf ("%s",resolution[word]);
				res=word;
				ONEOPT("\t\t custom PCF\n");
				ONEOPT("\t\t UMV \n");
				ONEOPT("\t\t SAC \n");
				ONEOPT("\t\t ADV Pred \n");
				ONEOPT("\t\t AIC \n");
				ONEOPT("\t\t Deblocking \n");
				ONEOPT("\t\t Slice \n");
				ONEOPT("\t\t RPS \n");
				ONEOPT("\t\t ISD \n");
				ONEOPT("\t\t Altern Intra VLC \n");
				ONEOPT("\t\t Modified Qz  \n");
				parser->read(4,&word);
				if(word!=0x8) printf("\t\t **OOPS\n");
	
		   	}
		  	parser->read(3,&word);
		  	printf("%s",frameType[word]);
				ONEOPT("\t\t RPR \n");
				ONEOPT("\t\t RRU \n");
				ONEOPT("\t\t RType \n");
				ONEOPT("\t\t error (1) \n");
				ONEOPT("\t\t error (3) \n");
				if(!parser->read1bit()) printf("\t\t error (2) \n");
		  	}
	
			if(i)
					{
						_idx[i-1].size=pos-_idx[i-1].offset;
					}
				_idx[i].offset=pos;
				_idx[i].intra=intra;
				printf(" Frame %ld at %lx intra :%d\n",i,pos,intra);
				i++;
		}
	}
	//
	//		Now build header info
	//
	switch(res)
	{
		default:
			printf("\n incorrect size !\n");
                        GUI_Error_HIG(QT_TR_NOOP("Size is not (s)QCIF"), NULL);
		
		case 1:  w=128;h=96;break;
		case 2:  w=176;h=144;break;
			
	}
	_idx[0].intra=1;
 	_isaudiopresent=0; // Remove audio ATM
       	_isvideopresent=1; // Remove audio ATM
		
#define CLR(x)              memset(& x,0,sizeof(  x));

              CLR( _videostream);
              CLR(  _mainaviheader);

    	      _videostream.dwScale=1;
              _videostream.dwRate=25;
              _mainaviheader.dwMicroSecPerFrame=40000;;     // 25 fps hard coded
              _videostream.fccType=fourCC::get((uint8_t *)"vids");
              _video_bih.biBitCount=24;
              _videostream.fccHandler=0;
              _videostream.dwLength= _mainaviheader.dwTotalFrames=nbImg;
              _videostream.dwInitialFrames= 0;
              _videostream.dwStart= 0;
              _video_bih.biWidth=_mainaviheader.dwWidth=w ;
              _video_bih.biHeight=_mainaviheader.dwHeight=h;
              _videostream.fccHandler=fourCC::get((uint8_t *)"H263"); 
	      _video_bih.biCompression=_videostream.fccHandler;

	
	return 1;
}
예제 #7
0
uint8_t prepareDualPass(uint32_t bufferSize,uint8_t *buffer,char *TwoPassLogFile,DIA_encoding *encoding_gui,Encoder *_encode,uint32_t total)
{
      uint32_t len, flag;
      FILE *tmp;
      uint8_t reuse=0,r;
      ADMBitstream bitstream(0);
      uint32_t prefill=0;
      uint32_t sent=0;
      
        aprintf("\n** Dual pass encoding**\n");

        if((tmp=fopen(TwoPassLogFile,"rt")))
        {
                fclose(tmp);
                if(GUI_Question(QT_TR_NOOP("\n Reuse the existing log-file ?")))
                {
                        reuse=1;
                }
        }
        
        if(!reuse)
        {
        
                encoding_gui->setPhasis ("1st Pass");
                aprintf("**Pass 1:%lu\n",total);
                _encode->startPass1 ();
                bitstream.data=buffer;
                bitstream.bufferSize=bufferSize;
                
preFilling2:
             bitstream.cleanup(0);
             if(!_encode->encode ( prefill, &bitstream))//&len, videoBuffer, &flags,&displayFrame))
             {
                        printf("MP4:First frame error\n");
                        GUI_Error_HIG (QT_TR_NOOP("Error while encoding"), NULL);
                        return 0;
              }
              sent++;
              if(!bitstream.len)
              {
                prefill++;
                goto preFilling2;
              }

                printf("Pass 1 prefill : %u\n",prefill);
                for (uint32_t cf = 1; cf < total; cf++)
                {
                        if (!encoding_gui->isAlive())
                        {
                                abt:
                                    GUI_Error_HIG (QT_TR_NOOP("Aborting"), NULL);
                                return 0;
                        }
                        bitstream.cleanup(cf);
                        if(!prefill || cf+prefill<total) 
                        {
                            r=_encode->encode ( prefill+cf, &bitstream);
                        }
                          else
                          {
                              r=_encode->encode ( total-1, &bitstream);
                          }
                        if (!r)
                        {
                                printf("\n Encoding of frame %lu failed !\n",cf);
                                return 0;
                        }
                        sent++;
                        encoding_gui->setFrame(cf,bitstream.len,bitstream.out_quantizer,total);
                }
                encoding_gui->reset();
                aprintf("**Pass 1:done\n");
        }// End of reuse

        if(!_encode->startPass2 ())
        {
                printf("Pass2 ignition failed\n");
                return 0;
        }
        printf("First pass : send %u frames\n",sent);
        encoding_gui->setPhasis ("2nd Pass");
        return 1;
}
//****************************************************************
uint8_t
mpegWritter::dopass2 (const char *name, char *statname, uint32_t final_size, uint32_t bitrate, ADM_MPEGTYPE mpegtype, int matrix, uint8_t interlaced, uint8_t bff,	// WLA
		      uint8_t widescreen)
{
  int intra, q;
  uint32_t size;
  AVDMGenericVideoStream *incoming;

  FILE *fd = NULL;
  uint64_t total_size = 0;
  uint32_t len, flags, type, outquant, audiolen;
  uint32_t sample_target = 0;
  double sample_time;
  ADMBitstream bitstream;

  memset (quantstat, 0, 32);

  incoming = getLastVideoFilter (frameStart, frameEnd - frameStart);
  if (!_audio)
    {
      if (!(fd = qfopen (name, "wb")))
	return 0;
    }

//      if(!init(name,mpegtype,interlaced,widescreen))
  if (!init (name, mpegtype, interlaced, bff, widescreen))	// WLA
    {
      printf ("Mpeg2 init failed\n");
      return 0;
    }
  printf ("\n mpeg2enc init done \n");

  ADM_assert (aImage);
  ADM_assert (_buffer_out);
  encoding->reset ();
  encoding->setFrame (0, _total);

/*-------------------- Pass 1 over, go to pass 2 --------------------------------*/

  ADM_assert (_ratecontrol->startPass2 (final_size, _total));

  encoding->setPhasis ("2nd Pass");
  q = 2;

  //mpegvbr.maxAllowedBitrate=(bitrate*1000)>>3;//(bitrate*1000)>>3;
  //mpegvbr.maxAllowedBitrate=(9000*1000)>>3; // enable stuff in xvid


//->
  switch (mpegtype)
    {
    case ADM_SVCD:

      Mpeg2encSVCD * dec;
      dec = new Mpeg2encSVCD (_w, _h);
      dec->setMatrix (matrix);
//                              dec->init(q,bitrate,_fps1000,interlaced,widescreen);
      dec->init (q, bitrate, _fps1000, interlaced, bff, widescreen, 0);	// WLA
      _codec = dec;
      encoding->setCodec ("SVCD");
      printf ("Svcd  max bitrate : %d\n", bitrate);
      break;
    case ADM_DVD:
      {

	Mpeg2encDVD *dec;
	dec = new Mpeg2encDVD (_w, _h);
	dec->setMatrix (matrix);
//                      dec->init(q,bitrate,_fps1000,interlaced,widescreen);
	dec->init (q, bitrate, _fps1000, interlaced, bff, widescreen, 0);	// WLA
	_codec = dec;
	printf ("DVD  max bitrate : %d\n", bitrate);
	encoding->setCodec ("DVD");
      }
      break;
    default:
      ADM_assert (0);
      break;
    }
  encoding->setPhasis ("2nd Pass");
  if (_muxer)
    {
      encoding->
	setAudioCodec (getStrFromAudioCodec (_audio->getInfo ()->encoding));
      sample_time = _total;
      sample_time *= 1000;
      sample_time /= _fps1000;	// target_time in second
      sample_time *= _audio->getInfo ()->frequency;
      sample_target = (uint32_t) floor (sample_time);
    }
  bitstream.data = _buffer_out;
  for (uint32_t i = 0; i < _total; i++)
    {
      if (!incoming->getFrameNumberNoAlloc (i, &size, aImage, &flags))
	{
          GUI_Error_HIG (_("Encoding error"), NULL);
	  if (!_audio)
	    qfclose (fd);
	  end ();
	  return 0;
	}
      encoding->setFrame (i, _total);

      if (i < MPEG_PREFILL)
	{

	  _codec->encode (aImage, &bitstream);	//_buffer_out , &len,&flags,&outquant);   
	  quantstat[bitstream.out_quantizer]++;
	  continue;
	}
     	// Set
      //
      ADM_rframe ftype, ztype;
      uint32_t qz;
      ADM_assert (_ratecontrol->getQz (&qz, &ztype));
      q = qz;
      //_codec->setQuantize(q);
      bitstream.in_quantizer = q;
      _codec->encode (aImage, &bitstream);	//_buffer_out , &len,&flags,&outquant);
      quantstat[bitstream.out_quantizer]++;
      encoding->setQuant (bitstream.out_quantizer);

      switch (bitstream.flags)
	{
	case AVI_KEY_FRAME:
	  ftype = RF_I;
	  break;
	case AVI_B_FRAME:
	  ftype = RF_B;
	  break;
	default:
	  ftype = RF_P;
	  break;
	}
      if (ftype != ztype)
	{
	  printf ("**Frame type does not match %d %d\n", ztype, ftype);
	}
      //aprintf("inquant  : %02d outquant %02d Intra %d size :%d flags %x\n",
      //              q,outquant,intra,len,flags);
      ADM_assert (_ratecontrol->
		  logPass2 (bitstream.out_quantizer, ftype, bitstream.len));
      total_size += bitstream.len;
      encoding->feedFrame (bitstream.len);
      if (!_muxer)
	{
	  qfwrite (_buffer_out, bitstream.len, 1, fd);
	  fflush (fd);
	}
      else
	{

	  // write video
	  _muxer->writeVideoPacket (&bitstream);

	  PACK_AUDIO;
	}



      if (!encoding->isAlive ())
	{
	  print_quant_stat (name);
	  end ();
	  qfclose (fd);
	  return 0;
	}
    }

//--
// flush queue
  for (uint32_t i = 0; i < MPEG_PREFILL; i++)
    {

      ADM_rframe ftype;
      uint32_t qz;
      ADM_assert (_ratecontrol->getQz (&qz, &ftype));
      q = qz;
      //_codec->setQuantize(q);
      bitstream.in_quantizer = q;
      _codec->encode (aImage, &bitstream);	//_buffer_out , &len,&flags,&outquant);
      quantstat[bitstream.out_quantizer]++;
      encoding->setQuant (bitstream.out_quantizer);
      switch (bitstream.flags)
	{
	case AVI_KEY_FRAME:
	  ftype = RF_I;
	  break;
	case AVI_B_FRAME:
	  ftype = RF_B;
	  break;
	default:
	  ftype = RF_P;
	  break;
	}
      //aprintf("inquant  : %02d outquant %02d Intra %d size :%d flags %x\n",
      //                      q,outquant,intra,len,flags);
      ADM_assert (_ratecontrol->
		  logPass2 (bitstream.out_quantizer, ftype, bitstream.len));

      total_size += bitstream.len;
      if (!_muxer)
	{
	  qfwrite (_buffer_out, bitstream.len, 1, fd);
	  fflush (fd);
	}
      else
	{
	  // write video
            _muxer->writeVideoPacket (&bitstream);
	  PACK_AUDIO;

	}

      //      printf("\n pipe opened %ld\n",i);
      encoding->feedFrame (bitstream.len);	// Set
      encoding->setQuant (bitstream.out_quantizer);
      encoding->setFrame (i, MPEG_PREFILL);

    }
//--                    
  if (!_muxer)
    qfclose (fd);
  else
    {
      _muxer->close ();
      delete _muxer;
      _muxer = NULL;
    }

  print_quant_stat (name);
  end ();
  return 1;
}
//________________________________________________
uint8_t	ADM_ogmWriteProcess::initVideo(const char *name)
{		
uint32_t w,h,fps1000,fcc;
		
	_incoming = getLastVideoFilter (frameStart,frameEnd-frameStart);
 	_togo=_incoming->getInfo()->nb_frames;
  	_encode = getVideoEncoder (_incoming->getInfo()->width,_incoming->getInfo()->height);
	if (!_encode)
    		return 0;
 	
	TwoPassLogFile=new char[strlen(name)+6];
  	strcpy(TwoPassLogFile,name);
  	strcat(TwoPassLogFile,".stat"); 	  
   
 	_encode->setLogFile(TwoPassLogFile,_togo);
	
  	if (!_encode->configure (_incoming))
    	{
      		delete 	_encode;
      		_encode = NULL;
      		GUI_Error_HIG ("Filter init failed", NULL);
      		return 0;
    	};
 	w= _incoming->getInfo ()->width;
	h=_incoming->getInfo ()->height;
	fps1000=_incoming->getInfo ()->fps1000;
	_fps1000=fps1000;
	fcc= fourCC::get((uint8_t *)_encode->getCodecName());
   	_videoBuffer=new uint8_t[w*h*3];
  	encoding_gui->setCodec(_encode->getDisplayName());
   
//-----------------------VBR--------------------------------------
	if (_encode->isDualPass ())
	{
		uint8_t *buffer;
		uint32_t len, flag;
		FILE *tmp;
		uint8_t reuse=0;

		aprintf("\n** Dual pass encoding**\n");

		if((tmp=fopen(TwoPassLogFile,"rt")))
		{
			fclose(tmp);
			if(GUI_Question("\n Reuse the existing log-file ?"))
			{
				reuse=1;
			}
		}
	
		if(!reuse)
 		{
      			aprintf("**Pass 1:%lu\n",_togo);
      			_encode->startPass1 ();
			encoding_gui->setCodec((char *)_encode->getCodecName());
			encoding_gui->setPhasis("Pass one");
      			//__________________________________
      			//   now go to main loop.....
      			//__________________________________
      			for (uint32_t cf = 0; cf < _togo; cf++)
			{	  
	  			if (!_encode->encode (cf, &len, _videoBuffer, &flag))
				{
					printf("\n Encoding of frame %lu failed !\n",cf);
	    				return 0;
				}
				encoding_gui->feedFrame(len);
				encoding_gui->setFrame(cf,_togo);
				encoding_gui->setQuant(_encode->getLastQz());
				if(!encoding_gui->isAlive())
				{
					return 0;
				}
			}
		     	aprintf("**Pass 1:done\n");
    		}// End of reuse

      		if(!_encode->startPass2 ())
		{
      			printf("Pass2 ignition failed\n");
      			return 0;
		}
		encoding_gui->setPhasis("Pass 2");
	}   //-------------------------/VBR-----------------------------------
	else
	{
		encoding_gui->setPhasis("Encoding");
	}
  // init save avi

// now we build the new stream !
    	aprintf("**main pass:\n");


		stream_header header;
		int64_t dur64;
		uint32_t dur32;
		uint16_t dur16;
		
		memset(&header,0,sizeof(header));
		
		memcpy(&(header.streamtype),"video\0\0\0",8);
		MEMCPY(&(header.subtype),&fcc,4);
		
		//header.size=sizeof(header);
		dur32=sizeof(header);
		MEMCPY(&header.size,&dur32,4);
		MEMCPY(&(header.video.width),&w,4);
		MEMCPY(&(header.video.height),&h,4);
		// Timing ..
		double duration; // duration in 10us
		duration=fps1000;
		duration=1000./duration;
		duration*=1000*1000;
		duration*=10;
		
		dur64=(int64_t)duration;
		
		MEMCPY(&header.time_unit,&dur64,8);
		dur64=1;
		MEMCPY(&header.samples_per_unit,&dur64,8);
		
		dur32=0x10000;
		MEMCPY(&header.buffersize,&dur32,4);
		
		dur16=24;
		MEMCPY(&header.bits_per_sample,&dur16,2);
		
		
		//header.default_len=1;
		dur32=1;
		MEMCPY(&header.default_len,&dur32,4);
		
		return videoStream->writeHeaders(sizeof(header),(uint8_t *)&header); // +4 ?

}
예제 #10
0
/*-------------------------------------------------------------------------------------------------------------------*/
uint8_t
mpegWritter::save_dualpass (const char *name, uint32_t final_size, uint32_t bitrate, ADM_MPEGTYPE mpegtype, int matrix, uint8_t interlaced, uint8_t bff,	// WLA
			    uint8_t widescreen)
{
  AVDMGenericVideoStream *incoming;
  char *statname;
  uint32_t reuse = 0;

  incoming = getLastVideoFilter (frameStart, frameEnd - frameStart);
  _w = incoming->getInfo ()->width;
  _h = incoming->getInfo ()->height;
  _page = _w * _h;
  _page += _page >> 1;
  _fps1000 = incoming->getInfo ()->fps1000;
  _total = incoming->getInfo ()->nb_frames;
  if (!_total)
    return 0;
  //_buffer       =new uint8_t[_w*_h*2];
  aImage = new ADMImage (_w, _h);
  _buffer_out = new uint8_t[_w * _h * 2];


  statname = new char[strlen (name) + 4 + 1];
  strcpy (statname, name);
  strcat (statname, ".st");
  printf ("Matrix : %d\n\n", matrix);
  encoding = new DIA_encoding (_fps1000);
  encoding->setPhasis ("Encoding");


  // check if stat file exists ?
#if 1				//ndef CYG_MANGLING
  {
    FILE *fd;
    fd = fopen (statname, "rt");
    if (fd)
      {
	fclose (fd);
	prefs->get (FEATURE_REUSE_2PASS_LOG, (uint32_t *) & reuse);
        if (!reuse && GUI_Question (_("Reuse log file ?")))
	  reuse = 1;
      }
  }
#endif
  //_ratecontrol=new ADM_oldXvidRc(_fps1000,statname);
  _ratecontrol = new ADM_newXvidRc (_fps1000, statname);

#if 1
  if (!reuse)
//      if(!dopass1(name,statname,final_size,bitrate,mpegtype,matrix,interlaced,widescreen))
    if (!dopass1
	(name, statname, final_size, bitrate, mpegtype, matrix, interlaced,
	 bff, widescreen))
      // WLA
      {
	delete encoding;
        GUI_Error_HIG (_("Error in pass 1"), NULL);
	delete[]statname;
	return 0;
      }
#endif
//      if(!dopass2(name,statname,final_size,bitrate,mpegtype,matrix,interlaced,widescreen))
  if (!dopass2
      (name, statname, final_size, bitrate, mpegtype, matrix, interlaced, bff,
       widescreen))
    // WLA
    {
      delete encoding;
      GUI_Error_HIG (_("Error in pass 2"), NULL);
      delete[]statname;
      return 0;
    }
  delete encoding;
  delete[]statname;
  return 1;
}
예제 #11
0
/*-------------------------------------------------------------------------------------------------------*/
uint8_t
mpegWritter::dopass1 (const char *name, char *statname, uint32_t final_size, uint32_t bitrate, ADM_MPEGTYPE mpegtype, int matrix, uint8_t interlaced, uint8_t bff,	// WLA
		      uint8_t widescreen)
{
  uint32_t size;
  AVDMGenericVideoStream *incoming;

  FILE *fd;
  uint64_t total_size = 0;
//uint32_t                                              len,flags,type,outquant;
  float br;
  uint32_t avg, flags;

  int intra, q;
  ADMBitstream bitstream;



  incoming = getLastVideoFilter (frameStart, frameEnd - frameStart);

//      if(!init(name,mpegtype,interlaced,widescreen)) return 0;
  if (!init (name, mpegtype, interlaced, bff, widescreen))
    return 0;			// WLA
  printf ("\n mpeg2enc init done \n");

  ADM_assert (aImage);
  ADM_assert (_buffer_out);

  q = 2;			// q=2
  encoding->setPhasis ("1st Pass");
  bitrate = 0;			// we dont care in pass 1 ...



  ADM_assert (_ratecontrol->startPass1 ());

  switch (mpegtype)
    {
    case ADM_SVCD:
      Mpeg2encSVCD * dec;
      dec = new Mpeg2encSVCD (_w, _h);
      dec->setMatrix (matrix);
#ifdef ADM_1PASS_CBR
      dec->disablePadding ();
      //dec->init(qz,bitrate,_fps1000,interlaced,widescreen); 
//                              dec->init(0,avg*1000,_fps1000,interlaced,widescreen);
      dec->init (0, avg * 1000, _fps1000, interlaced, bff, widescreen, 1);	// WLA
#else
//                              dec->init(q,0,_fps1000,interlaced,widescreen);
      dec->init (q, 0, _fps1000, interlaced, bff, widescreen, 1);	// WLA
#endif
      // 6 Megabits should be enough
      //dec->init(0,avg,_fps1000); // 6 Megabits should be enough
      _codec = dec;
      encoding->setCodec ("SVCD");
      break;
    case ADM_DVD:
      {

	Mpeg2encDVD *dec;
	dec = new Mpeg2encDVD (_w, _h);
	dec->setMatrix (matrix);

#ifdef ADM_1PASS_CBR
	dec->disablePadding ();
//                                              dec->init(0,avg*1000,_fps1000,interlaced,widescreen);
	dec->init (0, avg * 1000, _fps1000, interlaced, bff, widescreen, 1);	// WLA
#else
//                              dec->init(q,0,_fps1000,interlaced,widescreen);
	dec->init (q, 0, _fps1000, interlaced, bff, widescreen, 1);	// WLA
#endif
	_codec = dec;
	encoding->setCodec ("DVD");;
      }
      break;
    default:
      ADM_assert (0);
      break;
    }

  encoding->setFrame (0, _total);
  bitstream.data = _buffer_out;
  for (uint32_t i = 0; i < _total; i++)
    {
      
      if (!incoming->getFrameNumberNoAlloc (i, &size, aImage, &flags))
	{
          GUI_Error_HIG (_("Encoding error"), NULL);
	  end ();
	  return 0;
	}
      if (i < MPEG_PREFILL)
	{
	  bitstream.cleanup (i);
	  bitstream.in_quantizer=q;
	  _codec->encode (aImage, &bitstream);
	  //_buffer_out , &len,&flags,&outquant);
	  continue;
	}
      bitstream.cleanup (i);
      _codec->encode (aImage, &bitstream);	//_buffer_out , &len,&flags,&outquant);
      total_size += bitstream.len;


//              aprintf("inquant  : %02d outquant :%02d Intra %d, len %lu\n",q,outquant,intra,len);

      ADM_rframe ftype;
      switch (bitstream.flags)
	{
	case AVI_KEY_FRAME:
	  ftype = RF_I;
	  break;
	case AVI_B_FRAME:
	  ftype = RF_B;
	  break;
	default:
	  ftype = RF_P;
	  break;
	}

      ADM_assert (_ratecontrol->
		  logPass1 (bitstream.out_quantizer, ftype, bitstream.len));

      encoding->setFrame (i, _total);
      encoding->setQuant (bitstream.out_quantizer);
      encoding->feedFrame (bitstream.len);
      if (!encoding->isAlive ())
	{
	  end ();
	  return 0;
	}
    }
  // flush queue
  for (uint32_t i = 0; i < MPEG_PREFILL; i++)
    {
        bitstream.cleanup (i);
      _codec->encode (aImage, &bitstream);	//_buffer_out , &len,&flags,&outquant);
      total_size += bitstream.len;


      aprintf ("inquant  : %02d outquant :%02d Intra %d\n", q,
	       bitstream.out_quantizer, intra);

      ADM_rframe ftype;
      switch (bitstream.flags)
	{
	case AVI_KEY_FRAME:
	  ftype = RF_I;
	  break;
	case AVI_B_FRAME:
	  ftype = RF_B;
	  break;
	default:
	  ftype = RF_P;
	  break;
	}
      ADM_assert (_ratecontrol->
		  logPass1 (bitstream.out_quantizer, ftype, bitstream.len));

      encoding->setFrame (i, MPEG_PREFILL);
      encoding->setQuant (bitstream.out_quantizer);
      encoding->feedFrame (bitstream.len);

    }
  // flush queue
  delete _codec;
  _codec = NULL;

  return 1;
}
예제 #12
0
/*
	Save as with the external mpeg2enc

*/
uint8_t
mpegWritter::save_regular (const char *name, ADM_MPEGTYPE mpegtype, int qz, int bitrate, int matrix, uint8_t interlaced, uint8_t bff,	// WLA
			   uint8_t widescreen)
{
  uint32_t size;
  AVDMGenericVideoStream *incoming;

  FILE *fd = NULL;
  uint64_t total_size = 0;
  uint32_t len, flags;
  uint32_t outquant;
  uint32_t audiolen = 0;
  DIA_encoding *encoding;
  uint32_t sample_target = 0;
  double sample_time;
  ADMBitstream bitstream;
  incoming = getLastVideoFilter (frameStart, frameEnd - frameStart);
  _total = incoming->getInfo ()->nb_frames;
  _fps1000 = incoming->getInfo ()->fps1000;
  if (!_total)
    {
      GUI_Error_HIG (_("No frames to encode"),
                     _("Please check markers. Is \"A>\" == \">B\"?"));
      return 0;
    }

  printf ("Br:%d, qz:%d\n", bitrate, qz);
  if (!_audio)
    {
      if (!(fd = qfopen (name, "wb")))
	return 0;
    }
  else
    {
      ADM_assert (_muxer);
      sample_time = _total;
      sample_time *= 1000;
      sample_time /= _fps1000;	// target_time in second
      sample_time *= _audio->getInfo ()->frequency;
      sample_target = (uint32_t) floor (sample_time);

    }


  _w = incoming->getInfo ()->width;
  _h = incoming->getInfo ()->height;


  _page = _w * _h;
  _page += _page >> 1;

//                      if(!init(name,ADM_VCD,interlaced,widescreen)) return 0;
  if (!init (name, ADM_VCD, interlaced, bff, widescreen))
    return 0;			//WLA
  printf ("\n mpeg2enc init done \n");


  //_buffer       =new uint8_t[_w*_h*2];
  aImage = new ADMImage (_w, _h);
  _buffer_out = new uint8_t[_w * _h * 2];

  ADM_assert (aImage);
  ADM_assert (_buffer_out);

  encoding = new DIA_encoding (_fps1000);

  encoding->setPhasis ("Encoding.");
  encoding->setFrame (0, _total);
//      printf("Br:%d, qz:%d\n",bitrate,qz);

  switch (mpegtype)
    {
    case ADM_VCD:
      {
	encoding->setCodec ("VCD.");
	Mpeg2encVCD *dec;
	dec = new Mpeg2encVCD (_w, _h);
//                                      dec->init(1,0,_fps1000,interlaced,widescreen);
	dec->init (1, 0, _fps1000, interlaced, bff, widescreen, 0);	// WLA
	_codec = dec;
      }
      break;
    case ADM_SVCD:

      Mpeg2encSVCD * dec;
      dec = new Mpeg2encSVCD (_w, _h);
      dec->setMatrix (matrix);
//                                      dec->init(qz,bitrate,_fps1000,interlaced,widescreen);
      dec->init (qz, bitrate, _fps1000, interlaced, bff, widescreen, 0);
      // WLA
      _codec = dec;
      encoding->setCodec ("SVCD.");

      break;

    case ADM_DVD:
      {
	Mpeg2encDVD *dec;
	dec = new Mpeg2encDVD (_w, _h);
	dec->setMatrix (matrix);
//                                      dec->init(qz,bitrate,_fps1000,interlaced,widescreen);
	dec->init (qz, bitrate, _fps1000, interlaced, bff, widescreen, 0);
	// WLA
	_codec = dec;
	encoding->setCodec ("DVD.");

      }
      break;
    default:
      ADM_assert (0);
    }

  printf ("\n--encoding started--\n");
  if (_muxer)
    {
      if (audioProcessMode ())
	encoding->
	  setAudioCodec (getStrFromAudioCodec (_audio->getInfo ()->encoding));
      else
	encoding->setAudioCodec ("Copy");
      switch (_outputAs)
	{

	case MUXER_TS:
	  encoding->setContainer ("Mpeg TS");
	  break;
	case MUXER_VCD:
	  encoding->setContainer ("Mpeg VCD");
	  break;
	case MUXER_SVCD:
	  encoding->setContainer ("Mpeg SVCD");
	  break;
	case MUXER_DVD:
	  encoding->setContainer ("Mpeg DVD");
	  break;
	default:
	  ADM_assert (0);
	}

    }
  else
    encoding->setContainer ("Mpeg ES");
  bitstream.data = _buffer_out;
  for (uint32_t i = 0; i < _total; i++)
    {
      if (!incoming->getFrameNumberNoAlloc (i, &size, aImage, &flags))
	{
	  delete encoding;
          GUI_Error_HIG (_("Encoding error"), NULL);
	  if (fd)
	    qfclose (fd);
	  end ();
	  return 0;
	}
      bitstream.cleanup (i);
      bitstream.in_quantizer=0;
      _codec->encode (aImage, &bitstream);
      //_buffer_out , &len,&flags,&outquant);
      total_size += bitstream.len;
      encoding->feedFrame (bitstream.len);
      encoding->setQuant (bitstream.out_quantizer);
      encoding->setFrame (i, _total);
      // Null frame are only possible
      // when in prefill state for mpeg-X
      if (!len)
	continue;
      if (_muxer)
	{
#warning FIXME
#warning FIXME
#warning FIXME
#warning FIXME
	  _muxer->writeVideoPacket (&bitstream);
	  PACK_AUDIO;

	}
      else
	{
            qfwrite (_buffer_out, bitstream.len, 1, fd);
	  fflush (fd);
	}

      aprintf (" outquant %02d  size :%d flags %x\n", outquant, len, flags);

      if (!encoding->isAlive ())
	{
	  delete encoding;
	  end ();
	  if (fd)
	    qfclose (fd);
	  return 0;
	}
    }
  encoding->setPhasis ("Finishing");
  bitstream.data = _buffer_out;
  for (uint32_t i = 0; i < MPEG_PREFILL; i++)
    {
      bitstream.cleanup (i);
      _codec->encode (aImage, &bitstream);	//_buffer_out , &len,&flags);
      total_size += bitstream.len;
      encoding->feedFrame (bitstream.len);
      if (!_muxer)
          qfwrite (_buffer_out, bitstream.len, 1, fd);
      else
	{
            _muxer->writeVideoPacket (&bitstream);
	  PACK_AUDIO;
	}

      //      printf("\n pipe opened %ld\n",i);
      encoding->setFrame (i, _total);

    }
  delete encoding;

  if (!_muxer)
    qfclose (fd);
  else
    {
      _muxer->close ();
      delete _muxer;
      _muxer = NULL;
      deleteAudioFilter (_audio);
      _audio = NULL;
    }
  end ();
  return 1;

}
예제 #13
0
int A_Save(const char *name)
{
uint32_t end;
int ret=0;
	// depending on the type we save a avi, a mpeg or a XVCD
	CodecFamilty family;
	family= videoCodecGetFamily();
	// in case of copy mode, we stick to avi file format
	if(!videoProcessMode())
	{
		family=CodecFamilyAVI;
		if( UI_GetCurrentFormat()==ADM_PS ||UI_GetCurrentFormat()==ADM_TS )  // exception
		{
			family=CodecFamilyMpeg;
		}
                        
	}
        else
        {
                if(UI_GetCurrentFormat()==ADM_AVI_DUAL)
                {
                  GUI_Error_HIG(QT_TR_NOOP("Dual audio can only be used in copy mode"),QT_TR_NOOP( "Select Copy as the video codec."));
                        return 0;
                }
        }
	printf("**saving:**\n");
	// Check if we need to do a sanity B frame check
	if(!videoProcessMode())
	{	
		uint32_t pb;
		end=avifileinfo->nb_frames;
		// if the last frame is the last frame (!)
		// we add one to keep it, else we systematically skip
		// the last frame
#if 0					
		if(frameEnd==end-1) end=frameEnd+1;
		else
			end=frameEnd;

		if(!video_body->sanityCheckRef(frameStart,end,&pb))
		{
			if(pb)
			{
				GUI_Error_HIG("Cannot save the file", "The video starts/ends with a lonely B-frame. Please remove it.");
				return 0;
			}
			if(!GUI_Question("Warning !\n Bframe has lost its reference frame\nContinue ?"))
				return 0;
		}
#endif
		// Alter frameEnd so that it is not a B frame	
		// as frameEnd -1 position	
		uint32_t tgt=frameEnd;;
		uint32_t flag=0,found=0;
		
		// need to do something ?
		if(frameEnd>frameStart)
		{
			tgt=frameEnd;
			if(tgt==end-1) tgt++;
			video_body->getFlags(tgt-1,&flag);
			if((frameEnd&AVI_B_FRAME))
			{
				printf("Last frame is a B frame, choosing better candidate\n");
				 // The last real one is not a I/P Frame
				 // Go forward or rewind
				 if(tgt<end-1)
				{	// Try next if possible
					video_body->getFlags(tgt,&flag);
					if(!(flag&AVI_B_FRAME))
					{
						printf("Taking next frame as last frame %lu\n",tgt+1);
				 		frameEnd=tgt+1;
				 		found=1;
					}
				}
				if(!found) // next frame not possible, rewind
				{
					if(tgt>=end-2) tgt=end-2;
					while(tgt>frameStart)
					{
						printf("Trying :%lu\n",tgt);
						video_body->getFlags(tgt,&flag);
						if(!(flag&AVI_B_FRAME))
						{
							printf("Taking previous frame as last frame %lu\n",tgt+1);
				 			frameEnd=tgt+1;
				 			found=1;
							break;
						}
						else tgt--;
					}
				}
				ADM_assert(found);
			}
		}
		
		
		
	}
        printf("Output format:%d\n",UI_GetCurrentFormat());
	switch(family)
	{
		case CodecFamilyAVI:
					printf(" AVI family\n");
					switch(UI_GetCurrentFormat())
					{
						case ADM_DUMMY:
					                            			ret=oplug_dummy(name);
					                            			break;
						case ADM_FLV:
                            			ret=oplug_flv(name);
                            			break;
                        case ADM_MP4:
                        case ADM_PSP:
                        case ADM_MATROSKA:
                        
                                                    ret=oplug_mp4(name,UI_GetCurrentFormat());
                                                    break;
						case ADM_AVI:
								ret=A_SaveAudioNVideo(name);
								break;
						case ADM_OGM:
								ret=ogmSave(name);
								break;
						case ADM_ES:
								ret=ADM_saveRaw(name);
								break;
						case ADM_AVI_DUAL:
								ret=A_SaveAudioDualAudio(name);
								break;
                                                case ADM_AVI_PAK:
								ret=A_SavePackedVop(name);
								break;

						case ADM_AVI_UNP:
								ret=A_SaveUnpackedVop(name);
								break;
						default:
                                                  GUI_Error_HIG(QT_TR_NOOP("Incompatible output format"), NULL);
					}
					break;
		case CodecFamilyMpeg:
					printf(" MPEG family\n");
					if(!videoProcessMode())
					{
						
						printf("Using pass through\n");
                                                switch(UI_GetCurrentFormat())
                                                {
                                                  case ADM_PS:
                                                  case ADM_TS:
						          ret=mpeg_passthrough(name,UI_GetCurrentFormat());
                                                          break;
                                                  default:
                                                    GUI_Error_HIG(QT_TR_NOOP("Incompatible output format"), NULL);
                                                }
                                                break;
                                        } // THERE IS NO BREAK HERE, NOT A MISTAKE!
		case CodecFamilyXVCD:
                    switch(UI_GetCurrentFormat())
                    {
                        case ADM_TS:
                        case ADM_PS:
                        case ADM_ES:
                                ret=oplug_mpegff(name,UI_GetCurrentFormat());;
                                break;
                        default:
                          GUI_Error_HIG(QT_TR_NOOP("Incompatible output format"), NULL);
                    }
                    break;
                default:
                            ADM_assert(0);
                            return 0;
        }
        getFirstVideoFilter(0,avifileinfo->nb_frames);
        return ret;
}
예제 #14
0
bool admSaver::save(void)
{


    int ret=false;
    
    
    ADM_info("Audio starting time %s\n",ADM_us2plain(startAudioTime));
    ADM_info("[A_Save] Saving..\n");
    
    const char *defaultExtension=ADM_MuxerGetDefaultExtension(muxerIndex);
    EditableAudioTrack *ed=NULL;
    ADM_info("Muxer default extension %s\n",defaultExtension);
    if(!videoEncoderIndex) 
    {
        if(false==video_body-> checkCutsAreOnIntra())
        {
            if(!GUI_Question("The video is in copy mode but the cut points are not on keyframes.\n"
                            "The video will be saved but there will corruption at cut point(s).\n"
                             "Do you want to continue anyway ?"))
            {
                return false;
            }
        }
    }

    if(!(muxer=ADM_MuxerSpawnFromIndex(muxerIndex)))
    {
        GUI_Error_HIG("Muxer","Cannot instantiante muxer");
        return 0;
    }
     
    ADM_videoStream *video=setupVideo();
    if(!video)
    {
        return false;
    }
    // adjust audio starting time
     for(int i=0;i<nbAudioTracks;i++)
        {
            ADM_audioStream  *stream=video_body->getAudioStreamAt(i);
            stream->goToTime(startAudioTime);
        }
    if(false==setupAudio())
    {
        if(video) delete video;
        if(muxer) delete muxer;
        muxer=NULL;
        return false;
    }
   
    // Check if we need to add an extension....
    if(defaultExtension)
    {
        if(!strstr(fileName.c_str(),"."))
        {
            
            fileName=fileName+std::string(".")+std::string(defaultExtension);
            ADM_info("Adding extension, filename is now %s\n",fileName.c_str());
        }

    }
    if(!muxer->open(fileName.c_str(),video,nbAudioTracks,audioAccess))
    {
        GUI_Error_HIG("Muxer","Cannot open ");
    }else
    {
        ret=muxer->save();
        muxer->close();
    }
abort123:
    if(video)
        delete video;
    video=NULL;
    for(int i=0;i<nbAudioTracks;i++)
    {
        delete audioAccess[i];
        audioAccess[i]=NULL;
    }
    return ret;
}
/**
    \fn saveAsBmp
    \brief save current image into filename, into bmp format
*/
bool  ADMImage::saveAsBmp(const char *filename)
{
  ADM_BITMAPFILEHEADER bmfh;
  ADM_BITMAPINFOHEADER bmph;
  FILE *fd;
  uint32_t sz;
  uint16_t s16;
  uint32_t s32;

  sz = _width* _height * 3;

  bmfh.bfReserved1 = bmfh.bfReserved2 = 0;
  bmfh.bfOffBits = sizeof (bmfh) + sizeof (bmph);
//_________________________________________
  bmph.biSize = sizeof (bmph);
  bmph.biWidth = _width;
  bmph.biHeight = _height;
  bmph.biPlanes = 1;
  bmph.biBitCount = 24;
  bmph.biCompression = 0;	// COMPRESSION NONE
  bmph.biSizeImage = sz;
  bmph.biXPelsPerMeter = 0;
  bmph.biYPelsPerMeter = 0;
  bmph.biClrUsed = 0;
  bmph.biClrImportant = 0;
/*
	bmph.resolutionUnits=0;
	bmph.origin=0;
	bmph.colorEncoding=0;
*/

  ADMImageDefault image(_width,_height);


  printf ("\n %u x %u=%u\n", bmph.biWidth, bmph.biHeight, sz);

  uint8_t *out;

        out=(uint8_t *)ADM_alloc(sz);
        if(!out)
        {
            GUI_Error_HIG(QT_TR_NOOP("Memory error"), NULL);
//            ADM_dealloc(out);
            return 0;
        }
        ADMColorScalerSimple converter(bmph.biWidth, bmph.biHeight, ADM_COLOR_YV12,ADM_COLOR_RGB24);
        converter.convertImage(this,out);
        uint32_t ww=bmph.biWidth;
        uint32_t hh=bmph.biHeight;
        uint8_t *swap = new uint8_t[ww*3];
        uint8_t *up=out;
        uint8_t *down=out+(hh-1)*ww*3;
        
        for(int y=0;y<hh>>1;y++)
        {
            SwapMe(swap,up,ww); 
            SwapMe(up,down,ww);
            memcpy( down,swap,ww*3);
            down-=3*ww;
            up+=3*ww;
        }

		delete [] swap;

        fd = ADM_fopen (filename, "wb");
        if (!fd)
        {
                GUI_Error_HIG (QT_TR_NOOP("Something bad happened"), NULL);
                ADM_dealloc(out);
                return 0;
        }

	// Bitmpap file header, not using tructure due to gcc padding it
#ifdef ADM_BIG_ENDIAN
	s16 = 0x424D;
#else
  	s16 = 0x4D42;
#endif
  	s32 = 14 + sizeof (bmph) + sz;
#ifdef ADM_BIG_ENDIAN
	#define SWAP32(x) x=R32(x)
#else
	#define SWAP32(x) ;
#endif
        SWAP32(s32);
        fwrite (&s16, 2, 1, fd);
        fwrite (&s32, 4, 1, fd);
        s32 = 0;
        fwrite (&s32, 4, 1, fd);
        s32 = 14 + sizeof (bmph);
        SWAP32(s32);
        fwrite (&s32, 4, 1, fd);
#ifdef ADM_BIG_ENDIAN
	Endian_BitMapInfo(&bmph);
#endif
        fwrite (&bmph, sizeof (bmph), 1, fd);
        fwrite (out, sz, 1, fd);

        fclose(fd);
        ADM_dealloc(out);
        return 1;
}
예제 #16
0
/**
    \fn open
*/
uint8_t avsHeader::open(const char *name)
{
   
    if(!network.bindMe(9999))
    {
        printf("[avsProxy]Open failed\n");
        return 0;
    }
    // now time to grab some info
    avsInfo info;
    avsNetPacket in,out;
    out.buffer=(uint8_t *)&info;
    out.sizeMax=sizeof(info);
    out.size=0;
    typedef struct 
    {
        uint32_t ver;
        uint32_t api;
    }version;
    version v={AVSHEADER_API_VERSION,6};
    in.buffer=(uint8_t *)&v;
    in.size=sizeof(v);
    in.sizeMax=sizeof(v);

    if(!network.command(AvsCmd_GetInfo,0,&in,&out))
    {
        printf("Get info failed\n");
        return 0;   
    }
    // Dump some info
#define PINFO(x) printf(#x":%d\n",info.x);
    PINFO( version);
	PINFO( width);
	PINFO( height);
	PINFO( fps1000);
	PINFO( nbFrames);
	PINFO( frequency);
	PINFO( channels);
    // Build header..
    _isaudiopresent = 0;	// Remove audio ATM
    _isvideopresent = 1;	// Remove audio ATM

#define CLR(x)              memset(& x,0,sizeof(  x));

    if(!info.width || !info.fps1000 || !info.height)
    {
        ADM_error("Wrong width/height/fps\n");
        return false;
    }
    if(info.version!=AVSHEADER_API_VERSION)
    {
        GUI_Error_HIG("","Wrong API version, expected %d, got %d\n",AVSHEADER_API_VERSION,info.version);
        return false;
    }

    CLR(_videostream);
    CLR(_mainaviheader);

    _videostream.dwScale = 1000;
    _videostream.dwRate = info.fps1000;
    _mainaviheader.dwMicroSecPerFrame = 40000;;	// 25 fps hard coded
    _videostream.fccType = fourCC::get((uint8_t *) "YV12");

    _video_bih.biBitCount = 24;

    _videostream.dwLength = _mainaviheader.dwTotalFrames = info.nbFrames;
    _videostream.dwInitialFrames = 0;
    _videostream.dwStart = 0;
    //
    //_video_bih.biCompression= 24;
    //
    _video_bih.biWidth = _mainaviheader.dwWidth = info.width;
    _video_bih.biHeight = _mainaviheader.dwHeight = info.height;
    _video_bih.biCompression = _videostream.fccHandler =  fourCC::get((uint8_t *) "YV12");
   
    //
    if(info.frequency)
    {
        wavHeader.frequency=info.frequency;
        wavHeader.channels=info.channels;
        wavHeader.bitspersample=16;
        wavHeader.blockalign=info.channels*2;
        wavHeader.byterate=info.frequency*2*info.channels;
        wavHeader.encoding=WAV_PCM;
        audioAccess=new ADM_avsAccess(&network,&wavHeader,10000);
        _isaudiopresent=1;
        if(audioAccess)
            audioStream=ADM_audioCreateStream(&wavHeader,audioAccess);
        if(audioStream)
        {
            ADM_info("Created audio stream\n");
            haveAudio=true;
        }
        else
            ADM_warning("Error when creating audio stream\n");
    }
    printf("Connection to avsproxy succeed\n");
    return 1;
}
/**
    \fn saveAsBmp
    \brief save current image into filename, into bmp format
*/
uint8_t  ADMImage::saveAsBmp(const char *filename)
{
  BITMAPFILEHEADER bmfh;
  BITMAPINFOHEADER bmph;
  FILE *fd;
  uint32_t sz;
  uint16_t s16;
  uint32_t s32;
  
  sz = _width* _height * 3;

  bmfh.bfReserved1 = bmfh.bfReserved2 = 0;
  bmfh.bfOffBits = sizeof (bmfh) + sizeof (bmph);
//_________________________________________
  bmph.biSize = sizeof (bmph);
  bmph.biWidth = _width;
  bmph.biHeight = _height;
  bmph.biPlanes = 1;
  bmph.biBitCount = 24;
  bmph.biCompression = 0;	// COMPRESSION NONE
  bmph.biSizeImage = sz;
  bmph.biXPelsPerMeter = 0;
  bmph.biYPelsPerMeter = 0;
  bmph.biClrUsed = 0;
  bmph.biClrImportant = 0;
/*
	bmph.resolutionUnits=0;
	bmph.origin=0;
	bmph.colorEncoding=0;
*/

  ADMImage image(_width,_height);
  

  printf ("\n %u x %u=%u\n", bmph.biWidth, bmph.biHeight, sz);

  uint8_t *out;

        out=(uint8_t *)ADM_alloc(sz);
        if(!out)
        {
            GUI_Error_HIG(QT_TR_NOOP("Memory error"), NULL);
//            ADM_dealloc(out);
            return 0;
        }

        if(!COL_yv12rgbBMP(bmph.biWidth, bmph.biHeight,data, out))
        {
              GUI_Error_HIG(QT_TR_NOOP("Error converting to BMP"), NULL);
              ADM_dealloc(out);
              return 0;
        }
        fd = fopen (filename, "wb");
        if (!fd)
        {
                GUI_Error_HIG (QT_TR_NOOP("Something bad happened"), NULL);
                ADM_dealloc(out);
                return 0;
        }

	// Bitmpap file header, not using tructure due to gcc padding it
#ifdef ADM_BIG_ENDIAN
	s16 = 0x424D;
#else	
  	s16 = 0x4D42;
#endif	
  	s32 = 14 + sizeof (bmph) + sz;
#ifdef ADM_BIG_ENDIAN	
	#define SWAP32(x) x=R32(x)	
#else
	#define SWAP32(x) ; 
#endif
        SWAP32(s32);	
        fwrite (&s16, 2, 1, fd);
        fwrite (&s32, 4, 1, fd);
        s32 = 0;
        fwrite (&s32, 4, 1, fd);
        s32 = 14 + sizeof (bmph);
        SWAP32(s32);
        fwrite (&s32, 4, 1, fd);
#ifdef ADM_BIG_ENDIAN
	Endian_BitMapInfo(&bmph);
#endif
        fwrite (&bmph, sizeof (bmph), 1, fd);
        fwrite (out, sz, 1, fd);
  
        fclose(fd);
        ADM_dealloc(out);
        return 1;
}
//**********************************************
uint8_t ADM_vob2vobsub(char *nameVob, char *nameVobSub, char *nameIfo)
{
   dmx_demuxerPS *demuxer=NULL;
   DIA_working *working=NULL;
   MPEG_TRACK track;
   FILE *indexFile=NULL;
   FILE *indexSub=NULL;
   uint32_t palette[16],width,height;
   uint64_t abs,rel,size,pts;
   int blockSize;
   uint8_t *data,stream;
   char *subname;
   double percent;
   uint32_t packetLen,usedLen,read;
   OneTrack allIndex[MAX_LANGUAGE];
   char language[MAX_LANGUAGE*4];
#ifdef  TEST_V2V  
   nameIfo="d:/Crime/VTS_01_0.IFO";
   nameVobSub="toto.idx";
#endif
   
        printf("v2v: Ifo:%s Vob:%s Vsub:%s\n",nameIfo,nameVob,nameVobSub);

   memset(language,0,sizeof(language));
   memset(palette,0,sizeof(uint32_t)*16);
   if(!vobsub_parse_ifo(nameIfo,palette,&width,&height,language))
   {
     GUI_Error_HIG(QT_TR_NOOP("Ifo error"),QT_TR_NOOP("Error reading ifo file, aborting."));   
        return 0;
   } 
   printf("Ifo: %d x %d\n",width,height);                 
   
   indexFile=fopen(nameVobSub,"wt");
   if(!indexFile)
   {
     GUI_Error_HIG(QT_TR_NOOP("Cannot write .idx"),NULL);              
        return 0;
    }
   subname=ADM_strdup(nameVobSub);
   size=strlen(subname);
   subname[size-3]='s';
   subname[size-2]='u';
   subname[size-1]='b';
   indexSub=fopen(subname,"wb");
   ADM_dealloc(subname);
    if(!indexSub)
    {
        fclose(indexFile);
        GUI_Error_HIG(QT_TR_NOOP("Cannot write .sub"),NULL);
        return 0;
    }
   for(int i=0;i<MAX_LANGUAGE;i++)
   {
         allIndex[i].setLang(language+i*3);  
   }
   track.pes=0x20;
   track.pid=track.pes;
   demuxer=new  dmx_demuxerPS(1,&track,1);
   if(!demuxer->open(nameVob))
   {
     GUI_Error_HIG(QT_TR_NOOP("Problem opening the mpeg files"),NULL);
        delete demuxer;
        fclose(indexFile);
        fclose(indexSub);
        return 0;   
   }
   
   
   size=demuxer->getSize();
   
    int display=0;
    
   dumpHeader(indexFile,0,width,height,palette);
   working=new DIA_working(QT_TR_NOOP("Generating VobSub file"));
   
   //*** Main Loop ***
   uint32_t startPts=0,lastPts=0;
   uint16_t hh,mm,ss,ms;
   uint32_t timestamp;
   while(1)
   {
       if(!demuxer->forceRefill(&stream)) goto _abt;
       demuxer->getPos(&abs,&rel);
       display++;
       if(display>20)
       {
        working->update(abs>>10,size>>10);
        display=0;
       }
#ifdef TEST_V2V       
       //if(abs>200*1024*1024) break;
#endif       
       if(stream>=0x20 && stream<0x20+MAX_LANGUAGE)
       {
            demuxer->getPacketInfo(&data,&packetLen,&usedLen,&pts);
            if(pts!=ADM_NO_PTS)
            {
                        // Wrap around ?
                        if(lastPts)
                        {
                                if(pts<lastPts)
                                {
                                        if(lastPts-pts>MIN_WRAP_VALUE)
                                        {
                                                
                                                printf("Wrapping at %u ",lastPts);
                                                startPts+=lastPts;
                                                timestamp=startPts/90;
                                                ms2time(timestamp,&hh,&mm,&ss,&ms);
                                                printf("%02d:%02d:%02d \n",hh,mm,ss);
                                        }
                                }
                        }

                        lastPts=pts;
                        pts+=startPts;
            }
#if 0
            if(pts!=ADM_NO_PTS)
            {
              timestamp=pts/90;
              ms2time(timestamp,&hh,&mm,&ss,&ms);
              printf("%02d:%02d:%02d \n",hh,mm,ss);
            }
#endif
            blockSize=demuxer->read16i();
            allIndex[stream-0x20].run(blockSize,data,packetLen,usedLen, pts)  ;
       }
    }
/**
      \fn GenericAviSaveCopyUnpack::setupVideo
      \brief init for unpacker code

*/
uint8_t GenericAviSaveCopyPack::setupVideo (char *name)
{
  printf("Setting up bitstream packer\n");
  //  Setup avi file output, all is coming from original avi
  // since we are inc copy mode
  memcpy(&_bih,video_body->getBIH (),sizeof(_bih));
  _bih.biSize=sizeof(_bih);  //fix old version of avidemux
  _bih.biXPelsPerMeter=_bih.biClrUsed=_bih.biYPelsPerMeter=0;
  //
  memcpy(&_videostreamheader,video_body->getVideoStreamHeader (),sizeof( _videostreamheader));
  memcpy(&_mainaviheader,video_body->getMainHeader (),sizeof(_mainaviheader));
  
  // Change both to divx/DX50
  	_videostreamheader.fccHandler=fourCC::get((uint8_t *)"divx");
	_bih.biCompression=fourCC::get((uint8_t *)"DX50");
  /* update to fix earlier bug */
   _mainaviheader.dwWidth=_bih.biWidth;
   _mainaviheader.dwHeight=_bih.biHeight;

   uint8_t *extraData;
   uint32_t extraLen;
  _lastIPFrameSent=0xfffffff;
   video_body->getExtraHeaderData(&extraLen,&extraData);
    if(extraLen>3)
    {
      uint32_t w,h,ti;
      if(extractMpeg4Info(extraData,extraLen,&w,&h,&ti) )
      {
        time_inc=ti;
        printf("Found info : %u  x %u, timeinc %u\n",w,h,ti); 
      }
    }
      
  	if (!writter->saveBegin (name,
			   &_mainaviheader,
			   frameEnd - frameStart + 1,
			   &_videostreamheader,
			   &_bih,
			   extraData,extraLen,
			   audio_filter,
			   audio_filter2
		))
    	{
          GUI_Error_HIG (QT_TR_NOOP("Cannot initiate save"), NULL);
      		return 0;
    	}
	if(audio_filter2)
	{
		printf("Second audio track present\n");
	}
	else
	{
		printf("Second audio track absent\n");
	}
 _incoming = getFirstVideoFilter (frameStart,frameEnd-frameStart);
 encoding_gui->setFps(_incoming->getInfo()->fps1000);
 encoding_gui->setPhasis("Saving");
 
 // Set up our copy codec ...
  copy=new EncoderCopy(NULL);
  if(!copy->configure(_incoming))
  {
      printf("Copy cannot [configure] \n");
      return 0;
  }
  // Our buffer
#define LOOK_SIZE 2*3*_incoming->getInfo ()->width *   _incoming->getInfo ()->height * 3
  uint8_t *buf=new uint8_t[LOOK_SIZE];
           lookAhead[0]=new ADMBitstream(LOOK_SIZE);
           lookAhead[0]->data=buf;
            buf=new uint8_t[LOOK_SIZE];
           lookAhead[1]=new ADMBitstream(LOOK_SIZE);
           lookAhead[1]->data=buf;

  return 1;
}
/**
    \fn saveLoop
*/
bool muxerFFmpeg::saveLoop(const char *title)
{


    printf("[FF] Saving\n");
    uint32_t bufSize=vStream->getWidth()*vStream->getHeight()*3;
    uint8_t *buffer=new uint8_t[bufSize];
    uint64_t rawDts;
    uint64_t lastVideoDts=0;
    uint64_t videoIncrement;
    int ret;
    int written=0;
    bool result=true;
    int missingPts=0;
    
    float f=(float)vStream->getAvgFps1000();
    f=1000./f;
    f*=1000000;
    videoIncrement=(uint64_t)f;



    ADM_info("avg fps=%u\n",vStream->getAvgFps1000());
    uint64_t videoDuration=vStream->getVideoDuration();

    initUI(QT_TRANSLATE_NOOP("adm","Saving"));
    encoding->setContainer(getContainerName());
    MuxAudioPacket *audioPackets=new MuxAudioPacket[nbAStreams];
    ADMBitstream out(bufSize);
    out.data=buffer;

    while(true==vStream->getPacket(&out))
    {
	AVPacket pkt;

            encoding->refresh();
            if(!encoding->isAlive())
            {
                result=false;
                break;
            }
            int64_t xpts=(int64_t)out.pts;
            int64_t xdts=(int64_t)out.dts;
            if(out.pts==ADM_NO_PTS) xpts=-1;
            if(out.dts==ADM_NO_PTS) xdts=-1;
            aprintf("[FF:V] Pts: %"PRId64" DTS:%"PRId64" ms\n",xpts/1000,xdts/1000);

            aprintf("[FF:V] LastDts:%08"PRIu64" Dts:%08"PRIu64" (%04"PRIu64") Delta : %"PRIu64"\n",
                        lastVideoDts,out.dts,out.dts/1000000,out.dts-lastVideoDts);
            rawDts=out.dts;
            if(rawDts==ADM_NO_PTS)
            {
                lastVideoDts+=videoIncrement;
            }else
            {
                lastVideoDts=out.dts;
            }
            if(out.pts==ADM_NO_PTS)
            {
                ADM_warning("No PTS information for frame %"PRIu32"\n",written);
                missingPts++;
                out.pts=lastVideoDts;
            }


            encoding->pushVideoFrame(out.len,out.out_quantizer,lastVideoDts);
            muxerRescaleVideoTimeDts(&(out.dts),lastVideoDts);
            muxerRescaleVideoTime(&(out.pts));
            aprintf("[FF:V] RawDts:%lu Scaled Dts:%lu\n",rawDts,out.dts);
            aprintf("[FF:V] Rescaled: Len : %d flags:%x Pts:%"PRIu64" Dts:%"PRIu64"\n",out.len,out.flags,out.pts,out.dts);

            av_init_packet(&pkt);
            pkt.dts=out.dts;
            if(vStream->providePts()==true)
            {
                pkt.pts=out.pts;
            }else
            {
                pkt.pts=pkt.dts;
            }
            pkt.stream_index=0;
            pkt.data= buffer;
            pkt.size= out.len;
            if(out.flags & 0x10) // FIXME AVI_KEY_FRAME
                        pkt.flags |= AV_PKT_FLAG_KEY;
            ret =writePacket( &pkt);
            aprintf("[FF]Frame:%u, DTS=%08lu PTS=%08lu\n",written,out.dts,out.pts);
            if(false==ret)
            {
                printf("[FF]Error writing video packet\n");
                break;
            }
            written++;
            // Now send audio until they all have DTS > lastVideoDts+increment
            for(int audio=0;audio<nbAStreams;audio++)
            {
                MuxAudioPacket *audioTrack=&(audioPackets[audio]);
                ADM_audioStream*a=aStreams[audio];
                uint32_t fq=a->getInfo()->frequency;

                while(1)
                {
                    if(audioTrack->eof==true) break; // no more packet for this track
                    if(audioTrack->present==false)
                    {
                        if(false==a->getPacket(audioTrack->buffer,
                                                &(audioTrack->size),
                                                AUDIO_BUFFER_SIZE,
                                                &(audioTrack->samples),
                                                &(audioTrack->dts)))
                        {
                                audioTrack->eof=true;
                                ADM_info("No more audio packets for audio track %d\n",audio);
                                break;
                        }
                       // printf("Track %d , new audio packet DTS=%"PRId64" size=%"PRIu32"\n",audioTrack->dts,audioTrack->size);
                        audioTrack->present=true;
                        // Delay audio by the delay induce by encoder
                        if(audioTrack->dts!=ADM_NO_PTS) audioTrack->dts+=audioDelay;
                    }
                    if(audioTrack->dts!=ADM_NO_PTS)
                    {
                        //printf("Audio PTS:%"PRId64", limit=%"PRId64"\n",audioTrack->dts,lastVideoDts+videoIncrement);
                        if(audioTrack->dts>lastVideoDts+videoIncrement) break; // This packet is in the future
                    }
                    // Write...
                    AVPacket pkt;
                    uint64_t rescaledDts;
                    rescaledDts=audioTrack->dts;
                    encoding->pushAudioFrame(audioTrack->size);
                    muxerRescaleAudioTime(audio,&rescaledDts,a->getInfo()->frequency);
                   //printf("[FF] A: Video frame  %d, audio Dts :%"PRIu64" size :%"PRIu32" nbSample : %"PRIu32" rescaled:%"PRIu64"\n",
                     //               written,audioTrack->dts,audioTrack->size,audioTrack->samples,rescaledDts);
                    av_init_packet(&pkt);

                    pkt.dts=rescaledDts;
                    pkt.pts=rescaledDts;
                    pkt.stream_index=1+audio;
                    pkt.data= audioTrack->buffer;
                    pkt.size= audioTrack->size;
                    pkt.flags |= AV_PKT_FLAG_KEY; // Assume all audio are keyframe, which is slightly wrong
                    ret =writePacket( &pkt);
                    audioTrack->present=false; // consumed
                    if(false==ret)
                    {
                        ADM_warning("[FF]Error writing audio packet\n");
                        break;
                    }
                   // printf("[FF] A:%"PRIu32" ms vs V: %"PRIu32" ms\n",(uint32_t)audioTrack->dts/1000,(uint32_t)(lastVideoDts+videoIncrement)/1000);
                }
                //if(!nb) printf("[FF] A: No audio for video frame %d\n",written);
            }

    }
    delete [] buffer;
    if((videoDuration *4)/5 > lastVideoDts)
    {
        GUI_Error_HIG("Too short","The video has been saved but seems to be incomplete.");
        result=false;
    }
    ADM_info("[FF] Wrote %d frames, nb audio streams %d\n",written,nbAStreams);
    ADM_info("[FF] Found %d missing PTS / %d total frames\n",missingPts,written);
    delete [] audioPackets;
    audioPackets=NULL;
    return result;
}
예제 #21
0
uint8_t oplug_mp4(const char *name, ADM_OUT_FORMAT type)
{
AVDMGenericVideoStream *_incoming=NULL;
AVDMGenericAudioStream  *audio=NULL;

uint8_t		audioBuffer[48000];
uint8_t         *videoBuffer=NULL;

uint32_t alen;//,flags;
uint32_t size;

uint8_t   ret=0;

uint32_t  sample_got=0,sample;
uint32_t  extraDataSize=0;
uint8_t   *extraData=NULL;
lavMuxer  *muxer=NULL;
aviInfo      info;
uint32_t   width,height;
DIA_encoding *encoding_gui=NULL;
Encoder         *_encode=NULL;
char            *TwoPassLogFile=NULL;
uint32_t total=0;
uint32_t videoExtraDataSize=0;
uint8_t  *videoExtraData=NULL;
uint8_t *dummy,err;
WAVHeader *audioinfo=NULL;
int prefill=0;
uint32_t displayFrame=0;
ADMBitstream    bitstream(0);
uint32_t        frameWrite=0;
ADM_MUXER_TYPE muxerType=MUXER_MP4;
uint8_t dualPass=0;
uint8_t r=0;
uint32_t skipping=1;
pthread_t     audioThread;
audioQueueMT context;
PacketQueue   *pq;//("MP4 audioQ",50,2*1024*1024);
uint32_t    totalAudioSize=0;
uint32_t sent=0;
const char *containerTitle;
           switch(type)
           {
             case ADM_PSP:muxerType=MUXER_PSP;containerTitle="PSP";break;
             case ADM_MP4:muxerType=MUXER_MP4;containerTitle="MP4";break;
             case ADM_MATROSKA:muxerType=MUXER_MATROSKA;containerTitle="MKV";break;
             default:
                ADM_assert(0);
           }
        // Setup video
        
        if(videoProcessMode())
        {
             _incoming = getLastVideoFilter (frameStart,frameEnd-frameStart);
        }else
        {
             _incoming = getFirstVideoFilter (frameStart,frameEnd-frameStart);
        }

           videoBuffer=new uint8_t[_incoming->getInfo()->width*_incoming->getInfo()->height*3];
                // Set global header encoding, needed for H264
           _encode = getVideoEncoder (_incoming->getInfo()->width,
                        _incoming->getInfo()->height,1);
           total= _incoming->getInfo()->nb_frames;

           encoding_gui=new DIA_encoding(_incoming->getInfo()->fps1000);
           bitstream.bufferSize=_incoming->getInfo()->width*_incoming->getInfo()->height*3;
           if (!_encode)
                {
                  GUI_Error_HIG (QT_TR_NOOP("Cannot initialize the video stream"), NULL);
                        goto  stopit;
                }

                // init compressor
               
                  encoding_gui->setContainer(containerTitle);
               
                encoding_gui->setAudioCodec("None");
                if(!videoProcessMode())
                        encoding_gui->setCodec("Copy");
                else
                        encoding_gui->setCodec(_encode->getDisplayName());
                TwoPassLogFile=new char[strlen(name)+6];
                strcpy(TwoPassLogFile,name);
                strcat(TwoPassLogFile,".stat");
                _encode->setLogFile(TwoPassLogFile,total);

                if (!_encode->configure (_incoming))
                {
                      GUI_Error_HIG (QT_TR_NOOP("Filter init failed"), NULL);
                     goto  stopit;
                };

                dualPass=_encode->isDualPass();
                if(dualPass)
                {
                       
                        if(!prepareDualPass(bitstream.bufferSize,videoBuffer,TwoPassLogFile,encoding_gui,_encode,total))
                                goto stopit;
                }else
                {
                        encoding_gui->setPhasis ("Encoding");
                }
                
                info.width=_incoming->getInfo()->width;
                info.height=_incoming->getInfo()->height;
                info.nb_frames=_incoming->getInfo()->nb_frames;
                info.fps1000=_incoming->getInfo()->fps1000;
                info.fcc=*(uint32_t *)_encode->getCodecName(); //FIXME
                _encode->hasExtraHeaderData( &videoExtraDataSize,&dummy);
                if(videoExtraDataSize)
                {
                        printf("We have extradata for video in copy mode (%d)\n",videoExtraDataSize);
                        videoExtraData=new uint8_t[videoExtraDataSize];
                        memcpy(videoExtraData,dummy,videoExtraDataSize);
                }
        // _________________Setup video (cont) _______________
        // ___________ Read 1st frame _________________
             
             ADM_assert(_encode);
             bitstream.data=videoBuffer;
             
preFilling:
             bitstream.cleanup(0);
             if(!(err=_encode->encode ( prefill, &bitstream)))//&len, videoBuffer, &flags,&displayFrame))
             {
                        printf("MP4:First frame error\n");
                        GUI_Error_HIG (QT_TR_NOOP("Error while encoding"), NULL);
                        goto  stopit;
              }
              sent++;
              if(!bitstream.len)
              {
                prefill++;
                goto preFilling;
              }
              printf("Pass 2 prefill : %u\n",prefill);
              if(!bitstream.flags & AVI_KEY_FRAME)
              {
                GUI_Error_HIG (QT_TR_NOOP("KeyFrame error"),QT_TR_NOOP( "The beginning frame is not a key frame.\nPlease move the A marker."));
                  goto  stopit; 
              }
           //len=bitstream.len;
           // If needed get VOL header
           if(isMpeg4Compatible(info.fcc) && !videoExtraDataSize && bitstream.len)
           {
                // And put them as extradata for esds atom
                uint32_t voslen=0;
               
                if(extractVolHeader(videoBuffer,bitstream.len,&voslen))
                {
                        if(voslen)
                        {
                                videoExtraDataSize=voslen;
                                videoExtraData=new uint8_t[videoExtraDataSize];
                                memcpy(videoExtraData,videoBuffer,videoExtraDataSize);
                        }
                } else  printf("Oops should be settings data for esds\n");
            }

// ____________Setup audio__________________
          if(currentaudiostream)
          {
                audio=mpt_getAudioStream();
                if(!audio)
                {
                        GUI_Error_HIG (QT_TR_NOOP("Cannot initialize the audio stream"), NULL);
                        goto  stopit;
                }
          } 
          if(audio)
          {
                audioinfo=audio->getInfo();
                audio->extraData(&extraDataSize,&extraData);
                if(audioProcessMode())
                        encoding_gui->setAudioCodec(getStrFromAudioCodec(audio->getInfo()->encoding));
                else
                         encoding_gui->setAudioCodec("Copy");

           }else
           {
                encoding_gui->setAudioCodec("None");
           }
// ____________Setup Muxer _____________________
           muxer= new lavMuxer;
           
           if(!muxer->open(
                name,
                2000000, // Muxrate
                muxerType,
                &info,videoExtraDataSize,videoExtraData,
                audioinfo,extraDataSize,extraData))
                         goto stopit;
//_____________ Loop _____________________
          
          encoding_gui->setContainer(containerTitle);
         
          if(!videoProcessMode())
                encoding_gui->setCodec("Copy");
          else
                encoding_gui->setCodec(_encode->getDisplayName());
           //
          UI_purge();
          if(bitstream.len)
          {
            muxer->writeVideoPacket( &bitstream);
            frameWrite++;
          }
//_____________ Start Audio thread _____________________
          if(audio)
          {          
            pq=new PacketQueue("MP4 audioQ",5000,2*1024*1024);
            memset(&context,0,sizeof(context));
            context.audioEncoder=audio;
            context.audioTargetSample=0xFFFF0000; ; //FIXME
            context.packetQueue=pq;
            // start audio thread
            ADM_assert(!pthread_create(&audioThread,NULL,(THRINP)defaultAudioQueueSlave,&context)); 
            ADM_usleep(4000);
          }
//_____________GO !___________________
           for(int frame=1;frame<total;frame++)
           {
               while(muxer->needAudio())
               {
                    if(pq->Pop(audioBuffer,&alen,&sample))
                    {
                     if(alen)
                     {
                        muxer->writeAudioPacket(alen,audioBuffer,sample_got);
                        totalAudioSize+=alen;
                        encoding_gui->setAudioSize(totalAudioSize);
                        sample_got+=sample;
                     }
                    }else break;
               }
               ADM_assert(_encode);
               bitstream.cleanup(frameWrite);
               if(!prefill || frame+prefill<total) 
               {
                  
                  r=_encode->encode ( prefill+frame, &bitstream);
               }
                else
                {
                    r=_encode->encode ( total-1, &bitstream);
                }
               if(!r && frame<total-2)
               {
                        printf("MP4:Frame %u error\n",frame);
                        GUI_Error_HIG (QT_TR_NOOP("Error while encoding"), NULL);
                        goto  stopit;
                }
                if(!bitstream.len && skipping)
                {
                    printf("Frame skipped (xvid ?)\n");
                    continue;
                }
                sent++;
                skipping=0;
            //    printf("Prefill %u FrameWrite :%u Frame %u PtsFrame :%u\n",prefill,frameWrite,frame,bitstream.ptsFrame);
                frameWrite++;
                muxer->writeVideoPacket( &bitstream);
                encoding_gui->setFrame(frame,bitstream.len,bitstream.out_quantizer,total);
               if(!encoding_gui->isAlive())
                {
                    
                    goto stopit;
                }
               
           }
           ret=1;
           
stopit:
    printf("2nd pass, sent %u frames\n",sent);
    // Flush slave Q
    if(audio)
    {
        context.audioAbort=1;
        pq->Abort();
        // Wait for audio slave to be over
        while(!context.audioDone)
        {
          printf("Waiting Audio thread\n");
          ADM_usleep(500000); 
        }
        delete pq;
    }
    //
           if(muxer) muxer->close();
           if(encoding_gui) delete encoding_gui;
           if(TwoPassLogFile) delete [] TwoPassLogFile;
           if(videoBuffer) delete [] videoBuffer;
           if(muxer) delete muxer;
           if(_encode) delete _encode;	
           if(videoExtraData) delete [] videoExtraData;
           // Cleanup
           deleteAudioFilter (audio);
           return ret;
}
/**
    \fn getDecoder
    \brief returns the correct decoder for a stream w,h,fcc,extraLen,extraData,bpp
*/
decoders *ADM_getDecoder (uint32_t fcc, uint32_t w, uint32_t h, uint32_t extraLen, 
            uint8_t * extraData,uint32_t bpp)
{
  ADM_info("\nSearching decoder in plugins\n");
  decoders *fromPlugin=tryCreatingVideoDecoder(w,h,fcc,extraLen,extraData,bpp);
  if(fromPlugin) return fromPlugin;
  
#if defined(USE_VDPAU) 
  ADM_info("Searching decoder in vdpau (%d x %d, extradataSize:%d)...\n",w,h,extraLen);
  if (isH264Compatible (fcc) || isMpeg12Compatible(fcc) || 1*isVC1Compatible(fcc))
    {
        ADM_info("This is vdpau compatible\n");
        if(true==vdpauUsable())
        {
            decoderFFVDPAU *dec=new decoderFFVDPAU (w,h,fcc,extraLen,extraData,bpp);
            if(dec->initializedOk()==true)
                return (decoders *) (dec);
            else
            {
                GUI_Error_HIG("VDPAU","Cannot initialize VDPAU, make sure it is not already used by another application.\nSwitching to default decoder.");
                delete dec;
            }
        }else ADM_info("Vdpau is not active\n");
    }        
#endif // VDPAU
  

#if defined(USE_XVBA) 
  ADM_info("Searching decoder in xvba (%d x %d, extradataSize:%d)...\n",w,h,extraLen);
  if (isH264Compatible (fcc) )
    {
        ADM_info("This is xvba compatible\n");
        if(true==xvbaUsable())
        {
            decoderFFXVBA *dec=new decoderFFXVBA (w,h,fcc,extraLen,extraData,bpp);
            if(dec->initializedOk()==true)
                return (decoders *) (dec);
            else
            {
                GUI_Error_HIG("XVBA","Cannot initialize XVBA, make sure it is not already used by another application.\nSwitching to default decoder.");
                delete dec;
            }
        }else ADM_info("XVBA is not active\n");
    }        
#endif // XVBA  
#if defined(USE_LIBVA) 
  ADM_info("Searching decoder in libva (%d x %d, extradataSize:%d)...\n",w,h,extraLen);
  if (isH264Compatible (fcc) )
    {
        ADM_info("This is libva compatible\n");
        if(true==libvaUsable())
        {
            decoderFFLIBVA *dec=new decoderFFLIBVA (w,h,fcc,extraLen,extraData,bpp);
            if(dec->initializedOk()==true)
                return (decoders *) (dec);
            else
            {
                GUI_Error_HIG("LIBVA","Cannot initialize LIBVA, make sure it is not already used by another application.\nSwitching to default decoder.");
                delete dec;
            }
        }else ADM_info("LIBVA is not active\n");
    }        
#endif // XVBA  
  
  
    ADM_info("Searching decoder in coreVideoCodec(%d x %d, extradataSize:%d)...\n",w,h,extraLen);
    return ADM_coreCodecGetDecoder(fcc,w,h,extraLen,extraData,bpp);
}
예제 #23
0
uint8_t DIA_vobsub(vobSubParam *param)
{
  char *name;
  int32_t shift;     
  int ret,ext;
        
  ret = 0;
  ext = 0;
  name = param->subname;
  shift = param->subShift;
  
  while(!ext)
  {
    dialog = create_dialog1();

	gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog),
										GTK_RESPONSE_OK,
										GTK_RESPONSE_CANCEL,
										-1);

    gtk_register_dialog(dialog);
    gtk_dialog_add_action_widget(GTK_DIALOG(dialog),WID(buttonSelect),GTK_RESPONSE_APPLY);
    
    fq = new GtkWidget*[ADM_MAX_LANGUAGE];
    
    // update if any
        if(name)
        {
                update(name,param->index);
      gtk_label_set_text(GTK_LABEL(WID(labelVobsub)),name);
        }
        else
        {
                gtk_label_set_text(GTK_LABEL(WID(labelVobsub)),QT_TR_NOOP("none"));     
        }

        gtk_write_entry(WID(entryShift),shift);

    switch(gtk_dialog_run(GTK_DIALOG(dialog)))
        {
              case GTK_RESPONSE_APPLY:
                char *file;
                        GUI_FileSelRead(QT_TR_NOOP("Select .idx file"),&file); 
                        if(file)
                        {
          ADM_dealloc(name);
          name = file;
              }
        shift = gtk_read_entry(WID(entryShift));
                break;
              case GTK_RESPONSE_OK:
        if(!name)
                {
          GUI_Error_HIG(QT_TR_NOOP("Wrong VobSub parametering"),QT_TR_NOOP("The idx/sub file does not set."));
        }
        else
        {
          param->subname = name;
          param->index = indeces[getRangeInMenu(WID(optionmenu1))];
          param->subShift = gtk_read_entry(WID(entryShift));
          ret = 1;
          ext = 1;
                }
                break;
              case GTK_RESPONSE_CANCEL:
      default:
        if(name != param->subname)
        {
          ADM_dealloc(name);
        }
                ret=0;
                ext=1;
                break;
        }
        delete [] fq;          
        gtk_unregister_dialog(dialog);
        gtk_widget_destroy(dialog);
  }
     
  return ret;
}    
예제 #24
0
/**
    \fn initAudio
*/
bool muxerMp4v2::initAudio(void)
{
    audioTrackIds=new MP4TrackId[nbAStreams];
    audioPackets=new mp4v2AudioPacket[nbAStreams];
    
    for(int i=0;i<nbAStreams;i++)
    {
        WAVHeader *header=aStreams[i]->getInfo();
        ADM_audioStream*a=aStreams[i];
        audioPackets[i].clock=new audioClock(header->frequency);
        // Preload this track...
        if(false==loadAndToggleAudioSlot(i))
        {
            audioPackets[i].eos=true;
            continue;
        }
        
        switch(header->encoding)
        {
            case WAV_AAC:
                    {
                        uint8_t *extraData=NULL;
                        uint32_t extraDataLen=0;
                        if(!a->getExtraData(&extraDataLen,&extraData))
                            {
                                 GUI_Error_HIG("AAC","Cannot get AAC Extra data\n");
                                 return false;
                            }
                        audioTrackIds[i]=MP4AddAudioTrack(handle,
                                                      header->frequency,
                                                      1024,
                                                      MP4_MPEG4_AUDIO_TYPE);
                        if(MP4_INVALID_TRACK_ID==audioTrackIds[i])
                        {
                            ADM_error("Error adding audio track %i of type 0x%x\n",i,header->encoding);
                            return false;
                        }
                        aprintf("Add Track %d fq %d\n",audioTrackIds[i],header->frequency);
                        MP4SetAudioProfileLevel(handle,0x0f);
                        MP4SetTrackIntegerProperty(handle,audioTrackIds[i],"mdia.minf.stbl.stsd.mp4a.channels",
                                    header->channels);
                        MP4SetTrackESConfiguration(handle,audioTrackIds[i],extraData,extraDataLen);
                    break;
                    }
            case WAV_AC3:
                    if(false==addAc3(i, header))
                    {
                            return false;
                    }
                    break;
            case WAV_MP2:
            case WAV_MP3:
                    audioTrackIds[i]=MP4AddAudioTrack(handle,
                                                      header->frequency,
                                                      audioPackets[i].blocks[0].nbSamples,
                                                      MP4_MPEG2_AUDIO_TYPE);
                    if(MP4_INVALID_TRACK_ID==audioTrackIds[i])
                    {
                        ADM_error("Error adding audio track %i of type 0x%x\n",i,header->encoding);
                        return false;
                    }
                    aprintf("Add Track %d fq %d\n",audioTrackIds[i],header->frequency);
                    MP4SetAudioProfileLevel(handle,0x0f);
                    MP4SetTrackIntegerProperty(handle,audioTrackIds[i],"mdia.minf.stbl.stsd.mp4a.channels",
                                header->channels);
                    break;
            default:
                    ADM_error("Cannot create audio track of type 0x%x\n",header->encoding);
                    return false;
        }
        if(aStreams[i]->isLanguageSet())
        {
                MP4SetTrackLanguage(handle,audioTrackIds[i],aStreams[i]->getLanguage().c_str());
                ADM_info("[MP4v2] Setting language to %s \n",aStreams[i]->getLanguage().c_str());
        }else
            ADM_warning("[MP4v2] Language is undefined\n");

         MP4SetTrackBytesProperty(handle,audioTrackIds[i],"udta.name.value",
                    (const uint8_t*)"Stereo", strlen("Stereo"));

    }
    if(nbAStreams)
         MP4SetTrackIntegerProperty(handle, audioTrackIds[0], "tkhd.flags", 3);
    return true;
}
예제 #25
0
/*
 * 		\fn    Oplug_flv
		\brief Main function to save in flv format.
		It is very close to oplug_mp4 but somehow simplified as the following assumptions are made :
				* No b frame
				* No 2 pass encoding

*/
uint8_t oplug_flv(const char *name)
{
AVDMGenericVideoStream *_incoming=NULL;
AVDMGenericAudioStream  *audio=NULL;

uint8_t		audioBuffer[48000];
uint8_t         *videoBuffer=NULL;

uint32_t alen;//,flags;
uint32_t size;

uint32_t  sample_got=0,sample;
uint32_t  extraDataSize=0;
uint8_t   *extraData=NULL;
lavMuxer  *muxer=NULL;
aviInfo      info;
uint32_t   width,height;
DIA_encoding *encoding_gui=NULL;
Encoder         *_encode=NULL;
uint32_t total=0;
uint32_t videoExtraDataSize=0;
uint8_t  *videoExtraData=NULL;
uint8_t *dummy,err;
WAVHeader *audioinfo=NULL;
int prefill=0;
uint32_t displayFrame=0;
ADMBitstream    bitstream(0);
uint8_t r=0;
pthread_t     audioThread;
audioQueueMT context;
PacketQueue   *pq=NULL;//("MP4 audioQ",50,2*1024*1024);
uint32_t    totalAudioSize=0;
int frameDelay = 0;
bool receivedFrame = false;

        // Setup video

        if(videoProcessMode())
        {
             _incoming = getLastVideoFilter (frameStart,frameEnd-frameStart);
        }else
        {
             _incoming = getFirstVideoFilter (frameStart,frameEnd-frameStart);
        }

           videoBuffer=new uint8_t[_incoming->getInfo()->width*_incoming->getInfo()->height*3];
                // Set global header encoding, needed for H264
           _encode = getVideoEncoder (_incoming->getInfo()->width,  _incoming->getInfo()->height,1);
           total= _incoming->getInfo()->nb_frames;

           info.fcc=*(uint32_t *)_encode->getCodecName(); //FIXME
           //
           int supported=0;
           if(isVP6Compatible(info.fcc)) supported=1;
           if(fourCC::check(info.fcc,(const uint8_t *)"FLV1")) supported=1;
           if(!supported)
           {
        	   GUI_Error_HIG(QT_TR_NOOP("Unsupported video"),QT_TR_NOOP("Only FLV1 and VP6 video are supported"));
        	   goto stopit;
           }
           /* Check audio, we support only mp3 right now
            * 44100, 22050, 11025 only!
            *  */
           if(currentaudiostream)
           {
        	   uint32_t audioCodec=0;
        	   uint32_t fq=currentaudiostream->getInfo()->frequency;

        	   	if(audioProcessMode())
        	   	{
        	   		audioCodec=audioFilter_getOuputCodec();
        	   		fq=audioFilter_getOuputFrequency(fq);

        	   	}else
        	   	{	// copy
        	   		audioCodec=currentaudiostream->getInfo()->encoding;
        	   	}
        	   	if(audioCodec!=WAV_MP3 )
        	   		{
        	   			GUI_Error_HIG(QT_TR_NOOP("Unsupported audio"),QT_TR_NOOP("Audio must be mp3 for flv output."));
        	   			goto stopit;
        	   		}
        	   	if(fq!=44100 && fq!=22050 && fq!=11025)
        	   	{
    	   			GUI_Error_HIG(QT_TR_NOOP("Unsupported audio"),QT_TR_NOOP("Frequency must be 44100, 22050 or 11025 Hz."));
    	   			goto stopit;

        	   	}
           }


           encoding_gui=new DIA_encoding(_incoming->getInfo()->fps1000);
           bitstream.bufferSize=_incoming->getInfo()->width*_incoming->getInfo()->height*3;
           if (!_encode)
                {
                  GUI_Error_HIG ("[FLV]",QT_TR_NOOP("Cannot initialize the video stream"));
                        goto  stopit;
                }

                // init compressor
                encoding_gui->setContainer(QT_TR_NOOP("FLV"));
                encoding_gui->setAudioCodec(QT_TR_NOOP("None"));
                if(!videoProcessMode())
                        encoding_gui->setCodec(QT_TR_NOOP("Copy"));
                else
                        encoding_gui->setCodec(_encode->getDisplayName());

                if (!_encode->configure (_incoming))
                {
                      GUI_Error_HIG (QT_TR_NOOP("Filter init failed"), NULL);
                     goto  stopit;
                };

                encoding_gui->setPhasis (QT_TR_NOOP("Encoding"));


                info.width=_incoming->getInfo()->width;
                info.height=_incoming->getInfo()->height;
                info.nb_frames=_incoming->getInfo()->nb_frames;
                info.fps1000=_incoming->getInfo()->fps1000;

                _encode->hasExtraHeaderData( &videoExtraDataSize,&dummy);
                if(videoExtraDataSize)
                {
                        printf("[FLV]We have extradata for video in copy mode (%d)\n",videoExtraDataSize);
                        videoExtraData=new uint8_t[videoExtraDataSize];
                        memcpy(videoExtraData,dummy,videoExtraDataSize);
                }

             ADM_assert(_encode);
             bitstream.data=videoBuffer;

// ____________Setup audio__________________
          if(currentaudiostream)
          {
                audio=mpt_getAudioStream();
                if(!audio)
                {
                        GUI_Error_HIG ("[FLV]",QT_TR_NOOP("Cannot initialize the audio stream"));
                        goto  stopit;
                }
          }
          if(audio)
          {
                audioinfo=audio->getInfo();
                audio->extraData(&extraDataSize,&extraData);
                if(audioProcessMode())
                        encoding_gui->setAudioCodec(getStrFromAudioCodec(audio->getInfo()->encoding));
                else
                         encoding_gui->setAudioCodec(QT_TR_NOOP("Copy"));

           }else
           {
                encoding_gui->setAudioCodec(QT_TR_NOOP("None"));
           }
// ____________Setup Muxer _____________________
           muxer= new lavMuxer;

           if(!muxer->open(
                name,
                2000000, // Muxrate
                MUXER_FLV,
                &info,videoExtraDataSize,videoExtraData,
                audioinfo,extraDataSize,extraData))
                         goto stopit;
//_____________ Loop _____________________

          encoding_gui->setContainer(QT_TR_NOOP("FLV"));

          if(!videoProcessMode())
                encoding_gui->setCodec(QT_TR_NOOP("Copy"));
          else
                encoding_gui->setCodec(_encode->getDisplayName());
           //
          UI_purge();

//_____________ Start Audio thread _____________________
          if(audio)
          {
            pq=new PacketQueue("[FLV] audioQ",5000,2*1024*1024);
            memset(&context,0,sizeof(context));
            context.audioEncoder=audio;
            context.audioTargetSample=0xFFFF0000; ; //FIXME
            context.packetQueue=pq;
            // start audio thread
            ADM_assert(!pthread_create(&audioThread,NULL,(THRINP)defaultAudioQueueSlave,&context));
            ADM_usleep(4000);
          }
//_____________GO !___________________

			 for (uint32_t frame = 0; frame < total; frame++)
			 {
				 if (!encoding_gui->isAlive())
				 {
					 r = 0;
					 break;
				 }

				 while(muxer->needAudio())
				 {
					 if(pq->Pop(audioBuffer,&alen,&sample))
					 {
						 if(alen)
						 {
							 muxer->writeAudioPacket(alen,audioBuffer,sample_got);
							 totalAudioSize+=alen;
							 encoding_gui->setAudioSize(totalAudioSize);
							 sample_got+=sample;
						 }
					 }
					 else
					 {
						 r = 0;
						 break;
					 }
				 }

				 for (;;)
				 {
					 bitstream.cleanup(frame);

					 if (frame + frameDelay >= total)
					 {
						 if (_encode->getRequirements() & ADM_ENC_REQ_NULL_FLUSH)
							 r = _encode->encode(UINT32_MAX, &bitstream);
						 else
							 r = 0;
					 }
					 else
						 r = _encode->encode(frame + frameDelay, &bitstream);

					 if (!r)
					 {
						 printf("Encoding of frame %lu failed!\n", frame);
						 GUI_Error_HIG (QT_TR_NOOP("Error while encoding"), NULL);
						 break;
					 }
					 else if (!receivedFrame && bitstream.len > 0)
					 {
						 if (!(bitstream.flags & AVI_KEY_FRAME))
						 {
							 GUI_Error_HIG (QT_TR_NOOP("KeyFrame error"), QT_TR_NOOP("The beginning frame is not a key frame.\nPlease move the A marker."));
							 r = 0;
							 break;
						 }
						 else
							 receivedFrame = true;
					 }

					 if (bitstream.len == 0 && (_encode->getRequirements() & ADM_ENC_REQ_NULL_FLUSH))
					 {
						 printf("skipping frame: %u size: %i\n", frame + frameDelay, bitstream.len);
						 frameDelay++;
					 }
					 else
						 break;
				 }

				 if (!r)
					 break;

				 muxer->writeVideoPacket(&bitstream);
				 encoding_gui->setFrame(frame, bitstream.len, bitstream.out_quantizer, total);
			 }

stopit:

    // Flush slave Q
    if(audio&& pq)
    {
        context.audioAbort=1;
        pq->Abort();
        // Wait for audio slave to be over
        while(!context.audioDone)
        {
          printf("[FLV]Waiting Audio thread\n");
          ADM_usleep(500000);
        }
        delete pq;
    }
    //
           if(muxer) muxer->close();
           if(encoding_gui) delete encoding_gui;
           if(videoBuffer) delete [] videoBuffer;
           if(muxer) delete muxer;
           if(_encode) delete _encode;
           if(videoExtraData) delete [] videoExtraData;
           // Cleanup
           deleteAudioFilter (audio);
           return r;
}
예제 #26
0
/**
    \fn addAC3
    \brief Setup AC3 audio track
*/
bool muxerMp4v2::addAc3(int index, WAVHeader *header)
{
        int fscod=0;
        switch(header->frequency)
        {
                case 48000: fscod=0;break;
                case 44100: fscod=1;break;
                case 32000: fscod=2;break;
                default: 
                    {
                    GUI_Error_HIG("", "invalid frequency for AC3. Only 32, 44.1 & 48 kHz");
                    return false;
                    }
        }
        int bitrate;
        static const uint16_t ac3_bitrate_tab[19] = { // From handbrake
                     32, 40, 48, 56, 64, 80, 96, 112, 128,
                     160, 192, 224, 256, 320, 384, 448, 512, 576, 640
                 };
        int Ceil=sizeof(ac3_bitrate_tab)/sizeof(const uint16_t);
        bitrate=-1;
        for(int ix=0;ix<Ceil;ix++)
                if(header->byterate==(ac3_bitrate_tab[ix]*1000)/8)
                {
                    bitrate=ix;
                    break;
                }
        if(-1==bitrate) 
        {
            GUI_Error_HIG("","Invalid bitrate for AC3");
            return false;
        }
        int acmod,lfe=0;
        switch(header->channels)
        {
                case 1: acmod=1;break;
                case 2: acmod=2;break;
                case 5: acmod=7;lfe=0;break; 
#warning Check!
                case 6: acmod=7;lfe=1;break;
                default: 
                        {
                                  GUI_Error_HIG("","Invalid number of channel for AC3");
                                  return false;
                        }
        }
        audioTrackIds[index]=MP4AddAC3AudioTrack(handle,
                                              header->frequency,// samplingRate,
                                               fscod,           // fscod
                                               8,               // bsid,
                                               0,               // bsmod,
                                               acmod,           // acmod
                                               lfe,             // lfeon
                                               bitrate);        // bit_rate_code 
        if(MP4_INVALID_TRACK_ID==audioTrackIds[index])
        {
            ADM_error("Error adding audio track %i of type 0x%x\n",index,header->encoding);
            return false;
        }
        aprintf("Add Track %d fq %d (AC3)\n",audioTrackIds[index],header->frequency);
        return true;
}
예제 #27
0
/**
    \fn configure
*/
bool changeFps::configure(void)
{
again:
    float newFrac=configuration.newFpsNum; 
    newFrac/=configuration.newFpsDen;

    float oldFrac=configuration.oldFpsNum; 
    oldFrac/=configuration.oldFpsDen;


ADM_assert(nbPredefined == 6);
  
   diaMenuEntry tFps[]={
#define Z(x)                 {x,     predefinedFps[x].desc}
                    Z(0),Z(1),Z(2),Z(3),Z(4),Z(5)

          };
    
    

    diaElemMenu mFps(&(configuration.oldMode),   QT_TR_NOOP("Source Fps:"), 6,tFps);
    diaElemFloat fps(&oldFrac,QT_TR_NOOP("Source frame rate:"),1,200.);

    mFps.link(tFps+0,1,&fps); // only activate entry in custom mode

    diaElemMenu targetmFps(&(configuration.newMode),   QT_TR_NOOP("Destination Fps:"), 6,tFps);
    diaElemFloat targetfps(&newFrac,QT_TR_NOOP("Destination frame rate:"),1,200.);

    targetmFps.link(tFps+0,1,&targetfps); // only activate entry in custom mode



    diaElem *elems[4]={&mFps,&fps,&targetmFps,&targetfps};
  
    if( !diaFactoryRun(QT_TR_NOOP("Change fps"),4,elems))
        return false;
    
    if(newFrac==0 || oldFrac==0)
    {
        GUI_Error_HIG("Error","Invalid fps");
        goto again;
    }
      // 
      if(!configuration.newMode) // Custom mode
      {
          newFrac*=1000;
          configuration.newFpsNum=(uint32_t)floor(newFrac+0.4);
          configuration.newFpsDen=(uint32_t)1000;
      }else   // Preset
        {
            const PredefinedFps_t *me=&(predefinedFps[configuration.newMode]);
            configuration.newFpsNum=me->num;
            configuration.newFpsDen=me->den;
        }

    if(!configuration.oldMode) // Custom mode
      {
          oldFrac*=1000;
          configuration.oldFpsNum=(uint32_t)floor(oldFrac+0.4);
          configuration.oldFpsDen=(uint32_t)1000;
      }else   // Preset
        {
            const PredefinedFps_t *me=&(predefinedFps[configuration.oldMode]);
            configuration.oldFpsNum=me->num;
            configuration.oldFpsDen=me->den;
        }
      updateTimingInfo();
      return true;
}
uint8_t
EncoderSaveMpeg (const char *name)
{
  uint8_t raw;
  uint8_t ret = 0;
  switch (UI_GetCurrentFormat ())
    {
    case ADM_ES:
      raw = 1;
      break;
    case ADM_PS:
      raw = 0;
      break;
    case ADM_TS:
      raw = 2;
      break;
    default:
      GUI_Error_HIG (QT_TR_NOOP("Wrong output format"), QT_TR_NOOP("Select MPEG as the output."));
      return 0;
    }
  if (current_codec != CodecDVD && raw == 2)
    {
      GUI_Error_HIG (QT_TR_NOOP("Wrong video codec"),
                     QT_TR_NOOP("Select DVD as the video codec for MPEG TS output."));
      return 0;
    }
  switch (current_codec)
    {
    case CodecVCD:
      if (raw)
	ret = oplug_mpeg_vcd (name);
      else
	ret = oplug_mpeg_vcd_ps (name);
      break;
    case CodecSVCD:
      if (raw)
	ret = oplug_mpeg_svcd (name);
      else
	ret = oplug_mpeg_svcd_ps (name);
      break;
    case CodecDVD:
      switch (raw)
	{
	case 2:
	  ret = oplug_mpeg_ts (name);
	  break;
	case 1:
	  ret = oplug_mpeg_dvd (name);
	  break;
	case 0:
	  ret = oplug_mpeg_dvd_ps (name);
	  break;
	default:
	  ADM_assert (0);
	}
      break;
    default:
      ADM_assert (0);
    }
  return ret;
}
예제 #29
0
bool muxerMp4v2::open(const char *file, ADM_videoStream *s,uint32_t nbAudioTrack,ADM_audioStream **a)
{

        audioDelay=s->getVideoDelay();
        vStream=s;
        nbAStreams=nbAudioTrack;
        aStreams=a;
        videoBufferSize=vStream->getWidth()*vStream->getHeight()*3;
        videoBuffer[0]=new uint8_t[videoBufferSize];
        videoBuffer[1]=new uint8_t[videoBufferSize];
        scratchBuffer=new uint8_t[videoBufferSize];
        in[0].bufferSize=videoBufferSize;
        in[0].data=videoBuffer[0];
        in[1].bufferSize=videoBufferSize;
        in[1].data=videoBuffer[1];
        targetFileName=string(file);
//------Verify everything is ok : Accept Mp4 & H264 for video, AAC for audio ----
        uint32_t fcc=vStream->getFCC();
        if(!isH264Compatible(fcc) && !isMpeg4Compatible(fcc))
        {
            ADM_error("[mp4v2] Only h264 and mp4 video track!\n");
            return false;
        }
        for(int i=0;i<nbAStreams;i++)
        {
            int encoding=aStreams[i]->getInfo()->encoding;
            switch(encoding)
            {
                case WAV_MP2:case WAV_MP3:case WAV_AAC:case WAV_AC3:
                            continue;
                default:
                    GUI_Error_HIG("Audio","Audio format not supported, only AAC/MP3/AC3");
                    return false;
            }            
        }
//------Verify everything is ok : Accept Mp4 & H264 for video, AAC for audio ----
        
        // Create file
        handle=MP4Create( file,  ADM_MP4_OPTIONS_OPEN);
        if(MP4_INVALID_FILE_HANDLE==handle)
        {
            ADM_error("[mp4v2]Cannot create output file %s\n",file);
            return false;
        }
        MP4LogSetLevel(MP4_LOG_INFO);
        
        if (!(MP4SetTimeScale( handle, 90*1000 ))) // 90 kHz tick
        {
            ADM_error("[mp4v2]Cannot set timescale to us\n");
            return false;
        }
        if(false==initVideo())
        {
            ADM_error("Cannot init video\n");
            return false;
        }
        if(false==initAudio())
        {
            ADM_error("Cannot init audio\n");
            return false;
        }

        return true;
er:
        return false;
}
예제 #30
0
/**
	Load or append a file.
	The file type is determined automatically and the ad-hoc video decoder is spawned


*/
uint8_t ADM_Composer::addFile (char *name, uint8_t mode)
{
  uint8_t    ret =    0;
  aviInfo    info;
  WAVHeader *    _wavinfo;
//  aviHeader *    tmp;
  fileType    type =    Unknown_FileType;

UNUSED_ARG(mode);
	_haveMarkers=0; // by default no markers are present
  ADM_assert (_nb_segment < max_seg);
  ADM_assert (_nb_video < MAX_VIDEO);

  if (!identify (name, &type))
    return 0;


#define OPEN_AS(x,y) case x:\
						_videos[_nb_video]._aviheader=new y; \
						 ret = _videos[_nb_video]._aviheader->open(name); \
						break;
  switch (type)
    {
      case VCodec_FileType:
      		loadVideoCodecConf(name);      		
		return ADM_IGN; // we do it but it wil fail, no problem with that
      		break;
      OPEN_AS (Mp4_FileType, mp4Header);
      OPEN_AS (H263_FileType, h263Header);
      
      case ASF_FileType:
              _videos[_nb_video]._aviheader=new asfHeader; 
              ret = _videos[_nb_video]._aviheader->open(name); 
              if(!ret)
              {
                delete _videos[_nb_video]._aviheader;;
                printf("Trying mpeg\n"); 
                goto thisIsMpeg; 
              }
              break;
      OPEN_AS (NewMpeg_FileType,dmxHeader);
      // For AVI we first try top open it as openDML
      case AVI_FileType:
      			_videos[_nb_video]._aviheader=new OpenDMLHeader; 
			 ret = _videos[_nb_video]._aviheader->open(name); 			
			break;
      
    case Nuppel_FileType:
	{ // look if the idx exists
	  char *tmpname = (char*)ADM_alloc(strlen(name)+strlen(".idx")+1);
		ADM_assert(tmpname);
		sprintf(tmpname,"%s.idx",name);
		if(addFile(tmpname))
		{
			return 1; // Memleak ?
		}
		ADM_dealloc(tmpname);
		// open .nuv file
		_videos[_nb_video]._aviheader=new nuvHeader;
		ret = _videos[_nb_video]._aviheader->open(name);
		// we store the native .nuv file in the edl
		// the next load of the edl will open .idx instead
		break;
	}
      OPEN_AS (BMP_FileType, picHeader);
      OPEN_AS (Matroska_FileType, mkvHeader);
      OPEN_AS (AvsProxy_FileType, avsHeader);
      OPEN_AS (_3GPP_FileType, _3GPHeader);
       OPEN_AS (Ogg_FileType, oggHeader);

    case Mpeg_FileType:
thisIsMpeg:
    	// look if the idx exists
	char tmpname[256];
	ADM_assert(strlen(name)+5<256);;
	strcpy(tmpname,name);
	strcat(tmpname,".idx");
        if(ADM_fileExist(tmpname))
        {
	       return addFile(tmpname);
        }
	/* check for "Read-only file system" */
	{
                int fd = open(tmpname,O_CREAT|O_EXCL|O_WRONLY,S_IRUSR|S_IWUSR);
                if( fd >= 0 )
                {
                    close(fd);
                    unlink(tmpname);
                    printf("Filesystem is writable\n");
		}else if( errno == EROFS ){
		  char *tmpdir = getenv("TMPDIR");
#ifdef CYG_MANGLING
                        printf("Filesystem is not writable, looking for somewhere else\n");
			if( !tmpdir )
				tmpdir = "c:";
			snprintf(tmpname,256,"%s%s.idx",tmpdir,strrchr(name,'\\'));
#else
			if( !tmpdir )
				tmpdir = "/tmp";
			snprintf(tmpname,256,"%s%s.idx",tmpdir,strrchr(name,'/'));
#endif
			tmpname[255] = 0;
                        printf("Storing index in %s\n",tmpname);
                    if(ADM_fileExist(tmpname))
                    {
                        printf("Index present, loading it\n");
                        return addFile(tmpname);
                    }
                }
        }
        if(tryIndexing(name,tmpname))
        {
                return addFile (tmpname);
        }
        return 0;
      break;
	case WorkBench_FileType:

  		return loadWorbench(name);
#if 0
        case Script_FileType:
                return parseScript(name);
#endif
	case ECMAScript_FileType:
                printf("****** This is an ecmascript, run it with avidemux2 --run yourscript *******\n");
                printf("****** This is an ecmascript, run it with avidemux2 --run yourscript *******\n");
                printf("****** This is an ecmascript, run it with avidemux2 --run yourscript *******\n");
                return 0;
		
                
    default:
      if (type == Unknown_FileType)
	{
	  printf ("\n not identified ...\n");
	}
      else
        GUI_Error_HIG(_("File type identified but no loader support detected..."),
                      _("May be related to an old index file."));
      return 0;
    }

   // check opening was successful
   if (ret == 0) {
     char str[512+1];
     snprintf(str,512,_("Attempt to open %s failed!"), name);
      str[512] = '\0';
      GUI_Error_HIG(str,NULL);
      delete _videos[_nb_video]._aviheader;;
      return 0;
   }

   /* check for resolution */
   if( _nb_video ){
      /* append operation */
      aviInfo info0, infox;
      _videos[   0     ]._aviheader->getVideoInfo (&info0);
      _videos[_nb_video]._aviheader->getVideoInfo (&infox);
      if( info0.width != infox.width || info0.height != infox.height ){
        char str[512+1];
         str[0] = '\0';
         if( info0.width != infox.width )
            strcpy(str,"width");
         if( info0.height != infox.height )
            snprintf(str+strlen(str),512-strlen(str),
              "%sheight%sdifferent between first and this video stream",
                 (strlen(str)?" and ":""),
                 (strlen(str)?" are ":" is ") );
         str[512] = '\0';
         GUI_Error_HIG(str,_("You cannot mix different video dimensions yet. Using the partial video filter later, will not work around this problem. The workaround is:\n1.) \"resize\" / \"add border\" / \"crop\" each stream to the same resolution\n2.) concatinate them together"));
         delete _videos[_nb_video]._aviheader;;
         return 0;
      }
   }
 
  // else update info
  _videos[_nb_video]._aviheader->getVideoInfo (&info);
  _videos[_nb_video]._aviheader->setMyName (name);
  // 1st if it is our first video we update postproc
 if(!_nb_video)
 {
        uint32_t type,value;

        if(!prefs->get(DEFAULT_POSTPROC_TYPE,&type)) type=3;
        if(!prefs->get(DEFAULT_POSTPROC_VALUE,&value)) value=3; 	

	deletePostProc(&_pp );
 	initPostProc(&_pp,info.width,info.height);
	_pp.postProcType=type;
	_pp.postProcStrength=value;
	_pp.forcedQuant=0;
	updatePostProc(&_pp);

	if(_imageBuffer) delete _imageBuffer;
	_imageBuffer=new ADMImage(info.width,info.height);
 	_imageBuffer->_qSize= ((info.width+15)>>4)*((info.height+15)>>4);
	_imageBuffer->quant=new uint8_t[_imageBuffer->_qSize];
	_imageBuffer->_qStride=(info.width+15)>>4;
 }