Пример #1
0
bool CCamAvi::Initialize (char* filename)
{
	long hr;
	AVISTREAMINFO info;
	
	m_init=false;
	m_pos=0;
	
	AVIFileInit ();
	
	hr=AVIFileOpen (&m_paf, filename, OF_READ, NULL);
	if (hr!=0) return false;

	hr=AVIFileGetStream (m_paf, &m_pas, streamtypeVIDEO, 0);
	if (hr!=0) return false;

	hr= AVIStreamInfo (m_pas, &info, sizeof (info));	
	if (hr!=0) return false;

	hr=sizeof (m_bi);
	hr= AVIStreamReadFormat (m_pas, 0, &m_bi, &hr);
	if (hr!=0) return false;	
	
	if (m_bi.bmiHeader.biCompression!=0)
	{
		// find decompressor
		m_hic=ICOpen (ICTYPE_VIDEO, info.fccHandler ,ICMODE_DECOMPRESS);
		if (m_hic==0) return false;
	}
 	m_data=new unsigned char[m_bi.bmiHeader.biSizeImage];
	AVISTREAMINFO a;
	AVIStreamInfo (m_pas, &a, sizeof (a));
	m_length=a.dwLength;
	hr=AVIStreamBeginStreaming (m_pas, 0, 100, 1000);	
	m_init=true;

    m_FrameRate = (double)a.dwRate / a.dwScale;
	
	m_pos=AVIStreamStart (m_pas);
	m_data=new BYTE[m_bi.bmiHeader.biSizeImage];
	if (m_bi.bmiHeader.biCompression!=0) 
	{
		hr=ICDecompressGetFormat (m_hic, &m_bi, &m_bi_out);
	}
	else m_bi_out=m_bi;
	m_frame.Create (m_bi_out.bmiHeader.biWidth, m_bi_out.bmiHeader.biHeight, m_bi_out.bmiHeader.biBitCount);
	return true;
}
VDTime AVIReadTunnelStream::PositionToTime(VDPosition pos) {
    AVISTREAMINFO asi;
    if (AVIStreamInfo(pas, &asi, sizeof asi))
        return 0;

    return VDRoundToInt64(pos * (double)asi.dwScale / (double)asi.dwRate * 1000000.0);
}
Пример #3
0
int AVIOBJ::OpenAVI(LPCSTR szFile)										// Opens An AVI File (szFile)
{

    AVIFileInit();												// Opens The AVIFile Library
    pgf=NULL;

    if (AVIStreamOpenFromFile(&pavi, szFile, streamtypeVIDEO, 0, OF_READ, NULL) !=0)
        return(0);

    AVIStreamInfo(pavi, &psi, sizeof(psi));						// Reads Information About The Stream Into psi
    width=psi.rcFrame.right-psi.rcFrame.left;					// Width Is Right Side Of Frame Minus Left
    height=psi.rcFrame.bottom-psi.rcFrame.top;					// Height Is Bottom Of Frame Minus Top

    lastframe=AVIStreamLength(pavi);							// The Last Frame Of The Stream

    mpf=AVIStreamSampleToTime(pavi,lastframe)/lastframe;		// Calculate Rough Milliseconds Per Frame

    bmih.biSize = sizeof (BITMAPINFOHEADER);					// Size Of The BitmapInfoHeader
    bmih.biPlanes = 1;											// Bitplanes
    bmih.biBitCount = 24;										// Bits Format We Want (24 Bit, 3 Bytes)
    bmih.biWidth = width;											// Width We Want
    bmih.biHeight = height;										// Height We Want
    bmih.biCompression = BI_RGB;								// Requested Mode = RGB

    hBitmap = CreateDIBSection (hdc, (BITMAPINFO*)(&bmih), DIB_RGB_COLORS, (void**)(&data), NULL, 0);
    SelectObject (hdc, hBitmap);								// Select hBitmap Into Our Device Context (hdc)

    pgf=AVIStreamGetFrameOpen(pavi, NULL);						// Create The PGETFRAME	Using Our Request Mode
    if (pgf==NULL) return(0);

    return(1);
}
VDPosition AVIReadTunnelStream::TimeToPosition(VDTime timeInUs) {
    AVISTREAMINFO asi;
    if (AVIStreamInfo(pas, &asi, sizeof asi))
        return 0;

    return VDRoundToInt64(timeInUs * (double)asi.dwRate / (double)asi.dwScale * (1.0 / 1000000.0));
}
Пример #5
0
static void test_ash1_corruption(void)
{
    COMMON_AVI_HEADERS cah;
    char filename[MAX_PATH];
    PAVIFILE pFile;
    int res;
    PAVISTREAM pStream1;
    AVISTREAMINFO asi1;

    GetTempPath(MAX_PATH, filename);
    strcpy(filename+strlen(filename), testfilename);

    /* Corrupt the sample size in the audio stream header */
    init_test_struct(&cah);
    cah.ash1.dwSampleSize = 0xdeadbeef;

    create_avi_file(&cah, filename);

    res = AVIFileOpen(&pFile, filename, OF_SHARE_DENY_WRITE, 0L);
    ok(res == 0, "Unable to open file: error=%u\n", res);

    res = AVIFileGetStream(pFile, &pStream1, 0, 1);
    ok(res == 0, "Unable to open audio stream: error=%u\n", res);

    res = AVIStreamInfo(pStream1, &asi1, sizeof(AVISTREAMINFO));
    ok(res == 0, "Unable to read stream info: error=%u\n", res);

    /* The result will still be 2, because the value is dynamically replaced with the nBlockAlign
       value from the stream format header. The next test will prove this */
    ok(asi1.dwSampleSize == 2, "got %u (expected 2)\n", asi1.dwSampleSize);

    AVIStreamRelease(pStream1);
    AVIFileRelease(pFile);
    ok(DeleteFile(filename) !=0, "Deleting file %s failed\n", filename);
}
Пример #6
0
static void test_ash1_corruption2(void)
{
    COMMON_AVI_HEADERS cah;
    char filename[MAX_PATH];
    PAVIFILE pFile;
    int res;
    PAVISTREAM pStream1;
    AVISTREAMINFO asi1;

    GetTempPath(MAX_PATH, filename);
    strcpy(filename+strlen(filename), testfilename);

    /* Corrupt the block alignment in the audio format header */
    init_test_struct(&cah);
    cah.pcmwf.wf.nBlockAlign = 0xdead;

    create_avi_file(&cah, filename);

    res = AVIFileOpen(&pFile, filename, OF_SHARE_DENY_WRITE, 0L);
    ok(res == 0, "Unable to open file: error=%u\n", res);

    res = AVIFileGetStream(pFile, &pStream1, 0, 1);
    ok(res == 0, "Unable to open audio stream: error=%u\n", res);

    ok(AVIStreamInfo(pStream1, &asi1, sizeof(AVISTREAMINFO)) == 0, "Unable to read stream info\n");

    /* The result will also be the corrupt value, as explained above. */
    ok(asi1.dwSampleSize == 0xdead, "got 0x%x (expected 0xdead)\n", asi1.dwSampleSize);

    AVIStreamRelease(pStream1);
    AVIFileRelease(pFile);
    ok(DeleteFile(filename) !=0, "Deleting file %s failed\n", filename);
}
Пример #7
0
bool CvCaptureAVI_VFW::open( const char* filename )
{
    close();
    icvInitCapture_VFW();

    if( !filename )
        return false;

    HRESULT hr = AVIFileOpen( &avifile, filename, OF_READ, NULL );
    if( SUCCEEDED(hr))
    {
        hr = AVIFileGetStream( avifile, &avistream, streamtypeVIDEO, 0 );
        if( SUCCEEDED(hr))
        {
            hr = AVIStreamInfo( avistream, &aviinfo, sizeof(aviinfo));
            if( SUCCEEDED(hr))
            {
                size.width = aviinfo.rcFrame.right - aviinfo.rcFrame.left;
                size.height = aviinfo.rcFrame.bottom - aviinfo.rcFrame.top;
                BITMAPINFOHEADER bmihdr = icvBitmapHeader( size.width, size.height, 24 );

                film_range.start_index = (int)aviinfo.dwStart;
                film_range.end_index = film_range.start_index + (int)aviinfo.dwLength;
                fps = (double)aviinfo.dwRate/aviinfo.dwScale;
                pos = film_range.start_index;
                getframe = AVIStreamGetFrameOpen( avistream, &bmihdr );
                if( getframe != 0 )
                    return true;
            }
        }
    }

    close();
    return false;
}
sint32 AVIReadTunnelStream::Info(VDAVIStreamInfo *pasi) {
    AVISTREAMINFO streamInfoW32;
    HRESULT hr = AVIStreamInfo(pas, &streamInfoW32, sizeof(streamInfoW32));

    if (FAILED(hr))
        return hr;

    ConvertAVIStreamInfo(*pasi, streamInfoW32);
    return S_OK;
}
Пример #9
0
bool AVI :: Load(std :: string fname,bool loopflag,Texture *tex)				// Opens An AVI File
{
	// copy over looping flag
	loop=loopflag;

	// do we have a texture manager?
	if(!tex)
		return false;
	// copy it over
	tman=tex;

	hdc=CreateCompatibleDC(0);									// Get a compatible DC
	hdd = DrawDibOpen();										// Grab A Device Context For Our Dib


	AVIFileInit();												// Opens The AVIFile Library

	// Opens The AVI Stream
	if (AVIStreamOpenFromFile(&pavi, fname.c_str(), streamtypeVIDEO, 0, OF_READ, NULL) !=0)
		return false;

	AVIStreamInfo(pavi, &psi, sizeof(psi));						// Reads Information About The Stream Into psi
	width=psi.rcFrame.right-psi.rcFrame.left;					// Width Is Right Side Of Frame Minus Left
	height=psi.rcFrame.bottom-psi.rcFrame.top;					// Height Is Bottom Of Frame Minus Top

	lastframe=AVIStreamLength(pavi);							// The Last Frame Of The Stream

	mpf=AVIStreamSampleToTime(pavi,lastframe)/lastframe;		// Calculate Rough Milliseconds Per Frame

	bmih.biSize = sizeof (BITMAPINFOHEADER);					// Size Of The BitmapInfoHeader
	bmih.biPlanes = 1;											// Bitplanes	
	bmih.biBitCount = 24;										// Bits Format We Want (24 Bit, 3 Bytes)
	bmih.biWidth = 256;											// Width We Want (256 Pixels)
	bmih.biHeight = 256;										// Height We Want (256 Pixels)
	bmih.biCompression = BI_RGB;								// Requested Mode = RGB

	hBitmap = CreateDIBSection (hdc, (BITMAPINFO*)(&bmih), DIB_RGB_COLORS, (void**)(&data), NULL, NULL);
	SelectObject (hdc, hBitmap);								// Select hBitmap Into Our Device Context (hdc)

	pgf=AVIStreamGetFrameOpen(pavi, NULL);						// Create The PGETFRAME	Using Our Request Mode
	if (pgf==NULL)
		return false;

	// create the texture
	Image img;
	img.Create(256,256,false);									// set dimensions of texture
	img.SetImage(data);											// set the texture information
	texid=tman->Create(&img);									// create the texture

	// clear the time position 
	pos=0;

	// success
	return true;
}
Пример #10
0
/*
---------------------------------------------------------------------------------------
- Opens An AVI File (szFile)
---------------------------------------------------------------------------------------
*/
bool AviVideoRenderer::OpenAVI(const char * szFile)
{
	// Opens The AVI Stream
	if (AVIStreamOpenFromFileA(&_AVR_pavi, szFile, streamtypeVIDEO, 0, OF_READ, NULL) !=0)
		return false;

	AVIStreamInfo(_AVR_pavi, &_AVR_psi, sizeof(_AVR_psi));						// Reads Information About The Stream Into psi
	_video_width=_AVR_psi.rcFrame.right-_AVR_psi.rcFrame.left;					// Width Is Right Side Of Frame Minus Left
	_video_height=_AVR_psi.rcFrame.bottom-_AVR_psi.rcFrame.top;					// Height Is Bottom Of Frame Minus Top

	_endFrame=AVIStreamLength(_AVR_pavi);							// The Last Frame Of The Stream

	_timeperframe=AVIStreamSampleToTime(_AVR_pavi,_endFrame)/_endFrame;		// Calculate Rough Milliseconds Per Frame


	int sizet = 1024;
	if((_video_width < 128) && (_video_height < 128))
		sizet = 128;
	else if((_video_width < 256) && (_video_height < 256))
		sizet = 256;
	else if((_video_width < 512) && (_video_height < 512))
		sizet = 512;

	_widths.push_back(sizet);
	_heights.push_back(sizet);

	// initialize the host texture
	InitializeTexture();


	_AVR_bmih.biSize = sizeof (BITMAPINFOHEADER);					// Size Of The BitmapInfoHeader
	_AVR_bmih.biPlanes = 1;											// Bitplanes
	_AVR_bmih.biBitCount = 24;										// Bits Format We Want (24 Bit, 3 Bytes)
	_AVR_bmih.biWidth = _widths[0];									// Width We Want
	_AVR_bmih.biHeight = _heights[0];								// Height We Want
	_AVR_bmih.biCompression = BI_RGB;								// Requested Mode = RGB

	_AVR_hBitmap = CreateDIBSection (_AVR_hdc, (BITMAPINFO*)(&_AVR_bmih), DIB_RGB_COLORS, (void**)(&_img_data), NULL, NULL);
	SelectObject (_AVR_hdc, _AVR_hBitmap);							// Select hBitmap Into Our Device Context (hdc)

	_AVR_pgf=AVIStreamGetFrameOpen(_AVR_pavi, NULL);				// Create The PGETFRAME	Using Our Request Mode


	_avi_opened = true;

	return(_AVR_pgf!=NULL);
}
Пример #11
0
void VideoReader::Open(CString strFilePath)
{    
    AVIFileInit();

    LONG hr;  
    hr = AVIStreamOpenFromFile(&m_pAviStream, strFilePath, streamtypeVIDEO, 0, OF_READ, NULL);
    if (hr != 0){ 
        // Handle failure.
        AfxMessageBox(L"Failed to open file, file must be an uncompressed video."); 
    }
    else
    {
        HRESULT          hr; 
        AVISTREAMINFO    strhdr; 
        LONG             lStreamSize; 
 

        // Determine the size of the format data using 
        // AVIStreamFormatSize. 
        AVIStreamFormatSize(m_pAviStream, 0, &lStreamSize); 
        if (lStreamSize > sizeof(m_bi)) // Format too large? 
            return; 

        lStreamSize = sizeof(m_bi); 
        hr = AVIStreamReadFormat(m_pAviStream, 0, &m_bi, &lStreamSize); // Read format 
        if (m_bi.biCompression != BI_RGB) // Wrong compression format? 
            return; 

        hr = AVIStreamInfo(m_pAviStream, &strhdr, sizeof(strhdr)); 

        // Create new AVI file using AVIFileOpen. 
        hr = AVIFileOpen(&m_pf, strFilePath + L".Processed.avi", OF_WRITE | OF_CREATE, NULL); 
        if (hr != 0) 
            return; 

        m_currentSize = AVIStreamStart(m_pAviStream);

        // Allocate memory for the bitmaps. 
        m_lpBuffer = (BYTE *)malloc(m_bi.biSizeImage); 
    }

}
Пример #12
0
BOOL FMPlayerDShow::GetAVIInfo(const tchar* pFileName)
{
	AVIFileInit();

	PAVIFILE pfile;
	BOOL bOK = FALSE; 
	if(AVIFileOpen(&pfile, pFileName, OF_SHARE_DENY_NONE, 0L) == 0)
	{
		AVIFILEINFO afi;
		memset(&afi, 0, sizeof(afi));
		AVIFileInfo(pfile, &afi, sizeof(AVIFILEINFO));

		CComPtr<IAVIStream> pavi;
		if(AVIFileGetStream(pfile, &pavi, streamtypeVIDEO, 0) == AVIERR_OK)
		{
			AVISTREAMINFO si;
			AVIStreamInfo(pavi, &si, sizeof(si));
			m_FourCC = FormatFourCC(si.fccHandler);
			m_FrameRate = (double)si.dwRate / (double)si.dwScale; 

			LONG lFormat; 
			if (0 == AVIStreamFormatSize(pavi, 0, &lFormat))
			{
				char* pBuf = new char[lFormat];
				if (0 == AVIStreamReadFormat(pavi, 0, pBuf, &lFormat))
				{
					BITMAPINFOHEADER* pHeader = (BITMAPINFOHEADER*)pBuf; 
					m_StreamFormat = FormatFourCC(pHeader->biCompression);
				}
				delete[] pBuf; 
			}

			bOK = TRUE; 
		}

		AVIFileRelease(pfile);
	}

	AVIFileExit();
	return bOK; 
}
Пример #13
0
bool CAviLoader::open( const char* filename )
{
    close();
    icvInitCapture_VFW();

    if( !filename )
        return false;

    HRESULT hr = AVIFileOpen( &avifile, filename, OF_READ, NULL );
    if( SUCCEEDED(hr))
    {
        hr = AVIFileGetStream( avifile, &avistream, streamtypeVIDEO, 0 );
        if( SUCCEEDED(hr))
        {
            hr = AVIStreamInfo( avistream, &aviinfo, sizeof(aviinfo));
            if( SUCCEEDED(hr))
            {
                //int fcc = aviinfo.fccHandler;
                data_offset = 0;
                size.width = aviinfo.rcFrame.right - aviinfo.rcFrame.left;
                size.height = aviinfo.rcFrame.bottom - aviinfo.rcFrame.top;
                BITMAPINFOHEADER bmih = icvBitmapHeader( size.width, size.height, 24 );

				if(frame)
					delete []frame;
				frame = new unsigned char[size.width*size.height*3];
                
                film_range.start_index = (int)aviinfo.dwStart;
                film_range.end_index = film_range.start_index + (int)aviinfo.dwLength;
                fps = (double)aviinfo.dwRate/aviinfo.dwScale;
                pos = film_range.start_index;
                getframe = AVIStreamGetFrameOpen( avistream, &bmih );
                if( getframe != 0 )
                    return true;
            }
        }
    }

    close();
    return false;
}
Пример #14
0
bool CAvi::OpenAVI( LPCWSTR szFile )
{
	AVISTREAMINFO psi;
	AVIFileInit();
	if( AVIStreamOpenFromFile( &m_pavi, szFile, streamtypeVIDEO, 0, OF_READ, NULL) !=0)
	{
		MessageBox( NULL, _T("Couldnt open the CAvi stream."), _T("VandaEngine Error"), MB_OK | MB_ICONERROR );
		return 0;
	}
	AVIStreamInfo(m_pavi, &psi, sizeof(psi));				// Reads Information About The Stream Into psi
	m_width=psi.rcFrame.right-psi.rcFrame.left;			// Width Is Right Side Of Frame Minus Left
	m_height=psi.rcFrame.bottom-psi.rcFrame.top;			// Height Is Bottom Of Frame Minus Top
	m_lastFrame = AVIStreamLength(m_pavi);	
	m_mpf=AVIStreamSampleToTime(m_pavi,m_lastFrame)/m_lastFrame;		// Calculate Rough Milliseconds Per Frame
	if( m_mpf == 0 )
	{
		MessageBox( NULL, _T("MPF is 0"), _T("VandaEngine Error"), MB_OK | MB_ICONINFORMATION );
		return 0;
	}

    BITMAPINFOHEADER bmih;
	bmih.biSize = sizeof (BITMAPINFOHEADER);					// Size Of The BitmapInfoHeader
	bmih.biPlanes = 1;											// Bitplanes	
	bmih.biBitCount = 24;										// Bits Format We Want (24 Bit, 3 Bytes)
	bmih.biWidth = 1024;											// Width We Want (512 Pixels)
	bmih.biHeight = 512;										// Height We Want (256 Pixels)
	bmih.biCompression = BI_RGB;								// Requested Mode = RGB

	m_hBitmap = CreateDIBSection (m_hDC, (BITMAPINFO*)(&bmih), DIB_RGB_COLORS, (void**)(&m_data), NULL, NULL);
	SelectObject (m_hDC, m_hBitmap);		// Select m_hBitmap Into Our Device Context (hdc)

	m_pgf=AVIStreamGetFrameOpen(m_pavi, NULL);	// Create The PGETFRAME	Using Our Request Mode
	if (m_pgf==NULL)
	{
		//An Error Occurred Opening The Frame
		MessageBox( NULL, _T("Couldn't open the CAvi frame."), _T("VandaEngine Error"), MB_OK | MB_ICONINFORMATION );
		return 0;
	}
	return 1;
}
Пример #15
0
bool CLoaderAVI::loadFromFile(const CString& fileName)
{
    CApplication::getApp()->log(CString::fromUTF8("Chargement de la vidéo %1").arg(fileName));

#ifdef T_SYSTEM_WINDOWS
    AVIStreamGetFrameClose(m_pgf);

    // Suppression des flux
    if (m_video)
        AVIStreamRelease(m_video);

    if (m_audio)
    {
        //AVIStreamRelease(m_audio);
        Game::soundEngine->removeMusic(m_audio);
        delete m_audio;
        m_audio = nullptr;
    }

    Game::textureManager->deleteTexture(m_texture);
    AVIFileExit();
#endif

    m_time = 0;
    m_play = false;

    // Suppression de la précédente texture
    if (m_texture)
    {
        Game::textureManager->deleteTexture(m_texture);
    }

#ifdef T_SYSTEM_WINDOWS

    AVIFileInit();

    // Ouverture du flux vidéo
    if (AVIStreamOpenFromFile(&m_video, fileName.toCharArray(), streamtypeVIDEO, 0, OF_READ, nullptr))
    {
        CApplication::getApp()->log(CString::fromUTF8("AVIStreamOpenFromFile : impossible de lire le flux video."), ILogger::Error);
        return false;
    }

    // Infos sur le stream video
    AVISTREAMINFO psi;

    if (AVIStreamInfo(m_video, &psi, sizeof(psi)))
    {
        CApplication::getApp()->log("AVIStreamInfo donne une erreur", ILogger::Error);
        return false;
    }

    // Dimensions de la vidéo
    m_width = psi.rcFrame.right - psi.rcFrame.left;
    m_height = psi.rcFrame.bottom - psi.rcFrame.top;

    m_fileName = fileName;

    m_pixels.resize(4 * m_width * m_height);

    for (int i = 0; i < m_width * m_height; ++i)
    {
        m_pixels[4 * i + 0] = 0x00;
        m_pixels[4 * i + 1] = 0x00;
        m_pixels[4 * i + 2] = 0x00;
        m_pixels[4 * i + 3] = 0xFF;
    }

    // Création de la texture
    CImage img(m_width, m_height, reinterpret_cast<CColor *>(&m_pixels[0]));

    m_texture = Game::textureManager->loadTexture(m_fileName, img, CTextureManager::FilterNone);


    m_lastFrame = AVIStreamLength(m_video);

    if (m_lastFrame == 0)
    {
        return false;
    }

    m_frameTime = AVIStreamSampleToTime(m_video, m_lastFrame) / m_lastFrame;
    m_pgf = AVIStreamGetFrameOpen(m_video, nullptr);

    // On ne peut pas récupérer les frames
    if (m_pgf == nullptr)
    {
        CApplication::getApp()->log("AVIStreamGetFrameOpen retourne un pointeur nul", ILogger::Error);
        return false;
    }

    // Ouverture du flux audio
    m_audio = new CMusic();
    m_audio->loadFromVideo(m_fileName);

    if (m_loop)
    {
        m_audio->setLoop();
    }

    m_audio->play();
    Game::soundEngine->addMusic(m_audio);

#endif

    //m_play = true;
    return true;
}
Пример #16
0
static FIMULTIBITMAP* ReadFromAvi(const char* filename) {
	int err=0;
	AVIFileInit();
	
	PAVISTREAM pavi; // Handle To An Open Stream
	if( AVIStreamOpenFromFile(&pavi, filename, streamtypeVIDEO, 0, OF_READ, NULL) != 0) {
		AVIFileExit();
		return NULL;
	}



	AVISTREAMINFO		psi;				// Pointer To A Structure Containing Stream Info
	AVIStreamInfo(pavi, &psi, sizeof(psi));				// Reads Information About The Stream Into psi
	int width  = psi.rcFrame.right-psi.rcFrame.left;			// Width Is Right Side Of Frame Minus Left
	int height = psi.rcFrame.bottom-psi.rcFrame.top;			// Height Is Bottom Of Frame Minus Top
	int frameCount = AVIStreamLength(pavi);							// The Last Frame Of The Stream

	double mpf = AVIStreamSampleToTime(pavi, frameCount) / (double)frameCount;		// Calculate Rough Milliseconds Per Frame

	PGETFRAME pgf = AVIStreamGetFrameOpen(pavi, NULL);				// Create The PGETFRAME Using Our Request Mode
	if (pgf==NULL)
	{
		// An Error Occurred Opening The Frame
		error("Failed To Open frame from AVI");
	}

	//HDC hdc = GetDC(0);

	HDRAWDIB hdd = DrawDibOpen();													// Handle For Our Dib

	BITMAPINFOHEADER bmih;										// Header Information For DrawDibDraw Decoding
	bmih.biSize = sizeof (BITMAPINFOHEADER);					// Size Of The BitmapInfoHeader
	bmih.biPlanes = 1;											// Bitplanes	
	bmih.biBitCount = 24;										// Bits Format We Want (24 Bit, 3 Bytes)
	bmih.biWidth = width;										// Width We Want (256 Pixels)
	bmih.biHeight = height;										// Height We Want (256 Pixels)
	bmih.biCompression = BI_RGB;								// Requested Mode = RGB

	char		*data;						// Pointer To Texture Data
	HBITMAP hBitmap = CreateDIBSection(hdc, (BITMAPINFO*)(&bmih), DIB_RGB_COLORS, (void**)(&data), NULL, NULL);
	SelectObject(hdc, hBitmap);								// Select hBitmap Into Our Device Context (hdc)

	// create a new freeimage anim
	someError=false;
	FIMULTIBITMAP* ret = FreeImage_OpenMultiBitmap(FIF_TIFF, "temp.tiff", TRUE, FALSE);
	if (!ret || someError) {
		error("Couldnt create multibitmap");
	}

	for (int frame=0; frame<frameCount; frame++) {
		fprintf(stderr, "Loading frame %i\n", frame);
		// Grab Data From The AVI Stream
		LPBITMAPINFOHEADER lpbi = (LPBITMAPINFOHEADER)AVIStreamGetFrame(pgf, frame);	
		// Pointer To Data Returned By AVIStreamGetFrame
		// (Skip The Header Info To Get To The Data)
		char* pdata = (char *)lpbi + lpbi->biSize + lpbi->biClrUsed * sizeof(RGBQUAD);	
		
		// Convert Data To Requested Bitmap Format
		DrawDibDraw(hdd, hdc, 0, 0, width, height, lpbi, pdata, 0, 0, width, height, 0);

		// copy into the freeimage thing
		FIBITMAP* fiBitmap = FreeImage_ConvertFromRawBits((BYTE*)data, width, height, width*3, 24, 0xFF0000, 0x00FF00, 0x0000FF);
/*		BYTE* src = (BYTE*)data;
		for (int y=0; y<height; y++) {
			BYTE* dst = FreeImage_GetScanLine(fiBitmap, y);
			for (int x=0; x<width; x++) {
				//src++;
				*dst++ = *src++;
				*dst++ = *src++;
				*dst++ = *src++;
			}
		}
*/
		FIBITMAP* grayBitmap = FreeImage_ConvertToGreyscale(fiBitmap);
		FreeImage_Unload(fiBitmap);

		FreeImage_AppendPage(ret, grayBitmap);
	}
	FreeImage_CloseMultiBitmap(ret);
	ret = FreeImage_OpenMultiBitmap(FIF_TIFF, "temp.tiff", FALSE, TRUE);

	DeleteObject(hBitmap);										// Delete The Device Dependant Bitmap Object
	DrawDibClose(hdd);											// Closes The DrawDib Device Context
	AVIStreamGetFrameClose(pgf);								// Deallocates The GetFrame Resources
	AVIStreamRelease(pavi);										// Release The Stream
	AVIFileExit();												// Release The File

	return ret;
}
int avisynth_read_header() {
    avs = (AVISynthContext *) av_mallocz(sizeof(AVISynthContext));
    HRESULT res;
    AVIFILEINFO info;
    DWORD id;


    AVIFileInit();


    res = AVIFileOpen(&avs->file, read_config_filepath(), OF_READ|OF_SHARE_DENY_WRITE, NULL);
    if (res != S_OK)
    {
        av_log(s, AV_LOG_ERROR, "AVIFileOpen failed with error %ld", res);
        AVIFileExit();
        return -1;
    }

    res = AVIFileInfo(avs->file, &info, sizeof(info));
    if (res != S_OK)
    {
        av_log(s, AV_LOG_ERROR, "AVIFileInfo failed with error %ld", res);
        AVIFileExit();
        return -1;
    }

    avs->streams = (AVISynthStream *) av_mallocz(info.dwStreams * sizeof(AVISynthStream));
    assert(info.dwStreams == 1);
    for (id=0; id<info.dwStreams; id++)
    {
        stream = &avs->streams[id];
        stream->read = 0;
        if (AVIFileGetStream(avs->file, &stream->handle, 0, id) == S_OK)
        {
            if (AVIStreamInfo(stream->handle, &stream->info, sizeof(stream->info)) == S_OK)
            {
                if (stream->info.fccType == streamtypeAUDIO)
                {

                    assert(false); // don't do audio yet
                    LONG struct_size = sizeof(WAVEFORMATEX);
                    if (AVIStreamReadFormat(stream->handle, 0, &wvfmt, &struct_size) != S_OK)
                        continue;

                    /* audio:
                    st = avformat_new_stream(s, NULL);
                    st->id = id;
                    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

                    st->codec->block_align = wvfmt.nBlockAlign;
                    st->codec->channels = wvfmt.nChannels;
                    st->codec->sample_rate = wvfmt.nSamplesPerSec;
                    st->codec->bit_rate = wvfmt.nAvgBytesPerSec * 8;
                    st->codec->bits_per_coded_sample = wvfmt.wBitsPerSample;


                    st->codec->codec_tag = wvfmt.wFormatTag;
                    st->codec->codec_id = ff_wav_codec_get_id(wvfmt.wFormatTag, st->codec->bits_per_coded_sample);
                    */
                    stream->chunck_samples = wvfmt.nSamplesPerSec * (__int64)info.dwScale / (__int64) info.dwRate;
                    stream->chunck_size = stream->chunck_samples * wvfmt.nChannels * wvfmt.wBitsPerSample / 8;
                }
                else if (stream->info.fccType == streamtypeVIDEO)
                {

                    LONG struct_size = sizeof(BITMAPINFO);

                    stream->chunck_size = stream->info.dwSampleSize;
                    stream->chunck_samples = 1;

                    if (AVIStreamReadFormat(stream->handle, 0, &savedVideoFormat, &struct_size) != S_OK)
                        continue;

                    /*

                    stream->info.dwRate is numerator
                    stream->info.dwScale is denominator [?]
                    savedVideoFormat.bmiHeader.biWidth

                    */
                    /*st = avformat_new_stream(s, NULL);
                    st->id = id;
                    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
                    st->r_frame_rate.num = stream->info.dwRate;
                    st->r_frame_rate.den = stream->info.dwScale;

                    st->codec->width = savedVideoFormat.bmiHeader.biWidth;
                    st->codec->height = savedVideoFormat.bmiHeader.biHeight;

                    st->codec->bits_per_coded_sample = savedVideoFormat.bmiHeader.biBitCount;
                    st->codec->bit_rate = (uint64_t)stream->info.dwSampleSize * (uint64_t)stream->info.dwRate * 8 / (uint64_t)stream->info.dwScale;
                    st->codec->codec_tag = savedVideoFormat.bmiHeader.biCompression;
                    st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, savedVideoFormat.bmiHeader.biCompression);
                    if (st->codec->codec_id == CODEC_ID_RAWVIDEO && savedVideoFormat.bmiHeader.biCompression== BI_RGB) {
                      st->codec->extradata = av_malloc(9 + FF_INPUT_BUFFER_PADDING_SIZE);
                      if (st->codec->extradata) {
                        st->codec->extradata_size = 9;
                        memcpy(st->codec->extradata, "BottomUp", 9);
                      }
                    }


                    st->duration = stream->info.dwLength;
                    */
                }
                else
                {
                    AVIStreamRelease(stream->handle);
                    continue;
                }

                avs->nb_streams++;

                // st->codec->stream_codec_tag = stream->info.fccHandler;

                //avpriv_set_pts_info(st, 64, info.dwScale, info.dwRate);
                //st->start_time = stream->info.dwStart; // wow what is the dshow equivalent? hmm...
            }
        }
    }

    return 0;
}
Пример #18
0
  int load_avi_file()
  {
    bitm.valid=false;
    const char *avifilename = filename->get().c_str();
    HRESULT res = AVIFileOpen(&m_aviFile, avifilename, OF_READ, NULL);
    if (res!=AVIERR_OK)
    {
      printf("Couldn't open avi file %s\n",filename->get().c_str());
      return 0;
    }

    res = AVIFileGetStream(m_aviFile, &streamVid, streamtypeVIDEO, 0);
    if (res!=AVIERR_OK)
    {
      AVIFileRelease(m_aviFile);
      m_aviFile = NULL;
      streamVid = NULL;
      printf("Couldn't get stream");
      return 0;
    }

    LONG format_length = 0;

    AVIStreamReadFormat(streamVid,0,NULL,&format_length);

    //if format_data is not a reasonable size, fail
    if (format_length>128)
    {
      printf("Format data too big");
      return 0;
    }
    //make room for at least 128 bytes, sizeof(int) aligned
    int format_data[(128/sizeof(int)) + 1];

    AVIStreamReadFormat(streamVid,0,format_data,&format_length);
        
    BITMAPINFOHEADER *bi = (BITMAPINFOHEADER *)format_data;

    //only 24 bit output is supported
    if (bi->biBitCount!=24)
    {
      printf("Bitcount %d not supported",bi->biBitCount);
      return 0;
    }
    
    // Create the PGETFRAME
    getFrame = AVIStreamGetFrameOpen(streamVid,NULL);
	
    //unable to decode the .avi?
    if (getFrame==NULL)
    {
      printf("AVIStreamGetFrameOpen returned NULL");
      return 0;
    }
        
    // Define the length of the video (necessary for loop reading)
		// and its size.
		num_frames = AVIStreamLength(streamVid);
      
    if (num_frames<1)
    {
      printf("Zero frames");
      return 0;
    }
    
    AVISTREAMINFO psi;
    AVIStreamInfo(streamVid, &psi, sizeof(AVISTREAMINFO));

    width  = psi.rcFrame.right - psi.rcFrame.left;
		height = psi.rcFrame.bottom - psi.rcFrame.top;

    dwRate = psi.dwRate;
    dwScale = psi.dwScale;

    bitm.bpp=(int)(bi->biBitCount/8);
    bitm.bformat=GL_BGR;
    bitm.size_x=width;
    bitm.size_y=height;
    bitm.valid=true;

    return 1;
  }
