void *ADM_realloc(void *ptr, size_t newsize)
{
  void *nalloc;
    
    if(!ptr) return ADM_alloc(newsize);
    if(!newsize) 
    {
    	
    	ADM_dealloc(ptr);
	return NULL;
    }
    // now we either shrink them or expand them
    // in case of shrink, we do nothing
    // in case of expand we have to copy
    // Do copy everytime (slower)
	uint32_t *backdoor;
	uint32_t size,offset;
	char	 *c=(char *)ptr;
	
	backdoor=(uint32_t *)ptr;
	backdoor-=2;
	
	ADM_assert(((*backdoor)>>16)==0xdead);
	
	offset=backdoor[0]&0xffff;
	size=backdoor[1];
	if(size>=newsize) // do nothing
		return ptr;
	// Allocate a new one
	nalloc=ADM_alloc(newsize);
	
	memcpy(nalloc,ptr,size);
	ADM_dealloc(ptr);
	return nalloc;
}
 ADMDolbyContext::ADMDolbyContext()
{
     for(int j=0;j<4;j++)
     {
         xv_left[j]=(float *)ADM_alloc( sizeof(float)*(NZEROS*2+2));
         xv_right[j]=(float *)ADM_alloc( sizeof(float)*(NZEROS*2+2));
     }    
     reset();
}
void set_content(const char *option, xmlNodePtr x){
   int idx = -1;
   char *str,*str2;
	for( int i=0; i < num_opts; i++ ){
		if( !strcmp(opt_defs[i].name,option) ){
			idx = i;
			break;
		}
	}
	if( idx == -1 ){
		fprintf(stderr,"option \"%s\" not defined.\n",option);
		return;
	}
	if( !(str = (char*)xmlNodeGetContent(x)) ){
		fprintf(stderr,"no content in xmlNode for option \"%s\".\n",option);
		return;
	}
	
	str2=(char *)ADM_alloc(strlen(str)+1);
	strcpy(str2,str);
	free(str);
	
	if( opt_defs[idx].current_val )
		ADM_dealloc(opt_defs[idx].current_val);
	opt_defs[idx].current_val = str2;
	#ifdef DEBUG_PREFS
	fprintf(stderr,"Prefs: %s => %s\n",opt_defs[idx].name,opt_defs[idx].current_val);
	#endif
}
void *adm_new_systray(GdkPixbuf *pixbufA[],int nb , char *name)
{
	flipflop=0;
  systray_icon = GTK_WIDGET (egg_tray_icon_new ("Avidemux"));
  nbListOfIcons=nb;
  if(listOfIcons) ADM_dealloc(listOfIcons);
  listOfIcons=NULL;
  listOfIcons=ADM_alloc(sizeof( GdkPixbuf *)*nb);
  memcpy(listOfIcons,pixbufA,sizeof(GdkPixbuf *)*nb);
  img = gtk_image_new_from_pixbuf (listOfIcons[0]);
  

  evbox = gtk_event_box_new ();
  gtk_container_add (GTK_CONTAINER (systray_icon), evbox);
  gtk_container_add (GTK_CONTAINER (evbox), img);
  gtk_widget_show_all (systray_icon);
  gtk_widget_realize (systray_icon);
  gtk_widget_show (systray_icon);

  systray_icon_tooltips = gtk_tooltips_new ();
  gtk_tooltips_enable (systray_icon_tooltips);

  gtk_tooltips_set_tip (systray_icon_tooltips, systray_icon, "avidemux", "");
  return (void *)systray_icon;
}
JSBool allFilesFrom(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
char *str;
DIR *dir;
struct dirent *direntry;
       // ADM_JSAvidemux *p = (ADM_JSAvidemux *)JS_GetPrivate(cx, obj);
        cleanup();
        // default return value
        if(argc != 1)
                return JS_FALSE;
	if(JSVAL_IS_STRING(argv[0]) == false)
		return JS_FALSE;

        str=JS_GetStringBytes(JSVAL_TO_STRING(argv[0]));
        dir=opendir(str);
        if(!dir)
        {
                *rval=INT_TO_JSVAL(0); // No files
                return JS_TRUE;
        }
        while((direntry=readdir(dir)) && dirmax<ADM_MAX_DIR-1)
        {
                dirs[dirmax]=(char *)ADM_alloc(strlen(str)+strlen(direntry->d_name)+2);
                strcpy(dirs[dirmax],str);
                strcat(dirs[dirmax],direntry->d_name);
                //printf("File:<%s>\n",dirs[dirmax]);
                dirmax++;
        }
        closedir(dir);
        *rval=INT_TO_JSVAL(dirmax);
        return JS_TRUE;
}
ADM_AudiocodecMP3::ADM_AudiocodecMP3( uint32_t fourcc,WAVHeader *info,uint32_t extraLength,uint8_t *extraData) :   ADM_Audiocodec(fourcc)
{
        if((fourcc!=WAV_MP3) && (fourcc!=WAV_MP2))
            ADM_assert(0); 
        if(fourcc==WAV_MP2) printf("Mpeg1/2 audio codec created\n");
        _stream=(void *)ADM_alloc(sizeof( mad_stream));
        _frame=(void *)ADM_alloc(sizeof( mad_frame));
        _synth=(void *)ADM_alloc(sizeof( mad_synth));
        
        
        mad_stream_init(Stream);
        mad_frame_init(Frame);
        mad_synth_init(Synth);
        
        _head=_tail=0;

}
char *ADM_strdup(const char *in)
{
	if(!in)
		return NULL;

	uint32_t l = strlen(in);
	char *out;

	out = (char*)ADM_alloc(l + 1);
	memcpy(out, in, l+1);

	return out;
}
/**
      \fn DIA_v2v
      \brief  handle vob2vobsub dialog 
*/
uint8_t  DIA_v2v(char **vobname, char **ifoname,char **vobsubname)
{
uint8_t ret=0;
char *tmp=NULL,*tmp2=NULL,*tmp3=NULL;

        
        diaElemFile eVob(0,&tmp,QT_TR_NOOP("_VOB file(s):"), NULL, QT_TR_NOOP("Select VOB file(s)"));
        diaElemFile eIfo(0,&tmp2,QT_TR_NOOP("_IFO file:"), NULL, QT_TR_NOOP("Select IFO file"));
        diaElemFile eVsub(1,&tmp3,QT_TR_NOOP("VobSub file:"), NULL, QT_TR_NOOP("Select VobSub file"));
        
        while(1)
        {
           diaElem *tabs[]={&eVob,&eIfo,&eVsub};
          if( diaFactoryRun(QT_TR_NOOP("VOB to VobSub"),3,tabs))
	  {
              if(!ADM_fileExist(tmp))
              {
                GUI_Error_HIG(QT_TR_NOOP("The selected vobfile does not exist"), NULL); 
                continue;
              }
              if(!ADM_fileExist(tmp2))
              {
                GUI_Error_HIG(QT_TR_NOOP("The selected vobfile does not exist"), NULL); 
                continue;
              }
              if(strlen(tmp3)<3)
              {
                 GUI_Error_HIG(QT_TR_NOOP("Please select a correct VobSub path/dir"), NULL); 
                 continue;
              }
                  if(*vobname) ADM_dealloc(*vobname);
                  if(*ifoname) ADM_dealloc(*ifoname);
                  if(*vobsubname) ADM_dealloc(*vobsubname);

                    *vobname=*ifoname=*vobsubname=NULL;

                  *vobname=ADM_strdup(tmp);
                  *ifoname=ADM_strdup(tmp2);
                  *vobsubname=(char *)ADM_alloc(strlen(tmp3)+5); //ADM_strdup(tmp3);
                  strcpy(*vobsubname,tmp3);
                  if(tmp3[strlen(tmp3)-1]!='x'|| tmp3[strlen(tmp3)-2]!='d') 
                          strcat(*vobsubname,".idx");
                  ADM_dealloc(tmp);
                  ADM_dealloc(tmp2);
                  ADM_dealloc(tmp3);
                  return 1;
          } 
          else return 0;
        }
        return 0;
}
/**
    \fn writeDummyChunk
    \brief write a placeholder dummy chunk
*/
bool  AviListAvi::writeDummyChunk(int size, uint64_t *pos)
{
	// save file position
		*pos=Tell();
		aprintf("[ODML]write dummy chunk at file position %" PRIu64" with data size %" PRIu32"\n",*pos, size);
		// generate dummy data
		uint8_t* dummy=(uint8_t*)ADM_alloc (size);
		memset(dummy,0,size);
		// write dummy chunk
		WriteChunk ( (const uint8_t  *)"JUNK", size, dummy);
		// clean up
		ADM_dealloc (dummy);
        return true;
}
// DND CYB
void DNDDataReceived( GtkWidget *widget, GdkDragContext *dc,
                                  gint x, gint y, GtkSelectionData *selection_data, guint info, guint t)
{
   void *filename;
   char *start,*end;
   int cont;

    if (info == TARGET_URI_LIST)
    {
     start = strstr((char*)selection_data->data,"file://");
     cont = 0;
     do
     {
       if (start)
       {
        end = strstr((char*)start+1,"file://");
        if (!end)
        {
                      end = start + strlen(start);
                      cont = 1;
                      continue;
        }
        filename = ADM_alloc(end-start); 
        if (filename)
        {
              memset(filename,0,end-start);
              memcpy(filename,start+7,end-start-7-2);
              if (avifileinfo) 
              {
                    // Append video when there's already something
                    fileReadWrite(A_appendAvi, 0, (char*)filename);
               }
               else
               {
                    fileReadWrite(A_openAvi, 0, (char*)filename);
               }
         } 
         ADM_dealloc(filename);
         start = end;
       }
       else
       {
           cont=1;
       } 
     } //do
     while (!cont);  
    }
    gtk_drag_finish(dc,TRUE,FALSE,t);
}
/*
    In some case (e.g. javascript), the reader expects unixish path 
    c:/foo/bar/c.c
    and the "natural" path is c:\foo\bar
    
    This function convert the later to the former

*/
extern char *slashToBackSlash(char *in)
{
    char *out,*cout;
    int n;
    n=strlen(in);
    cout=out=(char *)ADM_alloc(n+1);   
    for(int i=0;i<n+1;i++)
    {
        if(   in[i]=='\\') out[i]='/';
        else    out[i]=in[i];
        
    }
    return cout;
    
}
int makeFilter(Float Imp[], long Nwing, double Froll, double Beta, 
	       long Num, int Normalize)
{
   double *ImpR;
   long Mwing, i;

   if (Nwing > MAXNWING)                      /* Check for valid parameters */
      return(-1);
   if ((Froll<=0) || (Froll>1))
      return(-2);

   /* it does help accuracy a bit to have the window stop at
    * a zero-crossing of the sinc function */
   Mwing = (long)(floor((double)Nwing/(((double)Num)/Froll))*(((double)Num)/Froll) +0.5);
   if (Mwing==0)
      return(-4);

   ImpR = (double *) ADM_alloc(sizeof(double) * Mwing);

   /* Design a Nuttall or Kaiser windowed Sinc low-pass filter */
   LpFilter(ImpR, Mwing, Froll, Beta, Num);

   if (Normalize) { /* 'correct' the DC gain of the lowpass filter */
      long Dh;
      double DCgain;
      DCgain = 0;
      Dh = Num;                  /* Filter sampling period for factors>=1 */
      for (i=Dh; i<Mwing; i+=Dh)
         DCgain += ImpR[i];
      DCgain = 2*DCgain + ImpR[0];    /* DC gain of real coefficients */
      /*st_report("DCgain err=%.12f",DCgain-1.0);*/
  
      DCgain = 1.0/DCgain;
      for (i=0; i<Mwing; i++)
         Imp[i] = ImpR[i]*DCgain;

   } else {
      for (i=0; i<Mwing; i++)
         Imp[i] = ImpR[i];
   }
   ADM_dealloc(ImpR);
   for (i=Mwing; i<=Nwing; i++) Imp[i] = 0;
   /* Imp[Mwing] and Imp[-1] needed for quadratic interpolation */
   Imp[-1] = Imp[1];

   return(Mwing);
}
Exemple #13
0
 /**
 *  \fn buildDirectoryContent
 * 	\brief Returns the content of a dir with the extension ext. The receiving array must be allocated by caller
 * (just the array, not the names themselves)
 */
 uint8_t buildDirectoryContent(uint32_t *outnb, const char *base, char *jobName[], int maxElems, const char *ext)
 {

    std::string joker = std::string(base) + std::string("/*.") + std::string(ext);
 	int dirNameLength = utf8StringToWideChar(joker.c_str(), -1, NULL);
 	wchar_t *base2 = new wchar_t[dirNameLength];
    utf8StringToWideChar(joker.c_str(), -1, base2);
    int dirmax = 0;
//--
    HANDLE hFind;
    WIN32_FIND_DATAW FindFileData;

    hFind = FindFirstFileW(base2,&FindFileData);
    if(hFind == INVALID_HANDLE_VALUE)
    {
        ADM_warning("Cannot list content of %s\n", base);
        delete[] base2;
        *outnb = 0;
        return true;
    }

    do 
    {
        WCHAR *wname = FindFileData.cFileName;
        //int wideCharStringToAnsi(const wchar_t *wideCharString, int wideCharStringLength, char *ansiString, const char *filler)
        int nameLength = wideCharStringToAnsi(wname, -1, NULL, "?");       
        char *shortName = new char[nameLength];
        nameLength = wideCharStringToAnsi(wname, -1, shortName, "?");
        std::string item = std::string(base) + std::string("/") + std::string(shortName);
        delete[] shortName;

        int targetLength = item.length();
        jobName[dirmax] = (char *)ADM_alloc(targetLength);
        strcpy(jobName[dirmax], item.c_str());
        dirmax++;
        if (dirmax > maxElems)
            break;
            
    } while (FindNextFileW(hFind, &FindFileData));
    FindClose(hFind);
    
    *outnb = dirmax;

    delete[] base2;
    return true;
 }
