Example #1
0
AviFile::AviFile(const char* fname, const Rect& r, int frame_rate)
: filename(fname), rect(r), fps(frame_rate), play(false), pfile(0),
ps(0), ps_comp(0), nframe(0), nsamp(0), iserr(false)
{
    Print("\n\nAviFile(%s, w=%d, h=%d, f=%d FPS)\n", fname, r.w, r.h, fps);
    frame_size = r.w * r.h * 3;

    AVIFileInit();
    HRESULT hr = AVIFileOpen(&pfile, fname, OF_WRITE|OF_CREATE, 0);

    if (hr != AVIERR_OK) {
        Print("AviFile - open failed. %08x\n", hr);
        iserr = true;
        return;
    }

    Print("AviFile - open successful\n");

    AVISTREAMINFO strhdr; 
    ZeroMemory(&strhdr,sizeof(strhdr));

    strhdr.fccType    = streamtypeVIDEO;
    strhdr.fccHandler = 0; 
    strhdr.dwScale    = 1000 / fps;
    strhdr.dwRate     = 1000;
    strhdr.dwSuggestedBufferSize  = frame_size;

    SetRect(&strhdr.rcFrame, 0, 0, r.w, r.h);

    hr = AVIFileCreateStream(pfile, &ps, &strhdr);

    if (hr != AVIERR_OK) {
        Print("AviFile - create stream failed. %08x\n", hr);
        iserr = true;
        return;
    }

    Print("AviFile - create stream successful\n");

    AVICOMPRESSOPTIONS opts; 
    ZeroMemory(&opts,sizeof(opts));
    opts.fccType      = streamtypeVIDEO;
    //opts.fccHandler = mmioFOURCC('W','M','V','3');
    opts.fccHandler   = mmioFOURCC('D','I','B',' ');  // (full frames)
    opts.dwFlags      = 8;

    hr = AVIMakeCompressedStream(&ps_comp, ps, &opts, 0);
    if (hr != AVIERR_OK) {
        Print("AviFile - compressed stream failed. %08x\n", hr);
        iserr=true; 
        return;
    }

    Print("AviFile - make compressed stream successful\n");

    BITMAPINFOHEADER bmih;
    ZeroMemory(&bmih, sizeof(BITMAPINFOHEADER));

    bmih.biSize          = sizeof(BITMAPINFOHEADER);
    bmih.biBitCount      = 24;
    bmih.biCompression   = BI_RGB;
    bmih.biWidth         = rect.w;
    bmih.biHeight        = rect.h;
    bmih.biPlanes        = 1;
    bmih.biSizeImage     = frame_size;

    hr = AVIStreamSetFormat(ps_comp, 0, &bmih, sizeof(BITMAPINFOHEADER));

    if (hr != AVIERR_OK) {
        Print("AviFile - stream format failed. %08x\n", hr);
        iserr=true; 
        return;
    }

    Print("AviFile - stream format successful\n");
}
Example #2
0
void AVICreate(struct AVIFile** avi_out)
{
	*avi_out = new AVIFile;
	memset(*avi_out, 0, sizeof(AVIFile));
	AVIFileInit();
}
Example #3
0
AviFile::AviFile(const char* fname)
: filename(fname), fps(0), play(true), pfile(0), ps(0), ps_comp(0),
nframe(0), nsamp(0), iserr(false), frame_size(0)
{
    AVIFileInit();
}
Example #4
0
void CAviHelper::AVItoBmp(const wstring& strAVIFileName, const wstring& strBmpDir)
{
	AVIFileInit();
	PAVIFILE avi;
	int res = AVIFileOpen(&avi, WS2S(strAVIFileName).c_str(), OF_READ, NULL);
	int n = GetLastError();
	if (res!=AVIERR_OK)
	{
		//an error occures
		if (avi!=NULL)
			AVIFileRelease(avi);
		return ;
	}
	
	AVIFILEINFO avi_info;
	AVIFileInfo(avi, &avi_info, sizeof(AVIFILEINFO));
	PAVISTREAM pStream;
	res=AVIFileGetStream(avi, &pStream, streamtypeVIDEO /*video stream*/, 0 /*first stream*/);
	if (res!=AVIERR_OK)
	{
		if (pStream!=NULL)
			AVIStreamRelease(pStream);
		AVIFileExit();
		return ;
	}
	
	//do some task with the stream
	int iNumFrames;
	int iFirstFrame;
	iFirstFrame = AVIStreamStart(pStream);
	if (iFirstFrame==-1)
	{
		//Error getteing the frame inside the stream
		if (pStream!=NULL)
			AVIStreamRelease(pStream);
		AVIFileExit();
		return ;
	}
	
	iNumFrames = AVIStreamLength(pStream);
	if (iNumFrames==-1)
	{
		//Error getteing the number of frames inside the stream
		if (pStream!=NULL)
			AVIStreamRelease(pStream);
		AVIFileExit();
		return ;
	}
	
	//getting bitmap from frame
	BITMAPINFOHEADER bih;
	ZeroMemory(&bih, sizeof(BITMAPINFOHEADER));
	bih.biBitCount=24; //24 bit per pixel
	bih.biClrImportant=0;
	bih.biClrUsed = 0;
	bih.biCompression = BI_RGB;
	bih.biPlanes = 1;
	bih.biSize = 40;
	bih.biXPelsPerMeter = 0;
	bih.biYPelsPerMeter = 0;
	
	//calculate total size of RGBQUAD scanlines (DWORD aligned)
	bih.biSizeImage = (((bih.biWidth * 3) + 3) & 0xFFFC) * bih.biHeight ;
	PGETFRAME pFrame;
	pFrame=AVIStreamGetFrameOpen(pStream, NULL );
	AVISTREAMINFO streaminfo;
	AVIStreamInfo(pStream,&streaminfo,sizeof(AVISTREAMINFO));
	
	//Get the first frame
	BITMAPINFOHEADER bih2;
	long lsize = sizeof(bih2);
	int index= 0;
	for (int i = iFirstFrame; i < iNumFrames; i++)
	{
		index= i-iFirstFrame;
		BYTE* pDIB = (BYTE*) AVIStreamGetFrame(pFrame, index); //
		AVIStreamReadFormat(pStream,index,&bih2,&lsize);
		BITMAPFILEHEADER stFileHdr;
		BYTE* Bits=new BYTE[bih2.biSizeImage];
		AVIStreamRead(pStream,index,1,Bits,bih2.biSizeImage,NULL,NULL);
		//RtlMoveMemory(Bits, pDIB + sizeof(BITMAPINFOHEADER), bih2.biSizeImage);
		bih2.biClrUsed =0;
		stFileHdr.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);
		stFileHdr.bfSize=sizeof(BITMAPFILEHEADER);
		stFileHdr.bfType=0x4d42; 
		CString FileName;
		FileName.Format(_T("Frame-%05d.bmp"), index);
		CString strtemp;
		strtemp.Format(_T("%s\\%s"), strBmpDir.c_str(), FileName);
		FILE* fp=_tfopen(strtemp ,_T("wb"));
		fwrite(&stFileHdr,1,sizeof(BITMAPFILEHEADER),fp);
		fwrite(&bih2,1,sizeof(BITMAPINFOHEADER),fp);
		int ff = fwrite(Bits,1,bih2.biSizeImage,fp);
		int e = GetLastError();
		fclose(fp);
		/////
		delete Bits;
		//CreateFromPackedDIBPointer(pDIB, index);
	}
	
	AVIStreamGetFrameClose(pFrame);
	//close the stream after finishing the task
	if (pStream!=NULL)
		AVIStreamRelease(pStream);
	AVIFileExit();
}
HRESULT CAVIFileReader::Initialize(IN char *pszFileName)
{

    HRESULT hr = S_OK;

    
    //
    // would do better argument checking in a real-life application
    //

    _ASSERTE(pszFileName);


    //
    // log file name and requested wave format
    //

    LogMessage("CAVIFileReader::Initialize started. file [%s]", 
                pszFileName);


    //
    // initialize avi file library. AVIFileExit should be called on the same 
    // thread when AVI library is no longer needed
    //
    // AVIFileExit is called in the destructor. 
    //
    // Assuption: instances of CAVIFileReader are initialized and destroyed on 
    // the same thread
    //
    
    AVIFileInit();

    
    //
    // open the first audio stream in the file
    //

    hr = AVIStreamOpenFromFile(&m_pAudioStream,
                               pszFileName,
                               streamtypeAUDIO,
                               0,
                               OF_READ | OF_SHARE_DENY_WRITE,
                               NULL);

    if (FAILED(hr))
    {
        LogError("CAVIFileReader::Initialize "
                 "Failed to open stream from the file");

        m_pAudioStream = NULL;

        return hr;
    }


    //
    // read the size of the stream's format
    //

    LONG nFormatSize = 0;

    hr = AVIStreamReadFormat(m_pAudioStream, 0, NULL, &nFormatSize);

    if ( FAILED(hr) || (0 == nFormatSize) )
    {
        LogError("CAVIFileReader::Initialize"
                 "Failed to get stream format's size");

        m_pAudioStream->Release();
        m_pAudioStream = NULL;

        return E_FAIL;
    }


    //
    // allocate memory for audio format. keep it in a waveformatex structure. 
    // if the structure returned is waveformat, still allocate waveformatex
    //

    nFormatSize = max((LONG)sizeof(WAVEFORMATEX), nFormatSize);
       
    m_pWaveFormat = (WAVEFORMATEX*)AllocateMemory(nFormatSize);

    if (NULL == m_pWaveFormat)
    {
        LogError("CAVIFileReader::Initialize "
                 "Failed to allocate memory for wave format, size %ld", 
                 nFormatSize);

        m_pAudioStream->Release();
        m_pAudioStream = NULL;

        return E_OUTOFMEMORY;

    }


    //
    // read stream format into allocated structure
    //

    hr = AVIStreamReadFormat(m_pAudioStream, 0, m_pWaveFormat, &nFormatSize);

    if (FAILED(hr))
    {
        LogError("CAVIFileReader::Initialize "
                 "Failed to read stream format");

        m_pAudioStream->Release();
        m_pAudioStream = NULL;

        FreeMemory(m_pWaveFormat);
        m_pWaveFormat = NULL;

        return hr;
    }


    //
    // log stream's format
    //

    LogMessage("CAVIFileReader::CAVIFileReader stream opened");
    LogFormat(m_pWaveFormat);


    LogMessage("CAVIFileReader::CAVIFileReader finished");

    return S_OK;
}
		AviFrameGraber::AviFrameGraber(){
			frame_=NULL;
			avi_file_=NULL;
			stream_=NULL;
			AVIFileInit();
		}