Пример #19
0
static int avisynth_read_header(AVFormatContext *s)
{
  AVISynthContext *avs = s->priv_data;
  HRESULT res;
  AVIFILEINFO info;
  DWORD id;
  AVStream *st;
  AVISynthStream *stream;
  wchar_t filename_wchar[1024] = { 0 };
  char filename_char[1024] = { 0 };

  AVIFileInit();

  /* avisynth can't accept UTF-8 filename */
  MultiByteToWideChar(CP_UTF8, 0, s->filename, -1, filename_wchar, 1024);
  WideCharToMultiByte(CP_THREAD_ACP, 0, filename_wchar, -1, filename_char, 1024, NULL, NULL);
  res = AVIFileOpen(&avs->file, filename_char, OF_READ|OF_SHARE_DENY_WRITE, NULL);
  if (res != S_OK)
    {
      av_log(s, AV_LOG_ERROR, "AVIFileOpen failed with error %ld", res);
      AVIFileExit();
      return -1;
    }

  res = AVIFileInfo(avs->file, &info, sizeof(info));
  if (res != S_OK)
    {
      av_log(s, AV_LOG_ERROR, "AVIFileInfo failed with error %ld", res);
      AVIFileExit();
      return -1;
    }

  avs->streams = av_mallocz(info.dwStreams * sizeof(AVISynthStream));

  for (id=0; id<info.dwStreams; id++)
    {
      stream = &avs->streams[id];
      stream->read = 0;
      if (AVIFileGetStream(avs->file, &stream->handle, 0, id) == S_OK)
        {
          if (AVIStreamInfo(stream->handle, &stream->info, sizeof(stream->info)) == S_OK)
            {
              if (stream->info.fccType == streamtypeAUDIO)
                {
                  WAVEFORMATEX wvfmt;
                  LONG struct_size = sizeof(WAVEFORMATEX);
                  if (AVIStreamReadFormat(stream->handle, 0, &wvfmt, &struct_size) != S_OK)
                    continue;

                  st = avformat_new_stream(s, NULL);
                  st->id = id;
                  st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

                  st->codec->block_align = wvfmt.nBlockAlign;
                  st->codec->channels = wvfmt.nChannels;
                  st->codec->sample_rate = wvfmt.nSamplesPerSec;
                  st->codec->bit_rate = wvfmt.nAvgBytesPerSec * 8;
                  st->codec->bits_per_coded_sample = wvfmt.wBitsPerSample;

                  stream->chunck_samples = wvfmt.nSamplesPerSec * (uint64_t)info.dwScale / (uint64_t)info.dwRate;
                  stream->chunck_size = stream->chunck_samples * wvfmt.nChannels * wvfmt.wBitsPerSample / 8;

                  st->codec->codec_tag = wvfmt.wFormatTag;
                  st->codec->codec_id = ff_wav_codec_get_id(wvfmt.wFormatTag, st->codec->bits_per_coded_sample);
                }
              else if (stream->info.fccType == streamtypeVIDEO)
                {
                  BITMAPINFO imgfmt;
                  LONG struct_size = sizeof(BITMAPINFO);

                  stream->chunck_size = stream->info.dwSampleSize;
                  stream->chunck_samples = 1;

                  if (AVIStreamReadFormat(stream->handle, 0, &imgfmt, &struct_size) != S_OK)
                    continue;

                  st = avformat_new_stream(s, NULL);
                  st->id = id;
                  st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
                  st->r_frame_rate.num = stream->info.dwRate;
                  st->r_frame_rate.den = stream->info.dwScale;

                  st->codec->width = imgfmt.bmiHeader.biWidth;
                  st->codec->height = imgfmt.bmiHeader.biHeight;

                  st->codec->bits_per_coded_sample = imgfmt.bmiHeader.biBitCount;
                  st->codec->bit_rate = (uint64_t)stream->info.dwSampleSize * (uint64_t)stream->info.dwRate * 8 / (uint64_t)stream->info.dwScale;
                  st->codec->codec_tag = imgfmt.bmiHeader.biCompression;
                  st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, imgfmt.bmiHeader.biCompression);
                  if (st->codec->codec_id == CODEC_ID_RAWVIDEO && imgfmt.bmiHeader.biCompression== BI_RGB) {
                    st->codec->extradata = av_malloc(9 + FF_INPUT_BUFFER_PADDING_SIZE);
                    if (st->codec->extradata) {
                      st->codec->extradata_size = 9;
                      memcpy(st->codec->extradata, "BottomUp", 9);
                    }
                  }


                  st->duration = stream->info.dwLength;
                }
              else
                {
                  AVIStreamRelease(stream->handle);
                  continue;
                }

              avs->nb_streams++;

              st->codec->stream_codec_tag = stream->info.fccHandler;

              avpriv_set_pts_info(st, 64, info.dwScale, info.dwRate);
              st->start_time = stream->info.dwStart;
            }
        }
    }

  return 0;
}
Пример #20
0
static void test_default_data(void)
{
    COMMON_AVI_HEADERS cah;
    char filename[MAX_PATH];
    PAVIFILE pFile;
    int res;
    LONG lSize;
    PAVISTREAM pStream0;
    PAVISTREAM pStream1;
    AVISTREAMINFO asi0;
    AVISTREAMINFO asi1;
    WAVEFORMATEX wfx;

    GetTempPath(MAX_PATH, filename);
    strcpy(filename+strlen(filename), testfilename);

    init_test_struct(&cah);
    create_avi_file(&cah, filename);

    res = AVIFileOpen(&pFile, filename, OF_SHARE_DENY_WRITE, 0L);
    ok(res != AVIERR_BADFORMAT, "Unable to open file: error1=%u\n", AVIERR_BADFORMAT);
    ok(res != AVIERR_MEMORY, "Unable to open file: error2=%u\n", AVIERR_MEMORY);
    ok(res != AVIERR_FILEREAD, "Unable to open file: error3=%u\n", AVIERR_FILEREAD);
    ok(res != AVIERR_FILEOPEN, "Unable to open file: error4=%u\n", AVIERR_FILEOPEN);
    ok(res != REGDB_E_CLASSNOTREG, "Unable to open file: error5=%u\n", REGDB_E_CLASSNOTREG);
    ok(res == 0, "Unable to open file: error=%u\n", res);

    res = AVIFileGetStream(pFile, &pStream0, 0, 0);
    ok(res == 0, "Unable to open video stream: error=%u\n", res);

    res = AVIFileGetStream(pFile, &pStream1, 0, 1);
    ok(res == 0, "Unable to open audio stream: error=%u\n", res);

    res = AVIStreamInfo(pStream0, &asi0, sizeof(AVISTREAMINFO));
    ok(res == 0, "Unable to read stream info: error=%u\n", res);

    res = AVIStreamInfo(pStream1, &asi1, sizeof(AVISTREAMINFO));
    ok(res == 0, "Unable to read stream info: error=%u\n", res);

    res = AVIStreamReadFormat(pStream0, AVIStreamStart(pStream1), NULL, &lSize);
    ok(res == 0, "Unable to read format size: error=%u\n", res);

    res = AVIStreamReadFormat(pStream1, AVIStreamStart(pStream1), &wfx, &lSize);
    ok(res == 0, "Unable to read format: error=%u\n", res);

    ok(asi0.fccType == streamtypeVIDEO, "got 0x%x (expected streamtypeVIDEO)\n", asi0.fccType);
    ok(asi0.fccHandler == 0x30323449, "got 0x%x (expected 0x30323449)\n", asi0.fccHandler);
    ok(asi0.dwFlags == 0, "got %u (expected 0)\n", asi0.dwFlags);
    ok(asi0.wPriority == 0, "got %u (expected 0)\n", asi0.wPriority);
    ok(asi0.wLanguage == 0, "got %u (expected 0)\n", asi0.wLanguage);
    ok(asi0.dwScale == 1001, "got %u (expected 1001)\n", asi0.dwScale);
    ok(asi0.dwRate == 30000, "got %u (expected 30000)\n", asi0.dwRate);
    ok(asi0.dwStart == 0, "got %u (expected 0)\n", asi0.dwStart);
    ok(asi0.dwLength == 1, "got %u (expected 1)\n", asi0.dwLength);
    ok(asi0.dwInitialFrames == 0, "got %u (expected 0)\n", asi0.dwInitialFrames);
    ok(asi0.dwSuggestedBufferSize == 0, "got %u (expected 0)\n", asi0.dwSuggestedBufferSize);
    ok(asi0.dwQuality == 0xffffffff, "got 0x%x (expected 0xffffffff)\n", asi0.dwQuality);
    ok(asi0.dwSampleSize == 0, "got %u (expected 0)\n", asi0.dwSampleSize);
    ok(asi0.rcFrame.left == 0, "got %u (expected 0)\n", asi0.rcFrame.left);
    ok(asi0.rcFrame.top == 0, "got %u (expected 0)\n", asi0.rcFrame.top);
    ok(asi0.rcFrame.right == 8, "got %u (expected 8)\n", asi0.rcFrame.right);  /* these are based on the values in the mah and not */
    ok(asi0.rcFrame.bottom == 6, "got %u (expected 6)\n", asi0.rcFrame.bottom);/* on the ones in the ash which are 0 here */
    ok(asi0.dwEditCount == 0, "got %u (expected 0)\n", asi0.dwEditCount);
    ok(asi0.dwFormatChangeCount == 0, "got %u (expected 0)\n", asi0.dwFormatChangeCount);

    ok(asi1.fccType == streamtypeAUDIO, "got 0x%x (expected streamtypeVIDEO)\n", asi1.fccType);
    ok(asi1.fccHandler == 0x1, "got 0x%x (expected 0x1)\n", asi1.fccHandler);
    ok(asi1.dwFlags == 0, "got %u (expected 0)\n", asi1.dwFlags);
    ok(asi1.wPriority == 0, "got %u (expected 0)\n", asi1.wPriority);
    ok(asi1.wLanguage == 0, "got %u (expected 0)\n", asi1.wLanguage);
    ok(asi1.dwScale == 1, "got %u (expected 1)\n", asi1.dwScale);
    ok(asi1.dwRate == 11025, "got %u (expected 11025)\n", asi1.dwRate);
    ok(asi1.dwStart == 0, "got %u (expected 0)\n", asi1.dwStart);
    ok(asi1.dwLength == 1637, "got %u (expected 1637)\n", asi1.dwLength);
    ok(asi1.dwInitialFrames == 0, "got %u (expected 0)\n", asi1.dwInitialFrames);
    ok(asi1.dwSuggestedBufferSize == 0, "got %u (expected 0)\n", asi1.dwSuggestedBufferSize);
    ok(asi1.dwQuality == 0xffffffff, "got 0x%x (expected 0xffffffff)\n", asi1.dwQuality);
    ok(asi1.dwSampleSize == 2, "got %u (expected 2)\n", asi1.dwSampleSize);
    ok(asi1.rcFrame.left == 0, "got %u (expected 0)\n", asi1.rcFrame.left);
    ok(asi1.rcFrame.top == 0, "got %u (expected 0)\n", asi1.rcFrame.top);
    ok(asi1.rcFrame.right == 0, "got %u (expected 0)\n", asi1.rcFrame.right);
    ok(asi1.rcFrame.bottom == 0, "got %u (expected 0)\n", asi1.rcFrame.bottom);
    ok(asi1.dwEditCount == 0, "got %u (expected 0)\n", asi1.dwEditCount);
    ok(asi1.dwFormatChangeCount == 0, "got %u (expected 0)\n", asi1.dwFormatChangeCount);

    ok(wfx.wFormatTag == 1, "got %u (expected 1)\n",wfx.wFormatTag);
    ok(wfx.nChannels == 2, "got %u (expected 2)\n",wfx.nChannels);
    ok(wfx.wFormatTag == 1, "got %u (expected 1)\n",wfx.wFormatTag);
    ok(wfx.nSamplesPerSec == 11025, "got %u (expected 11025)\n",wfx.nSamplesPerSec);
    ok(wfx.nAvgBytesPerSec == 22050, "got %u (expected 22050)\n",wfx.nAvgBytesPerSec);
    ok(wfx.nBlockAlign == 2, "got %u (expected 2)\n",wfx.nBlockAlign);

    AVIStreamRelease(pStream0);
    AVIStreamRelease(pStream1);
    AVIFileRelease(pFile);
    ok(DeleteFile(filename) !=0, "Deleting file %s failed\n", filename);
}
Пример #21
0
static void test_EditStreamSetInfo(void)
{
    PAVISTREAM stream = NULL;
    HRESULT hres;
    AVISTREAMINFO info, info2;

    hres = CreateEditableStream(&stream, NULL);
    ok(hres == AVIERR_OK, "got 0x%08X, expected AVIERR_OK\n", hres);


    if(0)    /* Crashing - first parameter not checked */
        hres = EditStreamSetInfo(NULL, &info, sizeof(AVISTREAMINFO) );

             /* Size parameter is somehow checked (notice the crash with size=-1 below) */
    hres = EditStreamSetInfo(stream, NULL, 0);
    ok( hres == AVIERR_BADSIZE, "got 0x%08X, expected AVIERR_BADSIZE\n", hres);

    hres = EditStreamSetInfo(stream, NULL, sizeof(AVISTREAMINFO)-1 );
    ok( hres == AVIERR_BADSIZE, "got 0x%08X, expected AVIERR_BADSIZE\n", hres);

    if(0)
    {        /* Crashing - second parameter not checked */
        hres = EditStreamSetInfo(stream, NULL, sizeof(AVISTREAMINFO) );

        hres = EditStreamSetInfo(stream, NULL, -1);
        ok( hres == AVIERR_BADSIZE, "got 0x%08X, expected AVIERR_BADSIZE\n", hres);
    }

    hres = AVIStreamInfo(stream, &info, sizeof(AVISTREAMINFO) );
    ok( hres == 0, "got 0x%08X, expected 0\n", hres);

             /* Does the function check what's it's updating ? */

#define IS_INFO_UPDATED(m) do { \
    hres = EditStreamSetInfo(stream, &info, sizeof(AVISTREAMINFO) ); \
    ok( hres == 0, "got 0x%08X, expected 0\n", hres); \
    hres = AVIStreamInfo(stream, &info2, sizeof(AVISTREAMINFO) ); \
    ok( hres == 0, "got 0x%08X, expected 0\n", hres); \
    ok( info2.m == info.m, "EditStreamSetInfo did not update "#m" parameter\n" ); \
    } while(0)

    info.dwStart++;
    IS_INFO_UPDATED(dwStart);
    info.dwStart = 0;
    IS_INFO_UPDATED(dwStart);

    info.wPriority++;
    IS_INFO_UPDATED(wPriority);
    info.wPriority = 0;
    IS_INFO_UPDATED(wPriority);

    info.wLanguage++;
    IS_INFO_UPDATED(wLanguage);
    info.wLanguage = 0;
    IS_INFO_UPDATED(wLanguage);

    info.dwScale++;
    IS_INFO_UPDATED(dwScale);
    info.dwScale = 0;
    IS_INFO_UPDATED(dwScale);

    info.dwRate++;
    IS_INFO_UPDATED(dwRate);
    info.dwRate = 0;
    IS_INFO_UPDATED(dwRate);

    info.dwQuality++;
    IS_INFO_UPDATED(dwQuality);
    info.dwQuality = 0;
    IS_INFO_UPDATED(dwQuality);
    info.dwQuality = -2;
    IS_INFO_UPDATED(dwQuality);
    info.dwQuality = ICQUALITY_HIGH+1;
    IS_INFO_UPDATED(dwQuality);

    info.rcFrame.left = 0;
    IS_INFO_UPDATED(rcFrame.left);
    info.rcFrame.top = 0;
    IS_INFO_UPDATED(rcFrame.top);
    info.rcFrame.right = 0;
    IS_INFO_UPDATED(rcFrame.right);
    info.rcFrame.bottom = 0;
    IS_INFO_UPDATED(rcFrame.bottom);

    info.rcFrame.left = -1;
    IS_INFO_UPDATED(rcFrame.left);
    info.rcFrame.top = -1;
    IS_INFO_UPDATED(rcFrame.top);
    info.rcFrame.right = -1;
    IS_INFO_UPDATED(rcFrame.right);
    info.rcFrame.bottom = -1;
    IS_INFO_UPDATED(rcFrame.bottom);
    AVIStreamRelease(stream);
#undef IS_INFO_UPDATED
}
Пример #22
0
AvisynthVideoProvider::AvisynthVideoProvider(agi::fs::path const& filename, std::string const& colormatrix)
{
	agi::acs::CheckFileRead(filename);

	std::lock_guard<std::mutex> lock(avs.GetMutex());

#ifdef _WIN32
	if (agi::fs::HasExtension(filename, "avi")) {
		// Try to read the keyframes before actually opening the file as trying
		// to open the file while it's already open can cause problems with
		// badly written VFW decoders
		AVIFileInit();

		PAVIFILE pfile;
		long hr = AVIFileOpen(&pfile, filename.c_str(), OF_SHARE_DENY_WRITE, 0);
		if (hr) {
			warning = "Unable to open AVI file for reading keyframes:\n";
			switch (hr) {
				case AVIERR_BADFORMAT:
					warning += "The file is corrupted, incomplete or has an otherwise bad format.";
					break;
				case AVIERR_MEMORY:
					warning += "The file could not be opened because of insufficient memory.";
					break;
				case AVIERR_FILEREAD:
					warning += "An error occurred reading the file. There might be a problem with the storage media.";
					break;
				case AVIERR_FILEOPEN:
					warning += "The file could not be opened. It might be in use by another application, or you do not have permission to access it.";
					break;
				case REGDB_E_CLASSNOTREG:
					warning += "There is no handler installed for the file extension. This might indicate a fundamental problem in your Video for Windows installation, and can be caused by extremely stripped Windows installations.";
					break;
				default:
					warning += "Unknown error.";
					break;
			}
			goto file_exit;
		}

		PAVISTREAM ppavi;
		if (hr = AVIFileGetStream(pfile, &ppavi, streamtypeVIDEO, 0)) {
			warning = "Unable to open AVI video stream for reading keyframes:\n";
			switch (hr) {
				case AVIERR_NODATA:
					warning += "The file does not contain a usable video stream.";
					break;
				case AVIERR_MEMORY:
					warning += "Not enough memory.";
					break;
				default:
					warning += "Unknown error.";
					break;
			}
			goto file_release;
		}

		AVISTREAMINFO avis;
		if (FAILED(AVIStreamInfo(ppavi,&avis,sizeof(avis)))) {
			warning = "Unable to read keyframes from AVI file:\nCould not get stream information.";
			goto stream_release;
		}

		for (size_t i = 0; i < avis.dwLength; i++) {
			if (AVIStreamIsKeyFrame(ppavi, i))
				keyframes.push_back(i);
		}

		// If every frame is a keyframe then just discard the keyframe data as it's useless
		if (keyframes.size() == (size_t)avis.dwLength)
			keyframes.clear();

		// Clean up
stream_release:
		AVIStreamRelease(ppavi);
file_release:
		AVIFileRelease(pfile);
file_exit:
		AVIFileExit();
	}
#endif

	try {
		auto script = Open(filename);

		// Check if video was loaded properly
		if (!script.IsClip() || !script.AsClip()->GetVideoInfo().HasVideo())
			throw VideoNotSupported("No usable video found");

		vi = script.AsClip()->GetVideoInfo();
		if (!vi.IsRGB()) {
			/// @todo maybe read ColorMatrix hints for d2v files?
			AVSValue args[2] = { script, "Rec601" };
			bool force_bt601 = OPT_GET("Video/Force BT.601")->GetBool() || colormatrix == "TV.601";
			bool bt709 = vi.width > 1024 || vi.height >= 600;
			if (bt709 && (!force_bt601 || colormatrix == "TV.709")) {
				args[1] = "Rec709";
				colorspace = "TV.709";
			}
			else
				colorspace = "TV.601";
			const char *argnames[2] = { 0, "matrix" };
			script = avs.GetEnv()->Invoke("ConvertToRGB32", AVSValue(args, 2), argnames);
		}
		else
			colorspace = "None";

		RGB32Video = avs.GetEnv()->Invoke("Cache", script).AsClip();
		vi = RGB32Video->GetVideoInfo();
		fps = (double)vi.fps_numerator / vi.fps_denominator;
	}
	catch (AvisynthError const& err) {
		throw VideoOpenError("Avisynth error: " + std::string(err.msg));
	}
}
Пример #23
0
static int startavi(struct anim *anim)
{

	AviError avierror;
#if defined(_WIN32) && !defined(FREE_WINDOWS)
	HRESULT hr;
	int i, firstvideo = -1;
	int streamcount;
	BYTE abFormat[1024];
	LONG l;
	LPBITMAPINFOHEADER lpbi;
	AVISTREAMINFO avis;

	streamcount = anim->streamindex;
#endif

	anim->avi = MEM_callocN(sizeof(AviMovie), "animavi");

	if (anim->avi == NULL) {
		printf("Can't open avi: %s\n", anim->name);
		return -1;
	}

	avierror = AVI_open_movie(anim->name, anim->avi);

#if defined(_WIN32) && !defined(FREE_WINDOWS)
	if (avierror == AVI_ERROR_COMPRESSION) {
		AVIFileInit();
		hr = AVIFileOpen(&anim->pfile, anim->name, OF_READ, 0L);
		if (hr == 0) {
			anim->pfileopen = 1;
			for (i = 0; i < MAXNUMSTREAMS; i++) {
				if (AVIFileGetStream(anim->pfile, &anim->pavi[i], 0L, i) != AVIERR_OK) {
					break;
				}
				
				AVIStreamInfo(anim->pavi[i], &avis, sizeof(avis));
				if ((avis.fccType == streamtypeVIDEO) && (firstvideo == -1)) {
					if (streamcount > 0) {
						streamcount--;
						continue;
					}
					anim->pgf = AVIStreamGetFrameOpen(anim->pavi[i], NULL);
					if (anim->pgf) {
						firstvideo = i;

						/* get stream length */
						anim->avi->header->TotalFrames = AVIStreamLength(anim->pavi[i]);

						/* get information about images inside the stream */
						l = sizeof(abFormat);
						AVIStreamReadFormat(anim->pavi[i], 0, &abFormat, &l);
						lpbi = (LPBITMAPINFOHEADER)abFormat;
						anim->avi->header->Height = lpbi->biHeight;
						anim->avi->header->Width = lpbi->biWidth;
					}
					else {
						FIXCC(avis.fccHandler);
						FIXCC(avis.fccType);
						printf("Can't find AVI decoder for type : %4.4hs/%4.4hs\n",
						       (LPSTR)&avis.fccType,
						       (LPSTR)&avis.fccHandler);
					}
				}
			}

			/* register number of opened avistreams */
			anim->avistreams = i;

			/*
			 * Couldn't get any video streams out of this file
			 */
			if ((anim->avistreams == 0) || (firstvideo == -1)) {
				avierror = AVI_ERROR_FORMAT;
			}
			else {
				avierror = AVI_ERROR_NONE;
				anim->firstvideo = firstvideo;
			}
		}
		else {
			AVIFileExit();
		}
	}
#endif

	if (avierror != AVI_ERROR_NONE) {
		AVI_print_error(avierror);
		printf("Error loading avi: %s\n", anim->name);
		free_anim_avi(anim);
		return -1;
	}
	
	anim->duration = anim->avi->header->TotalFrames;
	anim->params = NULL;

	anim->x = anim->avi->header->Width;
	anim->y = anim->avi->header->Height;
	anim->interlacing = 0;
	anim->orientation = 0;
	anim->framesize = anim->x * anim->y * 4;

	anim->curposition = 0;
	anim->preseek = 0;

	/*  printf("x:%d y:%d size:%d interl:%d dur:%d\n", anim->x, anim->y, anim->framesize, anim->interlacing, anim->duration);*/

	return 0;
}
Пример #24
0
	/////////////////////////////////////////////////////////
	//open avi file. preapre avi streams
	/////////////////////////////////////////////////////////
	CAviMan::OpenAviFile(LPTSTR szFileName)
	{
		LONG hr;

	    hr = AVIFileOpen(&m_aviFile, szFileName, 0, 0L);			//open AVI file

		if(hr!=0)
		{
			return 1;
		}

		PAVISTREAM	aviStream;

		//
		// Get all the streams from the new file
		//
		for (DWORD i = 0; i <= MAX_AVI_STREAM; i++)
		{
			if (AVIFileGetStream(m_aviFile, &aviStream, 0L, i) != AVIERR_OK)
			break;

			if (i == MAX_AVI_STREAM) {
				AVIStreamRelease(aviStream);
				break;
			}

			m_aviStream[i] = aviStream;				//save all streams
		}


		m_dwNumStreams = i;					//save real number of streams

		//
		// Couldn't get any streams out of this file
		//
		if (i == 0 && i != MAX_AVI_STREAM)
		{
	   //   ErrMsg(TEXT("Unable to open %s"), lpszFile);
			if (m_aviFile)
				AVIFileRelease(m_aviFile);
			return 1;
		}



		AVISTREAMINFO     aviStreamInfo;


		m_aviVideoStream = NULL;

		//
		// Walk through and init all streams loaded
		//
		for (i = 0; i < m_dwNumStreams; i++)
		{

			AVIStreamInfo(m_aviStream[i], &aviStreamInfo, sizeof(aviStreamInfo));

			//
			// Initialize video streams for getting decompressed frames to display
			//
			if (aviStreamInfo.fccType == streamtypeVIDEO) 
			{

		
				if (m_aviVideoStream == NULL) 
				{

					m_dwScale=aviStreamInfo.dwScale;
					m_dwRate =aviStreamInfo.dwRate;

					//
					// Remember the first video stream --- treat it specially
					//
					m_aviVideoStream = m_aviStream[i];

					m_aviGetFrame = AVIStreamGetFrameOpen(m_aviStream[i], NULL);

				}

			}//if aviStreamInfo==streamVideo 

		}//for i=0..dwNumStreams


		m_dwCurrentFrame = 0;
		m_dwStartFrame = 0;
		m_dwTotalFrame  = 0;

		return 0;

	}