/*--------------------------------------------------------------------*/
uint32_t quantstat[32];		/* 0-31 ; 0 and 1 are unused */
void
print_quant_stat (const char *n)
{
  char *str = (char *) ADM_alloc (strlen (n) + 4);
  unsigned int i = 2, sum = 0, total = 0;
  FILE *fd;
  ADM_assert (str);
  strcpy (str, n);
  strcat (str, ".qs");
  if ((fd = qfopen (str, "wb")))
    {
      for (; i < 32; i++)
	{
	  qfprintf (fd, "Quant % 2u: % 7u times\n", i, quantstat[i]);
	  sum += i * quantstat[i];
	  total += quantstat[i];
	}
      qfprintf (fd, "\nQuant over all: %2.2f\n", (float) sum / (float) total);
      qfclose (fd);
    }
  ADM_dealloc (str);
}
/*
   			val is the average bitrate wanted, else it is useless
*/
uint8_t
ffmpegEncoderVBR::init (uint32_t val, uint32_t fps1000)
{
  uint32_t statSize;
  FILE *_statfile;

  printf ("[lavc] initializing in VBR mode\n");
  _qual = val;
  mplayer_init ();

//   _context->frame_rate_base = 1000;
//   _context->frame_rate = fps1000;

  _context->time_base = (AVRational)  {  1000, fps1000};

  /* If internal 2 passes mode is selected ... */
  _context->flags |= CODEC_FLAG_PASS2;

  _statfile = fopen (LogName, "rb");
  if (!_statfile)
    {
      printf ("internal file does not exists ?\n");
      return 0;
    }

  fseek (_statfile, 0, SEEK_END);
  statSize = ftello (_statfile);
  fseek (_statfile, 0, SEEK_SET);
  _context->stats_in = (char *) ADM_alloc (statSize + 1);
  _context->stats_in[statSize] = 0;
  fread (_context->stats_in, statSize, 1, _statfile);
  fclose(_statfile);

  _context->bit_rate = val;	// bitrate

  return initContext ();

}
/**
    \fn Ctor
*/       
Decimate::Decimate(	ADM_coreVideoFilter *in,CONFcouple *couples)      : 
            ADM_coreVideoFilterCached(11,in,couples)
{
		
		char buf[80];
		unsigned int *p;	
        deciMate *_param=&configuration;
		//		
		// Init here
		if(!couples || !ADM_paramLoad(couples,deciMate_param,&configuration))
  		{
			_param->cycle=5;
			_param->mode=3;
            _param->show=false;
            _param->debug=false;
			_param->quality=2;
			_param->threshold=0;
			_param->threshold2=3.0;
		}
		
		ADM_assert(_param->cycle);
		
		if (_param->mode == 0 || _param->mode == 2 || _param->mode == 3)
		{
                    updateInfo();
		}
		sum = (unsigned int *) ADM_alloc(MAX_BLOCKS * MAX_BLOCKS * sizeof(unsigned int));
		ADM_assert(sum);		
	

		if (configuration.debug)
		{
			OutputDebugString( "Decimate %s by Donald Graft, Copyright 2003\n", 0); // VERSION
		}

        reset();
}
/**
    \fn ADM_calloc(size_t nbElm,size_t elSize);
    \brief Replacement for system Calloc using our memory management
    \param nbElem : # of elements to allocate
    \param elSize : Size of one element in bytes
    \return pointer 
*/
void *ADM_calloc(size_t nbElm, size_t elSize)
{
	void *out = ADM_alloc(nbElm * elSize);
	memset(out, 0, nbElm * elSize);
	return out;
}
/**
    \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;
}
//_______________________________________
//
void ComputePreload(void)
//_______________________________________
{
    uint32_t state,latency, one_sec;
    uint32_t small_;
    uint32_t channels;

    wavbuf = 0;

    if (!currentaudiostream)	// audio ?
      {
	  return;
      }
    // PCM or readable format ?
    if (currentaudiostream->isCompressed())
      {
	  if (!currentaudiostream->isDecompressable())
	    {
		audio_available = 0;
		return;
	    }
      }


    double db;
    // go to the beginning...

    db = curframe * 1000.;	// ms
    db *= 1000.;		// fps is 1000 time too big
    db /= avifileinfo->fps1000;
    printf(".. Offset ...%ld ms\n", (uint32_t) floor(db + 0.49));
    //      currentaudiostream->goToTime( (uint32_t)floor(db+0.49));        

    playback = buildPlaybackFilter(currentaudiostream,(uint32_t) (db + 0.49), 0xffffffff);
    
    channels= playback->getInfo()->channels;
    one_audio_frame = (one_frame * wavinfo->frequency * channels);	// 1000 *nb audio bytes per ms
    one_audio_frame /= 1000; // In elemtary info (float)
    printf("1 audio frame = %lu bytes\n", one_audio_frame);
    // 3 sec buffer..               
    wavbuf =  (float *)  ADM_alloc((3 *  2*channels * wavinfo->frequency*wavinfo->channels));
    ADM_assert(wavbuf);
    // Call it twice to be sure it is properly setup
     state = AVDM_AudioSetup(playback->getInfo()->frequency,  channels );
     AVDM_AudioClose();
     state = AVDM_AudioSetup(playback->getInfo()->frequency,  channels );
     latency=AVDM_GetLayencyMs();
     printf("[Playback] Latency : %d ms\n",latency);
      if (!state)
      {
          GUI_Error_HIG(QT_TR_NOOP("Trouble initializing audio device"), NULL);
          return;
      }
    // compute preload                      
    //_________________
    // we preload 1/4 a second
     currentaudiostream->beginDecompress();
     one_sec = (wavinfo->frequency *  channels)  >> 2;
     one_sec+=(latency*wavinfo->frequency *  channels*2)/1000;
     AUD_Status status;
    uint32_t fill=0;
    while(fill<one_sec)
    {
      if (!(small_ = playback->fill(one_sec-fill, wavbuf,&status)))
      {
        break;
      }
    fill+=small_;
    }
    dauds += fill/channels;  // In sample
    AVDM_AudioPlay(wavbuf, fill);
    // Let audio latency sets in...
    ADM_usleep(latency*1000);
    audio_available = 1;
}
uint8_t  DIA_v2v(char **vobname, char **ifoname,char **vobsubname)
{
uint8_t ret=0;
char *tmp=NULL,*tmp2=NULL,*tmp3=NULL;

        GtkWidget *dialog;

        dialog=create_dialog1();
        gtk_register_dialog(dialog);
        gtk_dialog_add_action_widget (GTK_DIALOG (dialog), WID(buttonVob),actionVOB);
        gtk_dialog_add_action_widget (GTK_DIALOG (dialog), WID(buttonIfo),actionIFO);
        gtk_dialog_add_action_widget (GTK_DIALOG (dialog), WID(buttonVobSub),actionVOBSUB);

#define ENTRY_SET(x,y) {gtk_write_entry_string(WID(x),*y);}

        ENTRY_SET(entryIfo,ifoname);
        ENTRY_SET(entryVob,vobname);
        ENTRY_SET(entryVobSub,vobsubname);

        while(1)
        {
                switch(gtk_dialog_run(GTK_DIALOG(dialog)))
                {
                        case actionVOB:
                                        {
                                        
                                        int r;
                                                GUI_FileSelRead(_("Select Vob file to scan"),&tmp);
                                                if(!tmp) continue;
                                                gtk_editable_delete_text(GTK_EDITABLE(WID(entryVob)), 0,-1);
                                                gtk_editable_insert_text(GTK_EDITABLE(WID(entryVob)), tmp, strlen(tmp), &r);
                                                ADM_dealloc(tmp);
                                        }
                                        break;
                        case actionIFO:
                                        {
                                        
                                        int r;
                                                GUI_FileSelRead(_("Select ifo file to use"),&tmp);
                                                if(!tmp) continue;
                                                gtk_editable_delete_text(GTK_EDITABLE(WID(entryIfo)), 0,-1);
                                                gtk_editable_insert_text(GTK_EDITABLE(WID(entryIfo)), tmp, strlen(tmp), &r);
                                                ADM_dealloc(tmp);
                                        }
                                        break;
                        case actionVOBSUB:
                                        {
                                        
                                        int r;
                                                GUI_FileSelWrite(_("Select vobsub to write"),&tmp);
                                                if(!tmp) continue;
                                                gtk_editable_delete_text(GTK_EDITABLE(WID(entryVobSub)), 0,-1);
                                                gtk_editable_insert_text(GTK_EDITABLE(WID(entryVobSub)), tmp, strlen(tmp), &r);
                                                ADM_dealloc(tmp);
                                        }
                                        break;

                                        break;
                        case GTK_RESPONSE_OK: 
                                        {
                                           tmp=gtk_editable_get_chars(GTK_EDITABLE (WID(entryVob)), 0, -1);
                                           if(!tmp || !*tmp)
                                           {
                                             GUI_Error_HIG(_("Invalid vobname"),_("Please select or enter a valid vob name"));
                                                        continue;
                                            }
                                           tmp2=gtk_editable_get_chars(GTK_EDITABLE (WID(entryIfo)), 0, -1);
                                           if(!tmp2 || !*tmp2)
                                           {
                                             GUI_Error_HIG(_("Invalid ifo"),_("Please select or enter a valid ifo file"));
                                                        continue;
                                            }
                                           tmp3=gtk_editable_get_chars(GTK_EDITABLE (WID(entryVobSub)), 0, -1);
                                           if(!tmp3 || !*tmp3 )
                                           {
                                             GUI_Error_HIG(_("Invalid vobsubname"),_("Please select or enter a valid vobsub file"));
                                                        continue;
                                            }
                                            if(*vobname) ADM_dealloc(*vobname);
                                            if(*ifoname) ADM_dealloc(*ifoname);
                                            if(*vobsubname) ADM_dealloc(*vobsubname);

                                             *vobname=*ifoname=*vobsubname=NULL;

                                            *vobname=ADM_strdup(tmp);
                                            *ifoname=ADM_strdup(tmp2);
                                            *vobsubname=(char *)ADM_alloc(strlen(tmp3)+5); //ADM_strdup(tmp3);
                                            strcpy(*vobsubname,tmp3);
                                            if(tmp3[strlen(tmp3)-1]!='x') strcat(*vobsubname,".idx");
                                            ret=1;
                                        }
                        default: goto _nxt;
                }
        }
_nxt:
        gtk_unregister_dialog(dialog);
        gtk_widget_destroy(dialog);
        return ret;
}
//************************************
int sox_init(uint32_t fin, uint32_t fout,ResampleStruct *r) 
{
	
long Xoff, gcdrate;
int i;

	memset(r,0,sizeof(ResampleStruct));
	/*
	r->rolloff = 0.94;
	r->quadr = 1;
	r->Nmult = 149;*/
	
	r->rolloff = 0.80;
	r->quadr = 0;
	r->Nmult = 45;
	
	
	r->beta=16;	
	
	if (fout == fin)
	{
	    printf("Input and Output rates must be different to use resample effect");
	    return(0);
	}
	printf("Resampling from %lu to %lu\n",fin,fout);	
	r->Factor = (double)fout / (double)fin;

	gcdrate = st_gcd((long)fin, (long)fout);
	r->a = fin/ gcdrate;
	r->b = fout / gcdrate;

	if (r->a <= r->b && r->b <= NQMAX) {
		r->quadr = -1; /* exact coeff's   */
		r->Nq = r->b;  /* MAX(r->a,r->b);	*/
	} else {
		r->Nq = Nc; /* for now */
	}

	/* Check for illegal constants */

	/* Nwing: # of filter coeffs in right wing */
	r->Nwing = r->Nq * (r->Nmult/2+1) + 1;

	r->Imp = (Float *)ADM_alloc(sizeof(Float) * (r->Nwing+2)) + 1;
	/* need Imp[-1] and Imp[Nwing] for quadratic interpolation */
	/* returns error # <=0, or adjusted wing-len > 0 */
	
	i = makeFilter(r->Imp, r->Nwing, r->rolloff, r->beta, r->Nq, 1);
	if (i <= 0)
	{
		printf("resample: Unable to make filter\n");
		return (0);
	}

	/*st_report("Nmult: %ld, Nwing: %ld, Nq: %ld\n",r->Nmult,r->Nwing,r->Nq);*/

	if (r->quadr < 0) { /* exact coeff's method */
		r->Xh = r->Nwing/r->b;
	  printf("resample: rate ratio %ld:%ld, coeff interpolation not needed\n", r->a, r->b);
	} else {
	  r->dhb = Np;  /* Fixed-point Filter sampling-time-increment */
	  if (r->Factor<1.0) r->dhb =(long int)floor( r->Factor*Np + 0.5);
	  r->Xh = (r->Nwing<<La)/r->dhb;
	  /* (Xh * dhb)>>La is max index into Imp[] */
	}

	/* reach of LP filter wings + some creeping room */
	Xoff = r->Xh + 10;
	r->Xoff = Xoff;

	/* Current "now"-sample pointer for input to filter */
	r->Xp = Xoff;
	/* Position in input array to read into */
	r->Xread = Xoff;
	/* Current-time pointer for converter */
	r->Time = Xoff;
	if (r->quadr < 0) { /* exact coeff's method */
		r->t = Xoff*r->Nq;
	}
	i = BUFFSIZE - 2*Xoff;
	if (i < r->Factor + 1.0/r->Factor)      /* Check input buffer size */
	{
		printf("Factor is too small or large for BUFFSIZE");
		return (0);
	}
	
	r->Xsize = (int)floor(2.*Xoff + i/(1.0+r->Factor));
	r->Ysize = BUFFSIZE - r->Xsize;
	/* st_report("Xsize %d, Ysize %d, Xoff %d",r->Xsize,r->Ysize,r->Xoff); */

	r->X = (Float *) ADM_alloc(sizeof(Float) * (BUFFSIZE));
	r->Y = r->X + r->Xsize;

	/* Need Xoff zeros at beginning of sample */
	for (i=0; i<Xoff; i++)
		r->X[i] = 0;
	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    picHeader::open(char *inname)
{

uint32_t		nnum;
uint32_t		*fcc;
uint8_t			fcc_tab[4];
FILE 			*fd;
char 			*end;
uint32_t			w=0,h=0;

	// 1- identity the file type
	//
	fcc=(uint32_t *)fcc_tab;
	fd=fopen(inname,"rb");
	if(!fd)
		{
			printf("\n Cannot open that file!\n");
			return 0;
		}
	fread(fcc_tab,4,1,fd);
	fclose(fd);
	if(fourCC::check(*fcc,(uint8_t *)"RIFF"))
	{
		_type=PIC_BMP;
		printf("\n It looks like BMP (RIFF)...\n");
	}
	else
	{
		if(fcc_tab[0]=='B' && fcc_tab[1]=='M')
		{
			_type=PIC_BMP2;
			printf("\n It looks like BMP (BM)...\n");
		}
		else	
		if(fcc_tab[0]==0xff && fcc_tab[1]==0xd8)
		{
		 	_type=PIC_JPEG;
			printf("\n It looks like Jpg...\n");
		}
		else
		{
			printf("\n Cannot identify file (%x %x)\n",*fcc,*fcc&0xffff);
			return 0;
		}
	}

	// Then spit the name in name and extension
	char *name;
	char *extension;
	 PathSplit(inname, &name, &extension);


     	nnum=1;

     	end=name+strlen(name)-1;
     	while(( *end>='0') && (*end<='9'))
     		{
            		end--;
        	      	nnum++;
         	};
      if(nnum==1)
      	{
          	printf("\n only one file!");
          	return 0;

         }
        nnum--;
        end++;
       _first=atoi(end);
       printf("\n First : %lu, num digit :%lu",_first,nnum);
       *(end)=0;
       printf("\n Path : %s\n",name);

       char realname[250];
       char realstring[250];

            	sprintf(realstring,"%%s%%0%lud.%s",nnum,extension);
              printf("\n string : %s",realstring);

       _nb_file=0;

       for(uint32_t i=0;i<MAX_ACCEPTED_OPEN_FILE;i++)
       	{
              sprintf(realname,realstring,name,i+_first);
              printf("\n %lu : %s",i,realname);
              fd=fopen(realname,"rb");
              if(fd==NULL) break;
              fclose(fd);
              _nb_file++;
          }
	printf("\n found %lu images\n",_nb_file);


	_fd=(FILE **)ADM_alloc(_nb_file*sizeof(FILE*));
	_imgSize=new uint32_t[_nb_file];
	  //_________________________________
          // now open them and assign fd && imgSize
	  //__________________________________
          for(uint32_t i=0;i<_nb_file;i++)
          {
              sprintf(realname,realstring,name,i+_first);
              printf("\n %lu : %s",i,realname);
              _fd[i]=fopen(realname,"rb");
	      fseek(_fd[i],0,SEEK_END);
	      _imgSize[i]=ftell( _fd[i] );
		fseek(_fd[i],0,SEEK_SET);
              ADM_assert(_fd[i]!=NULL);
            }

	delete [] name;
	delete [] extension;


	//
	//	Image is bmp type
	//________________________
	switch(_type)
	{
		case PIC_BMP:
			{
			BITMAPHEADER bmph;

              		fread(&s16,2,1, _fd[0]);
              		if(s16!=0x4D42)
              		{
                		printf("\n incorrect bmp sig.\n");
              			return 0;
               		}
              		fread(&s32,4,1, _fd[0]);
              		fread(&s32,4,1, _fd[0]);
              		fread(&s32,4,1, _fd[0]);
               		fread(&bmph, sizeof(bmph), 1, _fd[0]);
               		if(bmph.compressionScheme!=0)
               		{
                 		printf("\ncannot handle compressed bmp\n");
	               		return 0;
                	}
              		_offset=bmph.size+14;
			w=bmph.width ;
			h=bmph.height ;
			}
			break;
	

		 // Jpeg : Grab the size
		//____________________
		case PIC_JPEG:
			{
			uint16_t tag=0,count=0,off;

			_offset=0;
			fseek(_fd[0],0,SEEK_SET);
			read16(_fd[0]); // skip jpeg ffd8
			while(count<10 && tag!=0xFFC0)
			{

				tag=read16(_fd[0]);
				if( (tag >>8 ) !=0xff)
				{
					printf("invalid jpeg tag found (%x)\n",tag);
				}
				if(tag==0xFFC0)
				{
					read16(_fd[0]); // size
					read8(_fd[0]);  // precision
					h=read16(_fd[0]);
					w=read16(_fd[0]);
				}
				else
				{

					off=read16(_fd[0]);
					if(off<2)
						{
							printf("Offset too short!\n");
							return 0;
						}
					aprintf("Found tag : %x , jumping %d bytes\n",tag,off);
					fseek(_fd[0],off-2,SEEK_CUR);
				}
				count++;
			}
			if(tag!=0xffc0)
			{
				printf("Cannot fint start of frame\n");
				return 0;
			}
			printf("\n %lu x %lu..\n",w,h);
			}
			break;

		case PIC_BMP2:
			{
			BITMAPINFOHEADER bmph;

			fseek(_fd[0],10,SEEK_SET);

			#define MK32() (fcc_tab[0]+(fcc_tab[1]<<8)+(fcc_tab[2]<<16)+ \
						(fcc_tab[3]<<24))

              		fread(fcc_tab,4,1, _fd[0]);
              		_offset=MK32();
			// size, width height follow as int32 
               		fread(&bmph, sizeof(bmph), 1, _fd[0]);
#ifdef ADM_BIG_ENDIAN
			Endian_BitMapInfo(&bmph);	
#endif
               		if(bmph.biCompression!=0)
               		{
                 		printf("\ncannot handle compressed bmp\n");
	               		return 0;
                	}
			w=bmph.biWidth ;
			h=bmph.biHeight ;
			printf("W: %d H: %d offset : %d\n",w,h,_offset);
			}
	
			break;
		default:
			ADM_assert(0);
		}