Example #7
0
CBmpToAvi::CBmpToAvi()
{
	m_pfile = NULL;
	m_pavi = NULL;
	AVIFileInit();
}
boolean VFWInit(){
	AVIFileInit();
	CoInitialize(NULL);
	std::stringstream filename;
	filename << directory<< "TheVideo.avi\0";
	pfile = new PAVIFILE();
	VFWReturnVal = AVIFileOpen(pfile, filename.str().c_str(),OF_SHARE_DENY_WRITE|OF_CREATE,0L);
	if(VFWReturnVal !=0 ){
		return false;
	}

	AVISTREAMINFO* strhdr = new AVISTREAMINFO();// ZeroMemory(&strhdr,sizeof(strhdr));
	strhdr->fccType = streamtypeVIDEO;// stream type
	strhdr->fccHandler = 0;
	strhdr->dwScale = 1;
	strhdr->dwRate = 60;//10;//100;//*/1000;

	pstream = new PAVISTREAM();
	VFWReturnVal = AVIFileCreateStream(*pfile,pstream,strhdr);
	if(VFWReturnVal !=0 ){
		return false;
	}

	poptions = new AVICOMPRESSOPTIONS();

	aopts[0] = poptions;
	AVISaveOptions(hWnd,0,1, pstream,aopts);
	
	DWORD flag=poptions->dwFlags &AVICOMPRESSF_VALID;
	if(!(poptions->dwFlags &AVICOMPRESSF_VALID)){
	
		delete poptions;
		return false;
	}

	pcompressedstream = new PAVISTREAM();
	VFWReturnVal = AVIMakeCompressedStream(pcompressedstream,*pstream,aopts[0],NULL);
	if(VFWReturnVal !=AVIERR_OK ){
		AVIStreamRelease(*pcompressedstream);
		delete(pcompressedstream);
		AVIStreamRelease(*pstream);
		delete pstream;
		AVISaveOptionsFree(1,aopts);
		AVIFileRelease(*pfile);
		return false;
	}

	bi = new BITMAPINFOHEADER();
	bi->biSize = sizeof (BITMAPINFOHEADER);
	bi->biWidth         = simWidth;
	bi->biHeight        = simHeight;
	bi->biPlanes        = 1;
	bi->biBitCount      = 32;
	bi->biCompression   = BI_RGB;
	bi->biSizeImage     = ((bi->biWidth*bi->biBitCount/8)*bi->biHeight);
	bi->biXPelsPerMeter = 14173;
	bi->biYPelsPerMeter = 14173;
	bi->biClrUsed       = 0;
	bi->biClrImportant  = 0;

	VFWReturnVal = AVIStreamSetFormat(*pcompressedstream,0,bi,bi->biSize);
	if(VFWReturnVal != 0 ){
		AVIStreamRelease(*pcompressedstream);
		delete(pcompressedstream);
		AVIStreamRelease(*pstream);
		delete pstream;
		AVISaveOptionsFree(1,aopts);
		AVIFileRelease(*pfile);

		return false;
	}
	return true;
}
Example #9
0
bool AviRecorder::Start(int cx, int cy, char *pszFn)
{
#ifndef DEV_BUILD
	// Don't let mortals record avis

	return false;
#endif

#if 1
	// Modify cx & cy to be 4 by 3 for NTSC video,
	// which is what Microsoft Movie Maker makes.

	if (cx > cy) {
		int cyT = cx * 3 / 4;
		if (cyT < cy) {
			cx = cy * 4 / 3;
		} else {
			cy = cyT;
		}
	} else {
		int cxT = cy * 4 / 3;
		if (cxT < cx) {
			cy = cx * 3 / 4;
		} else {
			cx = cxT;
		}
	}
#endif

	// Now dword align the dst, for Windows sake

	cx = (cx + 3) & ~3;

	// Create a temp buffer that we'll use for flipping the dib since it needs to
	// be upside down for windows.

	m_pbmFlip = CreateDibBitmap(NULL, cx, cy);
	if (m_pbmFlip == NULL)
		return false;

	// Init

	m_ptbmPointer = LoadTBitmap("arrow5.tbm");
	AVIFileInit();

	// Create filename

	if (pszFn == NULL) {
		char szFn[MAX_PATH];
		strcpy(szFn, "c:\\ht.avi");
		pszFn = szFn;
	}

	// Open AVI file

	HRESULT hr = AVIFileOpen(&m_pavif, pszFn, OF_CREATE | OF_WRITE, NULL);
	if (hr != AVIERR_OK)
		return false;

	// Create the video streams if they don't exist

	AVISTREAMINFO stmInfo;
	memset(&stmInfo, 0, sizeof(stmInfo));
	stmInfo.fccType = streamtypeVIDEO;
	stmInfo.fccHandler = 0; // mmioFOURCC('M','S','V','C');
	stmInfo.dwScale = 2;
	stmInfo.dwRate = 25;
	stmInfo.dwSuggestedBufferSize = cx * cy;
	stmInfo.dwQuality = 0; // 10000;
	SetRect(&stmInfo.rcFrame, 0, 0, cx, cy);

	// Create video stream

	if (m_pstmVideo == NULL) {
		hr = AVIFileCreateStream(m_pavif, &m_pstmVideo, &stmInfo);
		if (hr != AVIERR_OK)
			return false;
	}

	// Set the stream format

	struct Header {
		BITMAPINFOHEADER bih;
		RGBQUAD argbqPal[256];
	};

	Header hdr;
	memset(&hdr, 0, sizeof(hdr));
	hdr.bih.biSize = sizeof(hdr.bih);
	hdr.bih.biWidth = cx;
	hdr.bih.biHeight = cy;
	hdr.bih.biPlanes = 1;
	hdr.bih.biBitCount = 8;
	hdr.bih.biCompression = BI_RGB;
	hdr.bih.biClrUsed = 256;

	// Get the palette

	gpdisp->GetWindowsPalette(hdr.argbqPal);

	// Set the format

	hr = AVIStreamSetFormat(m_pstmVideo, 0, &hdr, sizeof(hdr));
	if (hr != AVIERR_OK)
		return false;

	// When recording started, useful for keeping video in sync

	m_tStart = HostGetTickCount();

	// Now create the audio stream

	memset(&stmInfo, 0, sizeof(stmInfo));
	stmInfo.fccType = streamtypeAUDIO;
	stmInfo.fccHandler = 0;
	stmInfo.dwScale = 1;
	stmInfo.dwRate = 8000;

	// Create audio stream

	if (m_pstmAudio == NULL) {
		hr = AVIFileCreateStream(m_pavif, &m_pstmAudio, &stmInfo);
		if (hr != AVIERR_OK)
			return false;
	}

	// Set the audio format

	WAVEFORMATEX fmt;
	fmt.wFormatTag = WAVE_FORMAT_PCM;
	fmt.nChannels = 1;
	fmt.nSamplesPerSec = 8000;
	fmt.nAvgBytesPerSec = 8000;
	fmt.nBlockAlign = 1;
	fmt.wBitsPerSample = 8;
	fmt.cbSize = 0;

	// Set the format

	hr = AVIStreamSetFormat(m_pstmAudio, 0, &fmt, sizeof(fmt));
	if (hr != AVIERR_OK)
		return false;
	
	// Now we can allow the audio thread to call

	m_fAudioReady = true;

	return true;
}
Example #10
0
static void avi_create(struct AVIFile** avi_out)
{
	*avi_out = (struct AVIFile*)malloc(sizeof(struct AVIFile));
	memset(*avi_out, 0, sizeof(struct AVIFile));
	AVIFileInit();
}
Example #11
0
AvisynthVideoProvider::AvisynthVideoProvider(wxString filename)
: last_fnum(-1)
{
	iframe.flipped = true;
	iframe.invertChannels = true;

	wxMutexLocker lock(avs.GetMutex());

	wxFileName fname(filename);
	if (!fname.FileExists())
		throw agi::FileNotFoundError(from_wx(filename));

	wxString extension = filename.Right(4).Lower();

#ifdef _WIN32
	if (extension == ".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.wc_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;
		}

		bool all_keyframes = true;
		for (size_t i = 0; i < avis.dwLength; i++) {
			if (AVIStreamIsKeyFrame(ppavi, i))
				KeyFrames.push_back(i);
			else
				all_keyframes = false;
		}

		// If every frame is a keyframe then just discard the keyframe data as it's useless
		if (all_keyframes) KeyFrames.clear();

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

	try {
		AVSValue script = Open(fname, extension);

		// 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" };
			if (!OPT_GET("Video/Force BT.601")->GetBool() && (vi.width > 1024 || vi.height >= 600)) {
				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));
	}
}
Example #12
0
bool AVIDump::CreateFile()
{
	s_total_bytes = 0;
	s_frame_count = 0;

	std::string movie_file_name = "";

	//Dragonbane: Movie Logic
	bool lastSide = false;

	movie_file_name = GetCurrDumpFile(s_file_count, false);

	if (Movie::cmp_isRunning)
	{
		if (Movie::cmp_leftFinished || Movie::cmp_rightFinished)
			lastSide = true;
	}

	if (!lastSide) //Dragonbane: Stay silent if last side is recorded
	{
		// Create path
		File::CreateFullPath(movie_file_name);

		// Ask to delete file
		if (File::Exists(movie_file_name))
		{
			if (SConfig::GetInstance().m_DumpFramesSilent ||
				AskYesNoT("Delete the existing file '%s'?", movie_file_name.c_str()))
			{
				File::Delete(movie_file_name);
			}
		}
	}

	AVIFileInit();
	NOTICE_LOG(VIDEO, "Opening AVI file (%s) for dumping", movie_file_name.c_str());

	// TODO: Make this work with AVIFileOpenW without it throwing REGDB_E_CLASSNOTREG
	HRESULT hr = AVIFileOpenA(&s_file, movie_file_name.c_str(), OF_WRITE | OF_CREATE, nullptr);

	if (FAILED(hr))
	{
		if (hr == AVIERR_BADFORMAT) NOTICE_LOG(VIDEO, "The file couldn't be read, indicating a corrupt file or an unrecognized format.");
		if (hr == AVIERR_MEMORY)  NOTICE_LOG(VIDEO, "The file could not be opened because of insufficient memory.");
		if (hr == AVIERR_FILEREAD) NOTICE_LOG(VIDEO, "A disk error occurred while reading the file.");
		if (hr == AVIERR_FILEOPEN) NOTICE_LOG(VIDEO, "A disk error occurred while opening the file.");
		if (hr == REGDB_E_CLASSNOTREG) NOTICE_LOG(VIDEO, "AVI class not registered");
		Stop();
		return false;
	}

	SetBitmapFormat();
	NOTICE_LOG(VIDEO, "Setting video format...");
	if (!SetVideoFormat())
	{
		NOTICE_LOG(VIDEO, "Setting video format failed");
		Stop();
		return false;
	}

	if (!s_file_count && !lastSide) //Dragonbane: Stay silent and re-use settings if last side is recorded
	{
		if (!SetCompressionOptions())
		{
			NOTICE_LOG(VIDEO, "SetCompressionOptions failed");
			Stop();
			return false;
		}
	}

	if (FAILED(AVIMakeCompressedStream(&s_stream_compressed, s_stream, &s_options, nullptr)))
	{
		NOTICE_LOG(VIDEO, "AVIMakeCompressedStream failed");
		Stop();
		return false;
	}

	if (FAILED(AVIStreamSetFormat(s_stream_compressed, 0, &s_bitmap, s_bitmap.biSize)))
	{
		NOTICE_LOG(VIDEO, "AVIStreamSetFormat failed");
		Stop();
		return false;
	}

	return true;
}
Example #13
0
int aviOpen(HWND hwndOwner, char* filename, int fps)
{
    AVICOMPRESSOPTIONS options;
    AVICOMPRESSOPTIONS* optionsPtr;
    AVISTREAMINFO steamHdr;
    AVISTREAMINFO soundHdr;
    WAVEFORMATEX wfex;
    BITMAPINFOHEADER bi;

    AVIFileInit();

    frameCount = 0;
    sampleCount = 0;
    aviStatusOk  = 0;

    if (AVIFileOpen(&aviFile, filename, OF_WRITE | OF_CREATE, NULL) != 0) {
        return 0;
    }

	memset(&bi, 0, sizeof(bi));      
	bi.biSize       = 0x28;    
	bi.biPlanes     = 1;
	bi.biBitCount   = 32;
	bi.biWidth      = 320 * zoom;
	bi.biHeight     = 240 * zoom;
	bi.biSizeImage  = bi.biWidth * bi.biHeight * bi.biBitCount / 8;

    memset(&steamHdr, 0, sizeof(steamHdr));
    steamHdr.fccType = streamtypeVIDEO;
    steamHdr.dwScale = 1;
    steamHdr.dwRate  = fps;
    steamHdr.dwSuggestedBufferSize = bi.biSizeImage;

    if (AVIFileCreateStream(aviFile, &aviStream, &steamHdr) != 0) {
        return 0;
    }
      
    memset(&options, 0, sizeof(options));
    optionsPtr = &options;
    if (!AVISaveOptions(hwndOwner, 0, 1, &aviStream, &optionsPtr)) {
        return 0;
    }
  
    if (AVIMakeCompressedStream(&aviVidStream, aviStream, &options, NULL) != 0) {
        return 0;
    }
  
    // setup the video stream format
    if (AVIStreamSetFormat(aviVidStream, 0, &bi, bi.biSize + bi.biClrUsed * sizeof(RGBQUAD)) != 0) {
        return 0;
    }

    memset(&wfex, 0, sizeof(wfex));
    wfex.wFormatTag      = WAVE_FORMAT_PCM;
    wfex.nChannels       = 2;
    wfex.nSamplesPerSec  = 44100;
    wfex.wBitsPerSample  = 8 * sizeof(Int16);
    wfex.nBlockAlign     = wfex.nChannels * wfex.wBitsPerSample / 8;
    wfex.nAvgBytesPerSec = wfex.nSamplesPerSec * wfex.nBlockAlign;
    
    memset(&soundHdr, 0, sizeof(soundHdr));
    soundHdr.fccType         = streamtypeAUDIO;
    soundHdr.dwQuality       = (DWORD)-1;
    soundHdr.dwScale         = wfex.nBlockAlign;
    soundHdr.dwInitialFrames = 0;
    soundHdr.dwRate          = wfex.nAvgBytesPerSec;
    soundHdr.dwSampleSize    = wfex.nBlockAlign;

    if (AVIFileCreateStream(aviFile, &aviSndStream, &soundHdr) != 0) {
        return 0;
    }

    if (AVIStreamSetFormat(aviSndStream, 0, (void *)&wfex, sizeof(wfex)) != 0) {
        return 0;
    }

    aviStatusOk = 1;

    return 1;
}
bool Movie::reload(const io::stringc &Filename, const s32 Resolution)
{
    if (DataPointer_)
        close();
    
    /* Information message */
    io::Log::message("Load movie: \"" + Filename + "\"");
    io::Log::upperTab();
    
    /* General settings */
    SMovieSequencePacket* MovieData = new SMovieSequencePacket;
    
    DataPointer_                = MovieData;
    
    MovieData->Next             = MovieData->Frame      = 0;
    MovieData->State            = MOVIESTATE_STOPED;
    MovieData->Time             = MovieData->LastTime   = 0;
    MovieData->RawData          = 0;
    MovieData->Resolution       = Resolution;
    
    MovieData->hDeviceContext   = CreateCompatibleDC(0);
    MovieData->hDrawDIB         = DrawDibOpen();
    
    AVIFileInit();
    
    /* Open video stream */
    if (AVIStreamOpenFromFile(&MovieData->pVideoStream, Filename.c_str(), streamtypeVIDEO, 0, OF_READ, 0) != 0)
        return exitWithError("Could not open video stream");
    if (AVIStreamInfo(MovieData->pVideoStream, &MovieData->VideoStreamInfo, sizeof(MovieData->VideoStreamInfo)) != 0)
        return exitWithError("Video stream information process failed");
    
    MovieData->VideoLastFrame = AVIStreamLength(MovieData->pVideoStream);
    
    if (MovieData->VideoLastFrame == -1)
        return exitWithError("Video stream length is invalid");
    
    MovieData->VideoMPF = AVIStreamSampleToTime(MovieData->pVideoStream, MovieData->VideoLastFrame) / MovieData->VideoLastFrame;
    
    if (MovieData->VideoMPF == -1)
        return exitWithError("Video stream sample is invalid");
    
    #if 0
    
    /* Open audio stream */
    if (AVIStreamOpenFromFile(&MovieData->pAudioStream, Filename.c_str(), streamtypeAUDIO, 0, OF_READ, 0))
        return exitWithError("Could not open audio stream");
    if (AVIStreamInfo(MovieData->pAudioStream, &MovieData->AudioStreamInfo, sizeof(MovieData->AudioStreamInfo)))
        return exitWithError("Audio stream information process failed");
    
    MovieData->AudioLastFrame = AVIStreamLength(MovieData->pAudioStream);
    
    if (MovieData->AudioLastFrame == -1)
        return exitWithError("Audio stream length is invalid");
    
    MovieData->AudioMPF = AVIStreamSampleToTime(MovieData->pAudioStream, MovieData->AudioLastFrame) / MovieData->AudioLastFrame;
    
    if (MovieData->AudioMPF == -1)
        return exitWithError("Audio stream sample is invalid");
    
    #endif
    
    /* Start configuration process */
    MovieData->Size.Width   = MovieData->VideoStreamInfo.rcFrame.right  - MovieData->VideoStreamInfo.rcFrame.left;
    MovieData->Size.Height  = MovieData->VideoStreamInfo.rcFrame.bottom - MovieData->VideoStreamInfo.rcFrame.top;
    
    MovieData->BitmapInfoHeader.biSize          = sizeof(BITMAPINFOHEADER);
    MovieData->BitmapInfoHeader.biPlanes        = 1;
    MovieData->BitmapInfoHeader.biBitCount      = 24;
    MovieData->BitmapInfoHeader.biWidth         = MovieData->Resolution;
    MovieData->BitmapInfoHeader.biHeight        = MovieData->Resolution;
    MovieData->BitmapInfoHeader.biCompression   = BI_RGB;
    
    /* Create the movie bitmap context */
    MovieData->hBitmap = CreateDIBSection(
        MovieData->hDeviceContext,
        (BITMAPINFO*)(&MovieData->BitmapInfoHeader),
        DIB_RGB_COLORS,
        (void**)(&MovieData->RawData),
        0, 0
    );

    if (!MovieData->hBitmap)
        return exitWithError("Could not create device independent bitmap (DIB) for video stream");
    
    SelectObject(MovieData->hDeviceContext, MovieData->hBitmap);
    
    MovieData->BitmapInfoHeader.biWidth         = MovieData->Size.Width;
    MovieData->BitmapInfoHeader.biHeight        = MovieData->Size.Height;
    MovieData->BitmapInfoHeader.biSizeImage     = 0;
    MovieData->BitmapInfoHeader.biClrUsed       = 0;
    MovieData->BitmapInfoHeader.biClrImportant  = 0;
    
    /* Get first video frame */
    MovieData->pGetFrame = AVIStreamGetFrameOpen(MovieData->pVideoStream, &MovieData->BitmapInfoHeader);
    
    if (!MovieData->pGetFrame)
        return exitWithError("Could not open first video stream");
    
    io::Log::lowerTab();
    
    return true;
}
Example #15
0
HRESULT CAviFile::InitMovieCreation(int nFrameWidth, int nFrameHeight, int nBitsPerPixel)
{
	AVIFileInit();

	int	nMaxWidth=GetSystemMetrics(SM_CXSCREEN),nMaxHeight=GetSystemMetrics(SM_CYSCREEN);

	m_hAviDC = CreateCompatibleDC(NULL);
	if(m_hAviDC==NULL)	
	{
		SetErrorMessage(_T("Unable to Create Compatible DC"));
		return E_FAIL;
	}
	
	if(nFrameWidth > nMaxWidth)	nMaxWidth= nFrameWidth;
	if(nFrameHeight > nMaxHeight)	nMaxHeight = nFrameHeight;

	m_hHeap=HeapCreate(HEAP_NO_SERIALIZE, nMaxWidth*nMaxHeight*4, 0);
	if(m_hHeap==NULL)
	{
		SetErrorMessage(_T("Unable to Create Heap"));
		return E_FAIL;
	}
	
	m_lpBits=HeapAlloc(m_hHeap, HEAP_ZERO_MEMORY|HEAP_NO_SERIALIZE, nMaxWidth*nMaxHeight*4);
	if(m_lpBits==NULL)	
	{	
		SetErrorMessage(_T("Unable to Allocate Memory on Heap"));
		return E_FAIL;
	}
	HRESULT result = AVIFileOpen(&m_pAviFile, m_szFileName, OF_CREATE|OF_WRITE, NULL);
	if(FAILED(result))
	{
		SetErrorMessage(_T("Unable to Create the Movie File"));
		switch(result) {
		case AVIERR_BADFORMAT: SetErrorMessage(_T("Bad file format"));break;
		case REGDB_E_CLASSNOTREG: SetErrorMessage(_T("Avi file type not registered"));break;
		case AVIERR_MEMORY: SetErrorMessage(_T("Insufficient memory"));break;
		case AVIERR_FILEOPEN: SetErrorMessage(_T("File already opened"));break;
		case AVIERR_FILEREAD: SetErrorMessage(_T("File read problem"));break;
		default: SetErrorMessage(_T("Unable to Create the Movie File"));
		}
		return E_FAIL;
	}

	ZeroMemory(&m_AviStreamInfo,sizeof(AVISTREAMINFO));
	m_AviStreamInfo.fccType		= streamtypeVIDEO;
	m_AviStreamInfo.fccHandler	= m_dwFCCHandler;
	m_AviStreamInfo.dwScale		= 1;
	m_AviStreamInfo.dwRate		= m_dwFrameRate;	// Frames Per Second;
	m_AviStreamInfo.dwQuality	= -1;				// Default Quality
	m_AviStreamInfo.dwSuggestedBufferSize = nMaxWidth*nMaxHeight*4;
    SetRect(&m_AviStreamInfo.rcFrame, 0, 0, nFrameWidth, nFrameHeight);
	_tcscpy_s(m_AviStreamInfo.szName, _T("Video Stream"));

	if(FAILED(AVIFileCreateStream(m_pAviFile,&m_pAviStream,&m_AviStreamInfo)))
	{
		SetErrorMessage(_T("Unable to Create Video Stream in the Movie File"));
		return E_FAIL;
	}

	ZeroMemory(&m_AviCompressOptions,sizeof(AVICOMPRESSOPTIONS));
	m_AviCompressOptions.fccType=streamtypeVIDEO;
	m_AviCompressOptions.fccHandler=m_AviStreamInfo.fccHandler;
	m_AviCompressOptions.dwFlags=AVICOMPRESSF_KEYFRAMES|AVICOMPRESSF_VALID;//|AVICOMPRESSF_DATARATE;
	m_AviCompressOptions.dwKeyFrameEvery=1;
	//m_AviCompressOptions.dwBytesPerSecond=1000/8;
	//m_AviCompressOptions.dwQuality=100;

	if(FAILED(AVIMakeCompressedStream(&m_pAviCompressedStream,m_pAviStream,&m_AviCompressOptions,NULL)))
	{
		// One reason this error might occur is if you are using a Codec that is not 
		// available on your system. Check the mmioFOURCC() code you are using and make
		// sure you have that codec installed properly on your machine.
		SetErrorMessage(_T("Unable to Create Compressed Stream: Check your CODEC options"));
		return E_FAIL;
	}

	BITMAPINFO bmpInfo;
	ZeroMemory(&bmpInfo,sizeof(BITMAPINFO));
	bmpInfo.bmiHeader.biPlanes		= 1;
	bmpInfo.bmiHeader.biWidth		= nFrameWidth;
	bmpInfo.bmiHeader.biHeight		= nFrameHeight;
	bmpInfo.bmiHeader.biCompression	= BI_RGB;
	bmpInfo.bmiHeader.biBitCount	= nBitsPerPixel;
	bmpInfo.bmiHeader.biSize		= sizeof(BITMAPINFOHEADER);
	bmpInfo.bmiHeader.biSizeImage	= bmpInfo.bmiHeader.biWidth*bmpInfo.bmiHeader.biHeight*bmpInfo.bmiHeader.biBitCount/8;

	if(FAILED(AVIStreamSetFormat(m_pAviCompressedStream,0,(LPVOID)&bmpInfo, bmpInfo.bmiHeader.biSize)))
	{
		// One reason this error might occur is if your bitmap does not meet the Codec requirements.
		// For example, 
		//   your bitmap is 32bpp while the Codec supports only 16 or 24 bpp; Or
		//   your bitmap is 274 * 258 size, while the Codec supports only sizes that are powers of 2; etc...
		// Possible solution to avoid this is: make your bitmap suit the codec requirements,
		// or Choose a codec that is suitable for your bitmap.
		SetErrorMessage(_T("Unable to Set Video Stream Format"));
		return E_FAIL;
	}

	return S_OK;	// Everything went Fine
}
Example #16
0
BOOL LoadAviDLL()
{
	if (hPPAviDll)
		goto ExitError;
    hPPAviDll = (HINSTANCE)AstralLoadLibrary( "avifile.dll" );
	if (!hPPAviDll)
		goto ExitError;
//	dll_InitVFW = (LONG (FAR * )(void))
//		GetProcAddress(hPPAviDll, "InitVFW");
//	if (!dll_InitVFW) goto ExitError;
//	dll_TermVFW = (LONG (FAR * )(void))
//		GetProcAddress(hPPAviDll,"TermVFW");
//	if (!dll_TermVFW) goto ExitError;
dll_AVIFileInit = (void (STDAPICALLTYPE FAR * )(void))
	GetProcAddress(hPPAviDll, "AVIFileInit");
	if (!dll_AVIFileInit) goto ExitError;
dll_AVIFileExit = (void (STDAPICALLTYPE FAR * )(void))
	GetProcAddress(hPPAviDll, "AVIFileExit");
	if (!dll_AVIFileExit) goto ExitError;
dll_AVIFileOpen = (HRESULT (STDAPICALLTYPE FAR * )(PAVIFILE FAR * ppfile, LPCSTR szFile, UINT uMode, LPCLSID lpHandler))
	GetProcAddress(hPPAviDll, "AVIFileOpen");
	if (!dll_AVIFileOpen) goto ExitError;
dll_AVIFileRelease = (ULONG (STDAPICALLTYPE FAR * )(PAVIFILE pfile))
	GetProcAddress(hPPAviDll, "AVIFileRelease");
	if (!dll_AVIFileRelease) goto ExitError;
dll_AVIFileGetStream = (HRESULT (STDAPICALLTYPE FAR * )(PAVIFILE pfile, PAVISTREAM FAR * ppavi, DWORD fccType, LONG lParam))
	GetProcAddress(hPPAviDll, "AVIFileGetStream");
	if (!dll_AVIFileGetStream) goto ExitError;
dll_AVIFileInfo  = (HRESULT (STDAPICALLTYPE FAR * )(PAVIFILE pfile, AVIFILEINFO FAR * pfi, LONG lSize))
	GetProcAddress(hPPAviDll, "AVIFileInfo");
	if (!dll_AVIFileInfo) goto ExitError;
dll_AVIFileCreateStream   = (HRESULT (STDAPICALLTYPE FAR * )(PAVIFILE pfile, PAVISTREAM FAR *ppavi, AVISTREAMINFO FAR *psi))
	GetProcAddress(hPPAviDll, "AVIFileCreateStream");
	if (!dll_AVIFileCreateStream) goto ExitError;
dll_AVIStreamRelease = (ULONG (STDAPICALLTYPE FAR * )(PAVISTREAM pavi))
	GetProcAddress(hPPAviDll, "AVIStreamRelease");
	if (!dll_AVIStreamRelease) goto ExitError;
dll_AVIStreamGetFrameOpen = (PGETFRAME (STDAPICALLTYPE FAR * )(PAVISTREAM pavi, LPBITMAPINFOHEADER lpbiWanted))
	GetProcAddress(hPPAviDll, "AVIStreamGetFrameOpen");
	if (!dll_AVIStreamGetFrameOpen) goto ExitError;
dll_AVIStreamGetFrame = (LPVOID (STDAPICALLTYPE FAR * )(PGETFRAME pg, LONG lPos))
	GetProcAddress(hPPAviDll, "AVIStreamGetFrame");
	if (!dll_AVIStreamGetFrame) goto ExitError;
dll_AVIStreamGetFrameClose = (HRESULT (STDAPICALLTYPE FAR * )(PGETFRAME pg))
	GetProcAddress(hPPAviDll, "AVIStreamGetFrameClose");
	if (!dll_AVIStreamGetFrameClose) goto ExitError;
dll_AVIStreamInfo  = (HRESULT (STDAPICALLTYPE FAR * )(PAVISTREAM pavi, AVISTREAMINFO FAR * psi, LONG lSize))
	GetProcAddress(hPPAviDll, "AVIStreamInfo");
	if (!dll_AVIStreamInfo) goto ExitError;
dll_AVIStreamStart  = (LONG (STDAPICALLTYPE FAR * )(PAVISTREAM pavi))
	GetProcAddress(hPPAviDll, "AVIStreamStart");
	if (!dll_AVIStreamStart) goto ExitError;
dll_AVIStreamSetFormat  = (HRESULT (STDAPICALLTYPE FAR * )(PAVISTREAM pavi, LONG lPos,LPVOID lpFormat,LONG cbFormat))
	GetProcAddress(hPPAviDll, "AVIStreamSetFormat");
	if (!dll_AVIStreamSetFormat) goto ExitError;
dll_AVIStreamWrite  = (HRESULT (STDAPICALLTYPE FAR * )(PAVISTREAM pavi, LONG lStart, LONG lSamples, LPVOID lpBuffer, LONG cbBuffer, DWORD dwFlags, LONG FAR *plSampWritten, LONG FAR *plBytesWritten))
	GetProcAddress(hPPAviDll, "AVIStreamWrite");
	if (!dll_AVIStreamWrite) goto ExitError;
dll_AVIStreamLength  = (LONG (STDAPICALLTYPE FAR * )(PAVISTREAM pavi))
	GetProcAddress(hPPAviDll,  "AVIStreamLength");
	if (!dll_AVIStreamLength) goto ExitError;

	if (!InitVFW())
		goto ExitError;
	AVIFileInit();
		
	return(TRUE);			

ExitError:

	if (hPPAviDll)
		FreeLibrary( hPPAviDll );
	hPPAviDll = NULL;
	Message(IDS_ENOAVI);
	return(FALSE);
}
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 = 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;

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

  return 0;
}
Example #18
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;
}
Example #19
0
bool AVIDump::CreateFile()
{
	m_totalBytes = 0;
	m_frameCount = 0;
	char movie_file_name[255];
	sprintf(movie_file_name, "%sframedump%d.avi", File::GetUserPath(D_DUMPFRAMES_IDX).c_str(), m_fileCount);
	// Create path
	File::CreateFullPath(movie_file_name);

	// Ask to delete file
	if (File::Exists(movie_file_name))
	{
		if (AskYesNoT("Delete the existing file '%s'?", movie_file_name))
			File::Delete(movie_file_name);
	}

	AVIFileInit();
	NOTICE_LOG(VIDEO, "Opening AVI file (%s) for dumping", movie_file_name);
	// TODO: Make this work with AVIFileOpenW without it throwing REGDB_E_CLASSNOTREG
	HRESULT hr = AVIFileOpenA(&m_file, movie_file_name, OF_WRITE | OF_CREATE, NULL);
	if (FAILED(hr))
	{
		if (hr == AVIERR_BADFORMAT) NOTICE_LOG(VIDEO, "The file couldn't be read, indicating a corrupt file or an unrecognized format."); 
		if (hr == AVIERR_MEMORY)  NOTICE_LOG(VIDEO, "The file could not be opened because of insufficient memory."); 
		if (hr == AVIERR_FILEREAD) NOTICE_LOG(VIDEO, "A disk error occurred while reading the file."); 
		if (hr == AVIERR_FILEOPEN) NOTICE_LOG(VIDEO, "A disk error occurred while opening the file.");
		if (hr == REGDB_E_CLASSNOTREG) NOTICE_LOG(VIDEO, "AVI class not registered");
		Stop();
		return false;
	}

	SetBitmapFormat();
	NOTICE_LOG(VIDEO, "Setting video format...");
	if (!SetVideoFormat())
	{
		NOTICE_LOG(VIDEO, "Setting video format failed");
		Stop();
		return false;
	}

	if (!m_fileCount)
	{
		if (!SetCompressionOptions())
		{
			NOTICE_LOG(VIDEO, "SetCompressionOptions failed");
			Stop();
			return false;
		}
	}

	if (FAILED(AVIMakeCompressedStream(&m_streamCompressed, m_stream, &m_options, NULL)))
	{
		NOTICE_LOG(VIDEO, "AVIMakeCompressedStream failed");
		Stop();
		return false;
	}

	if (FAILED(AVIStreamSetFormat(m_streamCompressed, 0, &m_bitmap, m_bitmap.biSize)))
	{
		NOTICE_LOG(VIDEO, "AVIStreamSetFormat failed");
		Stop();
		return false;
	}

	return true;
}
Example #20
0
bool VideoComponent::openAvi(const std::string& filename)
{
	// Stop any currently loaded avi
	closeAvi();

	AVIFileInit();							// Opens The AVIFile Library
	// Opens The AVI Stream
	if (AVIStreamOpenFromFile(&m_pavi, filename.c_str(), streamtypeVIDEO, 0, OF_READ, NULL) !=0)
	{
		GameLog::errorMessage("Error opening avi: %s", filename.c_str());
		// An Error Occurred Opening The Stream
		AVIFileExit();								// Release The File
		return false;
	}
	AVIStreamInfo(m_pavi, &m_psi, sizeof(m_psi));						// Reads Information About The Stream Into psi
	m_width = m_psi.rcFrame.right-m_psi.rcFrame.left;					// Width Is Right Side Of Frame Minus Left
	m_height = m_psi.rcFrame.bottom-m_psi.rcFrame.top;					// Height Is Bottom Of Frame Minus Top
	if (!m_resize)
	{
		// Size should be kept
		m_resizeWidth = m_width;
		m_resizeHeight = m_height;
	}
	m_lastframe = AVIStreamLength(m_pavi);								// The Last Frame Of The Stream
	m_timePerFrame = ((float)AVIStreamSampleToTime(m_pavi, m_lastframe) / (float) m_lastframe) / 1000.0f;	// Calculate Rough Seconds Per Frame
	m_bmih.biSize		= sizeof (BITMAPINFOHEADER);					// Size Of The BitmapInfoHeader
	m_bmih.biPlanes		= 1;					// Bitplanes
	m_bmih.biBitCount	= 24;					// Bits Format We Want 24 / 8  = 3 bytes
	m_bmih.biWidth		= m_resizeWidth;		// Width We Want
	m_bmih.biHeight		= m_resizeHeight;		// Height We Want
	m_bmih.biCompression= BI_RGB;				// Requested Mode = RGB
	m_hBitmap = CreateDIBSection (m_hdc, (BITMAPINFO*)(&m_bmih), DIB_RGB_COLORS, (void**)(&m_data), NULL, NULL);	
	SelectObject (m_hdc, m_hBitmap);					// Select hBitmap Into Our Device Context (hdc)
	// Bitmapinfo header for decoding (needed for xvid)
	m_bmiavih.biSize = sizeof(BITMAPINFOHEADER);
	m_bmiavih.biPlanes			= 1;					// Bitplanes
	m_bmiavih.biBitCount		= 24;					// Bits Format We Want 24 / 8  = 3 bytes
	m_bmiavih.biWidth			= m_width;				// Width We Want
	m_bmiavih.biHeight			= m_height;				// Height We Want
	m_bmiavih.biCompression		= BI_RGB;				// Requested Mode = RGB
	// And some more infos
	m_bmiavih.biClrImportant	= 0;
	m_bmiavih.biClrUsed			= 0;
	m_bmiavih.biXPelsPerMeter	= 0;
	m_bmiavih.biYPelsPerMeter	= 0;
	m_bmiavih.biSizeImage = (((m_bmiavih.biWidth * 3) + 3) & 0xFFFC) * m_bmiavih.biHeight;
	m_pgf=AVIStreamGetFrameOpen(m_pavi, &m_bmiavih);// Create The PGETFRAME Using Our Request Mode
	if (m_pgf==0x0)
	{
		GameLog::errorMessage("Error opening first frame of avi: %s", filename.c_str());
		// An Error Occurred Opening The Frame
		DeleteObject(m_hBitmap);					// Delete The Device Dependant Bitmap Object
		AVIStreamRelease(m_pavi);					// Release The Stream
		AVIFileExit();								// Release The File
		return false;
	}
	m_fileName = filename;

	// Create buffer for converted data
	// width*height = count pixel; each pixel has 4 channels for rgba with each one byte
	int dataSize = 4*m_resizeWidth*m_resizeHeight;
	m_bgraData = new unsigned char[dataSize];
	// Initialize with 255 (black screen with full alpha)
	memset(m_bgraData, 255, dataSize);

	// Prepare horde texture stream named like the video file name, to get a unique name
	m_videoTexture = h3dCreateTexture(filename.c_str(), m_resizeWidth, m_resizeHeight, H3DFormats::TEX_BGRA8, H3DResFlags::NoTexMipmaps);
	if (m_videoTexture == 0)
	{
		GameLog::errorMessage("Error creating texture for playing avi: %s", filename.c_str());
		// Failure creating the dynamic texture
		closeAvi();
		return false;
	}

	// Find the sampler index within the material
	m_samplerIndex = h3dFindResElem(m_material, H3DMatRes::SamplerElem, H3DMatRes::SampNameStr, "albedoMap");	
	if (m_samplerIndex == -1)
	{
		GameLog::errorMessage("Error preparing material with resID %d for playing avi: %s", m_material, filename.c_str());
		// No sampler found in material
		closeAvi();
		return false;
	}

	// Store old sampler
	m_originalSampler = h3dGetResParamI(m_material, H3DMatRes::SamplerElem, m_samplerIndex, H3DMatRes::SampTexResI);

	
	// Now open the audio stream
	PAVISTREAM audioStream;
	if (AVIStreamOpenFromFile(&audioStream, filename.c_str(), streamtypeAUDIO, 0, OF_READ, NULL) == 0)
	{
		// Audio stream found
		// Get format info
		PCMWAVEFORMAT audioFormat;
		long formatSize = sizeof(audioFormat);
		int start = AVIStreamStart(audioStream);
		// TODO get channelsmask and use it
		AVIStreamReadFormat(audioStream, start, &audioFormat, &formatSize);
		long numSamples = AVIStreamLength(audioStream);
		int bitsPerSample = (audioFormat.wf.nAvgBytesPerSec * 8) / (audioFormat.wf.nSamplesPerSec * audioFormat.wf.nChannels);
		/*if (audioFormat.wf.wFormatTag == WAVE_FORMAT_MPEGLAYER3)
		{
			// TODO
			MPEGLAYER3WAVEFORMAT mp3Format;
			formatSize = sizeof(mp3Format);
			AVIStreamReadFormat(audioStream, start, &mp3Format, &formatSize);
		}*/

		// Create buffer with appropriate size
		long bufferSize = (bitsPerSample * numSamples) / 8;
		char* buffer = new char[bufferSize];
		// Read the audio data
		long bytesWritten = 0;
		AVIStreamRead(audioStream, start, numSamples, buffer, bufferSize, &bytesWritten, 0x0);

		if (bytesWritten > 0)
		{
			// Send the audio data to the sound component
			SoundResourceData eventData(buffer, bytesWritten, audioFormat.wf.nSamplesPerSec, bitsPerSample, audioFormat.wf.nChannels);
			GameEvent event(GameEvent::E_SET_SOUND_WITH_USER_DATA, &eventData, this);
			m_owner->executeEvent(&event);
			m_hasAudio = true;
		}

		// Delete the buffer data
		delete[] buffer;
	}

	if (m_autoStart)
		// Play video directly
		playAvi();

	return true;
}
Example #21
0
void CAviHelper::BMPtoAVI(const wstring& szAVIName, const wstring& strBDir)
{
	CFileFind finder;
	CString strBmpDir;
	strBmpDir.Format(_T("%s\\*.*"), strBDir.c_str()); 
	AVIFileInit(); 
	AVISTREAMINFO strhdr;
	PAVIFILE pfile;
	PAVISTREAM ps; 
	int nFrames =0; 
	HRESULT hr; 
	BOOL bFind = finder.FindFile(strBmpDir);
	while(bFind)
	{
		bFind = finder.FindNextFile();
		if(!finder.IsDots() && !finder.IsDirectory())
		{
			CString str = finder.GetFilePath();
			FILE *fp = _tfopen(str, _T("rb"));
			
			BITMAPFILEHEADER bmpFileHdr;
			BITMAPINFOHEADER bmpInfoHdr;
			fseek( fp,0,SEEK_SET);
			fread(&bmpFileHdr,sizeof(BITMAPFILEHEADER),1, fp);
			fread(&bmpInfoHdr,sizeof(BITMAPINFOHEADER),1, fp);
			BYTE *tmp_buf = NULL;
			if(nFrames ==0 )
			{
			
				AVIFileOpen(&pfile, WS2S(szAVIName).c_str(), OF_WRITE | OF_CREATE,NULL);
				memset(&strhdr, 0, sizeof(strhdr));
				strhdr.fccType = streamtypeVIDEO;// stream type
				strhdr.fccHandler = 0;
				strhdr.dwScale = 1;
				strhdr.dwRate = 15; // 15 fps
				strhdr.dwSuggestedBufferSize = bmpInfoHdr.biSizeImage ;
				SetRect(&strhdr.rcFrame, 0, 0, bmpInfoHdr.biWidth, bmpInfoHdr.biHeight);
				
				// And create the stream;
				hr = AVIFileCreateStream(pfile,&ps,&strhdr); 
				// hr = AVIStreamSetFormat(ps,nFrames,&bmpInfoHdr,sizeof(bmpInfoHdr));
			}
			
			tmp_buf = new BYTE[bmpInfoHdr.biWidth * bmpInfoHdr.biHeight * 3];
			fread(tmp_buf, 1, bmpInfoHdr.biWidth * bmpInfoHdr.biHeight * 3, fp);
			hr = AVIStreamSetFormat(ps,nFrames,&bmpInfoHdr,sizeof(bmpInfoHdr));
			hr = AVIStreamWrite(ps, // stream pointer
				nFrames , // time of this frame
				1, // number to write
				(LPBYTE) tmp_buf,
				bmpInfoHdr.biSizeImage , // size of this frame
				AVIIF_KEYFRAME, // flags....
				NULL,
				NULL);
			nFrames ++; 
			fclose(fp);
		}
	}
	
	AVIStreamClose(ps);
	if(pfile != NULL)
		AVIFileRelease(pfile);
	AVIFileExit();
}
bool mitk::MovieGeneratorWin32::InitGenerator()
{
  InitBitmapHeader();

  AVISTREAMINFO strHdr; // information for a single stream
  AVICOMPRESSOPTIONS opts;
  AVICOMPRESSOPTIONS FAR *aopts[1] = {&opts};

  TCHAR szBuffer[1024];
  HRESULT hr;

  m_sError = _T("Ok");

  // Step 0 : Let's make sure we are running on 1.1
  DWORD wVer = HIWORD(VideoForWindowsVersion());
  if (wVer < 0x010a)
  {
    // oops, we are too old, blow out of here
    m_sError = _T("Version of Video for Windows too old. Come on, join the 21th century!");
    return false;
  }

  // Step 1 : initialize AVI engine
  AVIFileInit();

  // Step 2 : Open the movie file for writing....
  hr = AVIFileOpen(&m_pAVIFile,          // Address to contain the new file interface pointer
                   (LPCTSTR)m_sFile,     // Null-terminated string containing the name of the file to open
                   OF_WRITE | OF_CREATE, // Access mode to use when opening the file.
                   NULL);                // use handler determined from file extension.
  // Name your file .avi -> very important

  if (hr != AVIERR_OK)
  {
    _tprintf(szBuffer, _T("AVI Engine failed to initialize. Check filename %s."), m_sFile);
    m_sError = szBuffer;
    // Check it succeded.
    switch (hr)
    {
      case AVIERR_BADFORMAT:
        m_sError += _T("The file couldn't be read, indicating a corrupt file or an unrecognized format.");
        break;
      case AVIERR_MEMORY:
        m_sError += _T("The file could not be opened because of insufficient memory.");
        break;
      case AVIERR_FILEREAD:
        m_sError += _T("A disk error occurred while reading the file.");
        break;
      case AVIERR_FILEOPEN:
        m_sError += _T("A disk error occurred while opening the file.");
        break;
      case REGDB_E_CLASSNOTREG:
        m_sError += _T("According to the registry, the type of file specified in AVIFileOpen does not have a handler ")
                    _T("to process it");
        break;
    }

    return false;
  }

  // Fill in the header for the video stream....
  memset(&strHdr, 0, sizeof(strHdr));
  strHdr.fccType = streamtypeVIDEO; // video stream type
  strHdr.fccHandler = 0;
  strHdr.dwScale = 1;                               // should be one for video
  strHdr.dwRate = static_cast<DWORD>(m_FrameRate);  // fps
  strHdr.dwSuggestedBufferSize = m_bih.biSizeImage; // Recommended buffer size, in bytes, for the stream.
  SetRect(&strHdr.rcFrame,
          0,
          0, // rectangle for stream
          (int)m_bih.biWidth,
          (int)m_bih.biHeight);

  // Step 3 : Create the stream;
  hr = AVIFileCreateStream(m_pAVIFile, // file pointer
                           &m_pStream, // returned stream pointer
                           &strHdr);   // stream header

  // Check it succeded.
  if (hr != AVIERR_OK)
  {
    m_sError = _T("AVI Stream creation failed. Check Bitmap info.");
    if (hr == AVIERR_READONLY)
    {
      m_sError += _T(" Read only file.");
    }
    return false;
  }

  // Step 4: Get codec and infos about codec
  memset(&opts, 0, sizeof(opts));

  // predefine MS-CRAM as standard codec
  opts.fccType = streamtypeVIDEO;
  // creates a video with minor quality! Use different codec (must be installed on local machine) to generate movies
  // with higher quality
  opts.fccHandler = mmioFOURCC('M', 'S', 'V', 'C');
  opts.dwQuality = 90000; // means 90% quality; dwQuality goes from [0...10000]

// Poping codec dialog
// GUI Codec selection does not work in a vs 2005 compiled mitk, since we do not pass a hwnd as first parameter
// of AVISaveOptions
#if !(_MSC_VER >= 1400)

  if (!AVISaveOptions(NULL, 0, 1, &m_pStream, (LPAVICOMPRESSOPTIONS FAR *)&aopts))
  {
    AVISaveOptionsFree(1, (LPAVICOMPRESSOPTIONS FAR *)&aopts);
    // return false;
  }

#endif

  // Step 5:  Create a compressed stream using codec options.
  hr = AVIMakeCompressedStream(&m_pStreamCompressed, m_pStream, &opts, NULL);

  if (hr != AVIERR_OK)
  {
    m_sError = _T("AVI Compressed Stream creation failed.");

    switch (hr)
    {
      case AVIERR_NOCOMPRESSOR:
        m_sError += _T(" A suitable compressor cannot be found.");
        break;
      case AVIERR_MEMORY:
        m_sError += _T(" There is not enough memory to complete the operation.");
        break;
      case AVIERR_UNSUPPORTED:
        m_sError += _T("Compression is not supported for this type of data. This error might be returned if you try ")
                    _T("to compress data that is not audio or video.");
        break;
    }

    return false;
  }

  // releasing memory allocated by AVISaveOptionFree
  hr = AVISaveOptionsFree(1, (LPAVICOMPRESSOPTIONS FAR *)&aopts);
  if (hr != AVIERR_OK)
  {
    m_sError = _T("Error releasing memory");
    return false;
  }

  // Step 6 : sets the format of a stream at the specified position
  hr = AVIStreamSetFormat(m_pStreamCompressed,
                          0,             // position
                          &m_bih,        // stream format
                          m_bih.biSize + // format size
                            m_bih.biClrUsed * sizeof(RGBQUAD));

  if (hr != AVIERR_OK)
  {
    m_sError = _T("AVI Compressed Stream format setting failed.");
    return false;
  }

  // Step 6 : Initialize step counter
  m_lFrame = 0;

  return true;
}
Example #23
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;
}
Example #24
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 cannot accept UTF-8 file names. */
    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 &&
            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->avg_frame_rate.num = stream->info.dwRate;
                st->avg_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);

                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;
}