Пример #25
0
void VideoHelper::OpenVideo(CString strFilePath, FrameData& data)
{    
    AVIFileInit();

    LONG hr;  
    hr = AVIStreamOpenFromFile(&m_pAviStream, strFilePath, streamtypeVIDEO, 0, OF_READ, NULL);
    if (hr != 0){ 
        // Handle failure.
        AfxMessageBox(L"Failed to open file."); 
    }
    else
    {
        PAVIFILE         pf; 
        PAVISTREAM       psSmall; 
        HRESULT          hr; 
        AVISTREAMINFO    strhdr; 
        BITMAPINFOHEADER bi; 
        BITMAPINFOHEADER biNew; 
        LONG             lStreamSize; 
        LPVOID           lpOld; 
        LPVOID           lpNew; 

        // Determine the size of the format data using 
        // AVIStreamFormatSize. 
        AVIStreamFormatSize(m_pAviStream, 0, &lStreamSize); 
        if (lStreamSize > sizeof(bi)) // Format too large? 
            return; 

        lStreamSize = sizeof(bi); 
        hr = AVIStreamReadFormat(m_pAviStream, 0, &bi, &lStreamSize); // Read format 
        if (bi.biCompression != BI_RGB) // Wrong compression format? 
            return; 

        hr = AVIStreamInfo(m_pAviStream, &strhdr, sizeof(strhdr)); 

        // Create new AVI file using AVIFileOpen. 
        hr = AVIFileOpen(&pf, strFilePath + L".Processed.avi", OF_WRITE | OF_CREATE, NULL); 
        if (hr != 0) 
            return; 

        // Set parameters for the new stream. 
        biNew = bi; 

        SetRect(&strhdr.rcFrame, 0, 0, (int) biNew.biWidth, 
            (int) biNew.biHeight); 

        // Create a stream using AVIFileCreateStream. 
        hr = AVIFileCreateStream(pf, &psSmall, &strhdr); 
        if (hr != 0) {            //Stream created OK? If not, close file. 
            AVIFileRelease(pf); 
            return; 
        } 

        // Set format of new stream using AVIStreamSetFormat. 
        hr = AVIStreamSetFormat(psSmall, 0, &biNew, sizeof(biNew)); 
        if (hr != 0) { 
            AVIStreamRelease(psSmall); 
            AVIFileRelease(pf); 
            return; 
        } 

        // Allocate memory for the bitmaps. 
        lpOld = malloc(bi.biSizeImage); 

        // Read the stream data using AVIStreamRead. 
        for (lStreamSize = AVIStreamStart(m_pAviStream); lStreamSize <
            AVIStreamEnd(m_pAviStream)/*1500*/; lStreamSize++) { 
                //Context::Oversubscribe(true);
                hr = AVIStreamRead(m_pAviStream, lStreamSize, 1, lpOld, bi.biSizeImage,
                    NULL, NULL); 
                //Context::Oversubscribe(false);
                //memcpy_s(lpNew, bi.biSizeImage, lpOld, bi.biSizeImage);
                data.m_BBP = bi.biBitCount;
                data.m_ColorPlanes = bi.biPlanes;
                data.m_EndHeight = bi.biHeight;
                data.m_EndWidth = bi.biWidth;
                data.m_pFrame = (BYTE*)lpOld;
                data.m_Pitch = bi.biWidth * (bi.biBitCount / 8);
                data.m_Size = bi.biSizeImage;
                data.m_StartHeight = 0;
                data.m_StartWidth = 0;
                lpNew = m_pVideoAgent->ProcessFrame(data);
               

                if(NULL != lpNew)
                {
                    // Save the compressed data using AVIStreamWrite.
                    hr = AVIStreamWrite(psSmall, lStreamSize, 1, lpNew,
                    biNew.biSizeImage, AVIIF_KEYFRAME, NULL, NULL);
                }
        } 
        free(lpOld);
        // Close the stream and file. 
        AVIStreamRelease(psSmall); 
        AVIFileRelease(pf); 
    }
    AVIFileExit();
}
Пример #26
0
static int avisynth_read_header(AVFormatContext *s, AVFormatParameters *ap)
{
  AVISynthContext *avs = s->priv_data;
  HRESULT res;
  AVIFILEINFO info;
  DWORD id;
  AVStream *st;
  AVISynthStream *stream;

  AVIFileInit();

  res = AVIFileOpen(&avs->file, s->filename, OF_READ|OF_SHARE_DENY_WRITE, NULL);
  if (res != S_OK)
    {
      av_log(s, AV_LOG_ERROR, "AVIFileOpen failed with error %ld", res);
      AVIFileExit();
      return -1;
    }

  res = AVIFileInfo(avs->file, &info, sizeof(info));
  if (res != S_OK)
    {
      av_log(s, AV_LOG_ERROR, "AVIFileInfo failed with error %ld", res);
      AVIFileExit();
      return -1;
    }

  avs->streams = av_mallocz(info.dwStreams * sizeof(AVISynthStream));

  for (id=0; id<info.dwStreams; id++)
    {
      stream = &avs->streams[id];
      stream->read = 0;
      if (AVIFileGetStream(avs->file, &stream->handle, 0, id) == S_OK)
        {
          if (AVIStreamInfo(stream->handle, &stream->info, sizeof(stream->info)) == S_OK)
            {
              if (stream->info.fccType == streamtypeAUDIO)
                {
                  WAVEFORMATEX wvfmt;
                  LONG struct_size = sizeof(WAVEFORMATEX);
                  if (AVIStreamReadFormat(stream->handle, 0, &wvfmt, &struct_size) != S_OK)
                    continue;

                  st = av_new_stream(s, id);
                  st->codec->codec_type = CODEC_TYPE_AUDIO;

                  st->codec->block_align = wvfmt.nBlockAlign;
                  st->codec->channels = wvfmt.nChannels;
                  st->codec->sample_rate = wvfmt.nSamplesPerSec;
                  st->codec->bit_rate = wvfmt.nAvgBytesPerSec * 8;
                  st->codec->bits_per_sample = wvfmt.wBitsPerSample;

                  stream->chunck_samples = wvfmt.nSamplesPerSec * (uint64_t)info.dwScale / (uint64_t)info.dwRate;
                  stream->chunck_size = stream->chunck_samples * wvfmt.nChannels * wvfmt.wBitsPerSample / 8;

                  st->codec->codec_tag = wvfmt.wFormatTag;
                  st->codec->codec_id = wav_codec_get_id(wvfmt.wFormatTag, st->codec->bits_per_sample);
                }
              else if (stream->info.fccType == streamtypeVIDEO)
                {
                  BITMAPINFO imgfmt;
                  LONG struct_size = sizeof(BITMAPINFO);

                  stream->chunck_size = stream->info.dwSampleSize;
                  stream->chunck_samples = 1;

                  if (AVIStreamReadFormat(stream->handle, 0, &imgfmt, &struct_size) != S_OK)
                    continue;

                  st = av_new_stream(s, id);
                  st->codec->codec_type = CODEC_TYPE_VIDEO;
                  st->r_frame_rate.num = stream->info.dwRate;
                  st->r_frame_rate.den = stream->info.dwScale;

                  st->codec->width = imgfmt.bmiHeader.biWidth;
                  st->codec->height = imgfmt.bmiHeader.biHeight;

                  st->codec->bits_per_sample = imgfmt.bmiHeader.biBitCount;
                  st->codec->bit_rate = (uint64_t)stream->info.dwSampleSize * (uint64_t)stream->info.dwRate * 8 / (uint64_t)stream->info.dwScale;
                  st->codec->codec_tag = imgfmt.bmiHeader.biCompression;
                  st->codec->codec_id = codec_get_id(codec_bmp_tags, imgfmt.bmiHeader.biCompression);

                  st->duration = stream->info.dwLength;
                }
              else
                {
                  AVIStreamRelease(stream->handle);
                  continue;
                }

              avs->nb_streams++;

              st->codec->stream_codec_tag = stream->info.fccHandler;

              av_set_pts_info(st, 64, info.dwScale, info.dwRate);
              st->start_time = stream->info.dwStart;
            }
        }
    }

  return 0;
}
Пример #27
0
bool CAviToBmp::GetStreamInfo(AVISTREAMINFO& Info) const
{
	return(!AVIStreamInfo(m_pStream, &Info, sizeof(Info)));
}
Пример #28
0
int imFileFormatAVI::Open(const char* file_name)
{
  /* initializes avi file library, can be called many times */
  AVIFileInit();

  /* open existing file */
  HRESULT hr = AVIFileOpen(&file, file_name, OF_READ, NULL);
  if (hr != 0)
  {
    AVIFileExit();

    if (hr == AVIERR_FILEOPEN)
      return IM_ERR_OPEN;
    else if (hr == AVIERR_BADFORMAT || hr == REGDB_E_CLASSNOTREG)
      return IM_ERR_FORMAT;
    else
      return IM_ERR_ACCESS;
  }

  /* get the video stream */
  hr = AVIFileGetStream(file, &stream, streamtypeVIDEO, 0);
  if (hr != 0)
  {
    AVIFileRelease(this->file);
    AVIFileExit();

    if (hr == AVIERR_NODATA)
      return IM_ERR_DATA;
    else
      return IM_ERR_ACCESS;
  }

  /* get stream info */
  AVISTREAMINFO streaminfo;
  AVIStreamInfo(stream, &streaminfo, sizeof(AVISTREAMINFO));

  this->image_count = streaminfo.dwLength;
  this->fps = (float)streaminfo.dwRate / (float)streaminfo.dwScale;

  if (streaminfo.fccHandler == mmioFOURCC('D','I','B',' '))
    strcpy(this->compression, "NONE");
  else if (streaminfo.fccHandler == mmioFOURCC('M','R','L','E'))
    strcpy(this->compression, "RLE");
  else if (streaminfo.fccHandler == mmioFOURCC('c','v','i','d'))
    strcpy(this->compression, "CINEPACK");    
  else
  {
    DWORD handler = streaminfo.fccHandler;
    this->compression[0] = (char)handler;
    this->compression[1] = (char)(handler >> 8);
    this->compression[2] = (char)(handler >> 16);
    this->compression[3] = (char)(handler >> 24);
    this->compression[4] = 0;
  }

  this->frame = 0;
  this->use_compressor = 0;
  this->dib = 0;
  this->current_frame = 0;

  return IM_ERR_NONE;
}
Пример #29
0
BOOL CALLBACK aviaudioOpenDevice(HWND hwnd, PAVISTREAM pavi)
{
	MMRESULT            mmResult;
	LPVOID              lpFormat;
	LONG                cbFormat;
	AVISTREAMINFO       strhdr;

	if (!pavi)          // no wave data to play
		return FALSE;

	if (shWaveOut)      // already something playing
		return TRUE;

	spavi = pavi;

	recalc = 1;

	AVIStreamInfo(pavi, &strhdr, sizeof(strhdr));

	slSampleSize = (LONG) strhdr.dwSampleSize;
	if (slSampleSize <= 0 || slSampleSize > AUDIO_BUFFER_SIZE)
		return FALSE;

	//AVIStreamFormatSize(pavi, 0, &cbFormat);
	AVIStreamFormatSize(pavi, AVIStreamStart(pavi), &cbFormat);

	lpFormat = GlobalAllocPtr(GHND, cbFormat);
	if (!lpFormat)
		return FALSE;

	//AVIStreamReadFormat(pavi, 0, lpFormat, &cbFormat);
	AVIStreamReadFormat(pavi, AVIStreamStart(pavi), lpFormat, &cbFormat);

	sdwSamplesPerSec = ((LPWAVEFORMAT) lpFormat)->nSamplesPerSec;
	sdwBytesPerSec = ((LPWAVEFORMAT) lpFormat)->nAvgBytesPerSec;

	mmResult = waveOutOpen(&shWaveOut, (UINT)WAVE_MAPPER, (WAVEFORMATEX *) lpFormat,
		(DWORD) (UINT) hwnd, 0L, CALLBACK_WINDOW);

	// Maybe we failed because someone is playing sound already.
	// Shut any sound off, and try once more before giving up.
	if (mmResult) {
		sndPlaySound(NULL, 0);
		mmResult = waveOutOpen(&shWaveOut, (UINT)WAVE_MAPPER, (WAVEFORMATEX *) lpFormat,
			(DWORD) (UINT)hwnd, 0L, CALLBACK_WINDOW);
	}

	if (mmResult != 0) {
		return FALSE;
	}

	for (swBuffers = 0; swBuffers < MAX_AUDIO_BUFFERS; swBuffers++) {
		if (!(salpAudioBuf[swBuffers] = (LPWAVEHDR)GlobalAllocPtr(GMEM_MOVEABLE | GMEM_SHARE, (DWORD)(sizeof(WAVEHDR) + AUDIO_BUFFER_SIZE))))
			break;
		salpAudioBuf[swBuffers]->dwFlags = WHDR_DONE;
		salpAudioBuf[swBuffers]->lpData = (LPSTR) salpAudioBuf[swBuffers] + sizeof(WAVEHDR);
		salpAudioBuf[swBuffers]->dwBufferLength = AUDIO_BUFFER_SIZE;
		if (!waveOutPrepareHeader(shWaveOut, salpAudioBuf[swBuffers], sizeof(WAVEHDR)))
			continue;

		GlobalFreePtr((LPSTR) salpAudioBuf[swBuffers]);
		break;
	}

	if (swBuffers < MIN_AUDIO_BUFFERS) {
		aviaudioCloseDevice();
		return FALSE;
	}

	swBuffersOut = 0;
	swNextBuffer = 0;

	sfPlaying = FALSE;

	return TRUE;
}
Пример #30
0
void CRotateAVIDlg::ProcessAVI(const TCHAR *source_filename, const TCHAR *dest_filename, eRotation rot)
{
	TCHAR error_buf[1024];

    PAVIFILE source_avi = 0;
    PAVIFILE dest_avi = 0;
    PAVISTREAM pSrcVidStream = 0;
    PAVISTREAM pSrcAudioStream = 0;
	PAVISTREAM pDestVidStream = 0;
	PAVISTREAM pDestAudioStream = 0;
	char *pSrcBuffer = 0;
	char *pJPGBuffer = 0;
	char *pDecompBuffer = 0;
	char *pRotateBuffer = 0;
	char *pDestBuffer = 0;

    AVIFileInit();

	// source setup

    if (AVIFileOpen(&source_avi, source_filename, OF_READ, NULL) != AVIERR_OK)
	{
		_stprintf(error_buf, TEXT("Couldn't open file %s"), source_filename);
		MessageBox(error_buf);
		goto cleanup;
	}

	AVIFILEINFO src_avi_info;
    AVIFileInfo(source_avi, &src_avi_info, sizeof(AVIFILEINFO));

    if (AVIFileGetStream(source_avi, &pSrcVidStream, streamtypeVIDEO, 0) != AVIERR_OK)
    {
		_stprintf(error_buf, TEXT("No video stream in %s"), source_filename);
		MessageBox(error_buf);
		goto cleanup;
    }

	BITMAPINFOHEADER srcBIH;
	long srcvidstreamsize;
    AVIStreamFormatSize(pSrcVidStream, 0, &srcvidstreamsize); 
    if (srcvidstreamsize > sizeof(BITMAPINFOHEADER))
	{
		_stprintf(error_buf, TEXT("Unable to handle video stream format in %s"), source_filename);
		MessageBox(error_buf);
		goto cleanup;
	}
 
    srcvidstreamsize = sizeof(BITMAPINFOHEADER); 
    if (AVIStreamReadFormat(pSrcVidStream, 0, &srcBIH, &srcvidstreamsize) != AVIERR_OK)
	{
		_stprintf(error_buf, TEXT("Error reading stream format in %s"), source_filename);
		MessageBox(error_buf);
		goto cleanup;
	}
    if (srcBIH.biCompression != MKFOURCC('M','J','P','G'))
	{
		_stprintf(error_buf, TEXT("%s is not motion JPEG format"), source_filename);
		MessageBox(error_buf);
		goto cleanup;
	}
 
	AVISTREAMINFO vidstream_info;
    if (AVIStreamInfo(pSrcVidStream, &vidstream_info, sizeof(AVISTREAMINFO)) != AVIERR_OK)
	{
		_stprintf(error_buf, TEXT("Error reading stream info in %s"), source_filename);
		MessageBox(error_buf);
		goto cleanup;
	}

    int firstVidSrcFrame = AVIStreamStart(pSrcVidStream);
    if (firstVidSrcFrame == -1)
	{
		_stprintf(error_buf, TEXT("Video stream start error in %s"), source_filename);
		MessageBox(error_buf);
		goto cleanup;
	}
    int numVidSrcFrames = AVIStreamLength(pSrcVidStream);
    if (numVidSrcFrames == -1)
	{
		_stprintf(error_buf, TEXT("Video stream length error in %s"), source_filename);
		MessageBox(error_buf);
		goto cleanup;
	}

    AVIFileGetStream(source_avi, &pSrcAudioStream, streamtypeAUDIO, 0);
	int firstAudioSrcFrame = 0;
	int numAudioSrcFrames = 0;
	if (pSrcAudioStream)
	{
		firstAudioSrcFrame = AVIStreamStart(pSrcAudioStream);
		if (firstAudioSrcFrame == -1)
		{
			_stprintf(error_buf, TEXT("Audio stream start error in %s"), source_filename);
			MessageBox(error_buf);
			goto cleanup;
		}
		numAudioSrcFrames = AVIStreamLength(pSrcAudioStream);
		if (numAudioSrcFrames == -1)
		{
			_stprintf(error_buf, TEXT("Audio stream length error in %s"), source_filename);
			MessageBox(error_buf);
			goto cleanup;
		}
	}

	// dest setup

	BITMAPINFOHEADER destBIH;
	destBIH = srcBIH;
	if (rot != CW_180)
	{
		destBIH.biWidth = srcBIH.biHeight;
		destBIH.biHeight = srcBIH.biWidth;
	}

    if (AVIFileOpen(&dest_avi, dest_filename, OF_CREATE | OF_WRITE, NULL) != AVIERR_OK)
	{
		_stprintf(error_buf, TEXT("Couldn't open file %s"), dest_filename);
		MessageBox(error_buf);
		goto cleanup;
	}
	vidstream_info.rcFrame.left = vidstream_info.rcFrame.top = 0;
	vidstream_info.rcFrame.right = destBIH.biWidth;
	vidstream_info.rcFrame.bottom = destBIH.biHeight;
 
    if (AVIFileCreateStream(dest_avi, &pDestVidStream, &vidstream_info) != AVIERR_OK)
	{
		_stprintf(error_buf, TEXT("Error creating video stream in %s"), dest_filename);
		MessageBox(error_buf);
		goto cleanup;
	}
 
    if (AVIStreamSetFormat(pDestVidStream, 0, &destBIH, sizeof(BITMAPINFOHEADER)) != AVIERR_OK)
	{ 
		_stprintf(error_buf, TEXT("Error setting video stream format in %s"), dest_filename);
		MessageBox(error_buf);
		goto cleanup;
    } 

    if (AVIStreamSetFormat(pDestVidStream, 0, &destBIH, sizeof(BITMAPINFOHEADER)) != AVIERR_OK)
	{ 
		_stprintf(error_buf, TEXT("Error setting video stream format in %s"), dest_filename);
		MessageBox(error_buf);
		goto cleanup;
    } 

	// video memory
	int img_rgb_size = srcBIH.biHeight * srcBIH.biWidth * 3;
	pSrcBuffer = new char[img_rgb_size];
	pJPGBuffer = new char[img_rgb_size];
	pDecompBuffer = new char[img_rgb_size];
	pRotateBuffer = new char[img_rgb_size];
	pDestBuffer = new char[img_rgb_size];

	long bytes_read;
	long bytes_written;

	for (int i = firstVidSrcFrame; i < numVidSrcFrames; ++i)
	{
		if (AVIStreamRead(pSrcVidStream, i, 1, pSrcBuffer, img_rgb_size, &bytes_read, 0) != AVIERR_OK)
		{
			_stprintf(error_buf, TEXT("Error reading video stream from %s"), source_filename);
			MessageBox(error_buf);
			goto cleanup;
		}

		// well-form the jpg
		int jpglen = ConstructWellFormedJPEG(pSrcBuffer, pJPGBuffer, bytes_read);
		// decompress
		JPEGHandler jpgh_decomp(pJPGBuffer, jpglen);
		jpgh_decomp.DecompressToRGB(pDecompBuffer, img_rgb_size);
		// rotate
		int destx, desty;
		char *pRotSrc;
		char *pRotDest;
		switch (rot)
		{
		case CW_90:
			for (int srcy = 0; srcy < srcBIH.biHeight; ++srcy)
			{
				for (int srcx = 0; srcx < srcBIH.biWidth; ++srcx)
				{
					destx = srcBIH.biHeight-1-srcy;
					desty = srcx;
					pRotSrc = &pDecompBuffer[(srcy * srcBIH.biWidth + srcx) * 3];
					pRotDest = &pRotateBuffer[(desty * srcBIH.biHeight + destx) * 3];

					*pRotDest++ = *pRotSrc++;
					*pRotDest++ = *pRotSrc++;
					*pRotDest++ = *pRotSrc++;
				}
			}
			break;

		case CW_180:
			for (int srcy = 0; srcy < srcBIH.biHeight; ++srcy)
			{
				for (int srcx = 0; srcx < srcBIH.biWidth; ++srcx)
				{
					destx = srcBIH.biWidth-1-srcx;
					desty = srcBIH.biHeight-1-srcy;
					pRotSrc = &pDecompBuffer[(srcy * srcBIH.biWidth + srcx) * 3];
					pRotDest = &pRotateBuffer[(desty * srcBIH.biWidth + destx) * 3];

					*pRotDest++ = *pRotSrc++;
					*pRotDest++ = *pRotSrc++;
					*pRotDest++ = *pRotSrc++;
				}
			}
			break;

		case ACW_90:
			for (int srcy = 0; srcy < srcBIH.biHeight; ++srcy)
			{
				for (int srcx = 0; srcx < srcBIH.biWidth; ++srcx)
				{
					destx = srcy;
					desty = srcBIH.biWidth-1-srcx;
					pRotSrc = &pDecompBuffer[(srcy * srcBIH.biWidth + srcx) * 3];
					pRotDest = &pRotateBuffer[(desty * srcBIH.biHeight + destx) * 3];

					*pRotDest++ = *pRotSrc++;
					*pRotDest++ = *pRotSrc++;
					*pRotDest++ = *pRotSrc++;
				}
			}
			break;
		}
		// compress
		JPEGHandler jpgh_comp(pRotateBuffer, img_rgb_size);
		if (rot != CW_180)
			destBIH.biSizeImage = jpgh_comp.CompressFromRGB(pDestBuffer, img_rgb_size, srcBIH.biHeight, srcBIH.biWidth);
		else
			destBIH.biSizeImage = jpgh_comp.CompressFromRGB(pDestBuffer, img_rgb_size, srcBIH.biWidth, srcBIH.biHeight);

		if (AVIStreamWrite(pDestVidStream, i, 1, pDestBuffer, destBIH.biSizeImage, AVIIF_KEYFRAME, NULL, &bytes_written) != AVIERR_OK)
		{
			_stprintf(error_buf, TEXT("Error writing video stream to %s"), dest_filename);
			MessageBox(error_buf);
			goto cleanup;
		}
	} 
 
cleanup:
	delete[] pSrcBuffer;
	delete[] pDestBuffer;
	delete[] pJPGBuffer;
	delete[] pDecompBuffer;
	delete[] pRotateBuffer;
	if (pDestAudioStream) AVIStreamRelease(pDestAudioStream);
	if (pDestVidStream) AVIStreamRelease(pDestVidStream);
	if (pSrcAudioStream) AVIStreamRelease(pSrcAudioStream);
	if (pSrcVidStream) AVIStreamRelease(pSrcVidStream);
	if (dest_avi) AVIFileRelease(dest_avi);
	if (source_avi) AVIFileRelease(source_avi);

	AVIFileExit();
}