//_______________________________________
//		Now build header info
//_______________________________________
	      _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.dwLength= _mainaviheader.dwTotalFrames=_nb_file;
               _videostream.dwInitialFrames= 0;
               _videostream.dwStart= 0;
               //
               //_video_bih.biCompression= 24;
               //
               _video_bih.biWidth=_mainaviheader.dwWidth		=w ;
               _video_bih.biHeight=_mainaviheader.dwHeight	=h;
               //_video_bih.biPlanes= 24;

	         if(PIC_JPEG==_type)
		 {
			          _video_bih.biCompression=_videostream.fccHandler=fourCC::get((uint8_t *)"MJPG");;
		 }
		 else
		 {
  				_video_bih.biCompression=_videostream.fccHandler=0;
		 }
		printf("Offset : %lu\n",_offset);
       return 1;
}
void *operator new[] ( size_t t)
{
	return ADM_alloc(t);
}
//********************************
// lavcodec wrapper
//********************************
void *av_malloc(unsigned int size)
{
 	return ADM_alloc(size);
}
/**
    \fn addFile
    \brief	Load or append a file.	The file type is determined automatically and the ad-hoc video decoder is spawned
    
    @param name: filename
    @param mode: 0 open, 1 append
    @param forcedType : if !=Unknown_FileType, it enables to force the file type

    @return 1 on success, 0 on failure
        

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

UNUSED_ARG(mode);
	_haveMarkers=0; // by default no markers are present

  if (_nb_video == (max_videos - 1))
  {
	  max_videos += MAX_VIDEO;
	  printf("extending max_videos: %i\n", max_videos);

	  _VIDEOS *vid = new _VIDEOS[max_videos];

	  memset(vid, 0, sizeof(_VIDEOS) * max_videos);
	  memcpy(vid, _videos, sizeof(_VIDEOS) * (max_videos - MAX_VIDEO));

	  delete _videos;
	  _videos = vid;
  }

  if (_nb_segment == max_seg - 1)
	  extendSegmentBuffer();

  ADM_assert (_nb_segment < max_seg);
  ADM_assert (_nb_video < max_videos);

  // Autodetect file type ?
  if(Unknown_FileType==type)
  {
      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 (FLV_FileType, flvHeader);
      OPEN_AS (AvsProxy_FileType, avsHeader);
      OPEN_AS (_3GPP_FileType, MP4Header);
      OPEN_AS (Ogg_FileType, oggHeader);
      OPEN_AS (AMV_FileType, amvHeader);

    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 = ADM_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 __WIN32
                        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(QT_TR_NOOP("File type identified but no loader support detected..."),
                      QT_TR_NOOP("May be related to an old index file."));
      return 0;
    }

   // check opening was successful
   if (ret == 0) {
     char str[512+1];
     snprintf(str,512,QT_TR_NOOP("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)
	  {
         GUI_Error_HIG(QT_TR_NOOP("Video dimensions don't match."), QT_TR_NOOP("You cannot mix different video dimensions yet. Using the partial video filter later will not work around this problem. The workaround is:\n\n1) \"Resize\" / \"Add Border\" / \"Crop\" each stream to the same resolution\n2) Concatenate them together"));
		 delete _videos[_nb_video]._aviheader;
         return 0;
      }
   }
 
  // else update info
  _videos[_nb_video]._aviheader->getVideoInfo (&info);
  _videos[_nb_video]._aviheader->setMyName (name);
  
  // Printf some info about extradata
  {
    uint32_t l=0;
    uint8_t *d=NULL;
    _videos[_nb_video]._aviheader->getExtraHeaderData(&l,&d);
    if(l && d)
    {
        printf("The video codec has some extradata (%d bytes)\n",l);
        mixDump(d,l);
        printf("\n");
    }
  }
  // 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;
 }
/**
    \fn Ctor
*/       
Telecide::Telecide(	ADM_coreVideoFilter *in,CONFcouple *couples)      : 
        ADM_coreVideoFilterCached(16,in,couples)
{

		int i;		
		int count;
		char *d, *dsaved;
		unsigned int *p, *x;
        teleCide *_param=&configuration;		
		

		if(!couples || !ADM_paramLoad(couples,teleCide_param,&configuration))
        {
                 
			 	_param->order = 1; 		// 0 Field ok, 1 field reverted 0 BFF/1 TFF
				_param->back = NO_BACK; // 0 Never, 1 when bad, 2 always tried MUST Have post !=0
				_param->chroma = false;
				_param->guide = GUIDE_32;// 0 / NONE - 1 GUIDE_32/ivtc-2 GUIDE 22/PAL-3 PAL/NTSC
				_param->gthresh = 10.0;
				_param->post = POST_METRICS;
				_param->vthresh = 50.0;
				_param->bthresh = 50.0;
				_param->dthresh = 7.0;
				_param->blend = false; // Interpolate is default
				_param->nt = 10;	// Noise tolerance
				_param->y0 = 0;		// Zone to try (avoid subs)
				_param->y1 = 0;
				_param->hints = true;
				_param->show = false;
				_param->debug = false; 

		}
				 
				
		tff = (_param->order == 0 ? false : true);	

		_param->back_saved = _param->back;

		// Set up pattern guidance.
		cache = (struct CACHE_ENTRY *) ADM_alloc(CACHE_SIZE * sizeof(struct CACHE_ENTRY));
		CachePurge();

		if (_param->guide == GUIDE_32)
		{
			// 24fps to 30 fps telecine.
			cycle = 5;
		}
		if (_param->guide == GUIDE_22)
		{
			// PAL guidance (expect the current match to be continued).
			cycle = 2;
		}
		else if (_param->guide == GUIDE_32322)
		{
			// 25fps to 30 fps telecine.
			cycle = 6;
		}

		// Get needed dynamic storage.
		vmetric = 0;
		_param->vthresh_saved = _param->vthresh;
		xblocks = (info.width+BLKSIZE-1) / BLKSIZE;
		yblocks = (info.height+BLKSIZE-1) / BLKSIZE;
#ifdef WINDOWED_MATCH
		matchp = (unsigned int *) ADM_alloc(xblocks * yblocks * sizeof(unsigned int));
		
		matchc = (unsigned int *) ADM_alloc(xblocks * yblocks * sizeof(unsigned int));
		
#endif
		sump = (unsigned int *) ADM_alloc(xblocks * yblocks * sizeof(unsigned int));
		
		sumc = (unsigned int *) ADM_alloc(xblocks * yblocks * sizeof(unsigned int));
}
Exemple #28
0
void * mpeg2_malloc (unsigned size, mpeg2_alloc_t reason)
{

	return ADM_alloc(size);
   
}
/**
    \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->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;
}
Decimate::Decimate(AVDMGenericVideoStream *in,CONFcouple *couples)		
{
{
		
		int count = 0;
		char buf[80];
		unsigned int *p;

		_in=in;		
   		memcpy(&_info,_in->getInfo(),sizeof(_info));    
  		_info.encoding=1;
		_uncompressed=NULL;		
  		_info.encoding=1;
		
		//		
		// Init here
		debug=0;
		show=0;		
#ifdef USE_SSE	
		if(CpuCaps::hasSSE())
		{
			printf("Decimate:SSE enabled\n");
		}
#endif
		//
		_param=new DECIMATE_PARAM;
		if(couples)
		{
			GET(cycle);
			GET(mode);
			GET(quality);
			GET(threshold);
			GET(threshold2);
			
		}
		else // Default
  		{
			_param->cycle=5;
			_param->mode=0;
			_param->quality=2;
			_param->threshold=0;
			_param->threshold2=3.0;
		}
		
		ADM_assert(_param->cycle);
		vidCache=new VideoCache(_param->cycle*2+1,in);
		
		if (_param->mode == 0 || _param->mode == 2 || _param->mode == 3)
		{
			num_frames_hi = _info.nb_frames;
			_info.nb_frames = _info.nb_frames * (_param->cycle - 1) / _param->cycle;
			_info.fps1000=_info.fps1000*(_param->cycle-1);
			_info.fps1000=(uint32_t)(_info.fps1000/_param->cycle);
			
		}
		last_request = -1;
		firsttime = true;
		sum = (unsigned int *) ADM_alloc(MAX_BLOCKS * MAX_BLOCKS * sizeof(unsigned int));
		ADM_assert(sum);		
		all_video_cycle = true;

		if (debug)
		{
			char b[80];
			sprintf(b, "Decimate %s by Donald Graft, Copyright 2003\n", VERSION);
			OutputDebugString(b);
		}
	}
}