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;
}
Пример #2
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);
}
Пример #3
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 = 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 = av_new_stream(s, 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);

                  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;
}
Пример #4
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;

	}
Пример #5
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
}
Пример #6
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;
}
Пример #7
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();
}
Пример #8
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));
	}
}
Пример #9
0
BOOL ExtractAVIFrames(CString szFileName)
{
	AVIFileInit();

	PAVIFILE avi;
	int res = AVIFileOpen(&avi, szFileName, OF_READ, NULL);

	if (res != AVIERR_OK)
	{
		//an error occures
		if (avi != NULL)
			AVIFileRelease(avi);

		return FALSE;
	}

	AVIFILEINFO avi_info;
	AVIFileInfo(avi, &avi_info, sizeof(AVIFILEINFO));

	CString szFileInfo;
	szFileInfo.Format("Dimention: %dx%d\n"
		"Length: %d frames\n"
		"Max bytes per second: %d\n"
		"Samples per second: %d\n"
		"Streams: %d\n"
		"File Type: %d", avi_info.dwWidth,
		avi_info.dwHeight,
		avi_info.dwLength,
		avi_info.dwMaxBytesPerSec,
		(DWORD)(avi_info.dwRate / avi_info.dwScale),
		avi_info.dwStreams,
		avi_info.szFileType);

	AfxMessageBox(szFileInfo, MB_ICONINFORMATION | MB_OK);

	PAVISTREAM pStream;
	res = AVIFileGetStream(avi, &pStream, streamtypeVIDEO /*video stream*/,
		0 /*first stream*/);

	if (res != AVIERR_OK)
	{
		if (pStream != NULL)
			AVIStreamRelease(pStream);

		AVIFileExit();
		return FALSE;
	}

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

	iNumFrames = AVIStreamLength(pStream);
	if (iNumFrames == -1)
	{
		//Error getteing the number of frames inside the stream

		if (pStream != NULL)
			AVIStreamRelease(pStream);

		AVIFileExit();
		return FALSE;
	}

	//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/*(BITMAPINFOHEADER*) AVIGETFRAMEF_BESTDISPLAYFMT*/ /*&bih*/);

	//Get the first frame
	int index = 0;
	for (int i = iFirstFrame; i<iNumFrames; i++)
	{
		index = i - iFirstFrame;

		BYTE* pDIB = (BYTE*)AVIStreamGetFrame(pFrame, index);

		CreateFromPackedDIBPointer(pDIB, index);
	}

	AVIStreamGetFrameClose(pFrame);

	//close the stream after finishing the task
	if (pStream != NULL)
		AVIStreamRelease(pStream);

	AVIFileExit();

	return TRUE;
}
Пример #10
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;
}
Пример #11
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();
}
Пример #12
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();
}
Пример #13
0
PAVISTREAM GetAudioStream(TSTR name,TCHAR *dir)
	{
	HRESULT		hr;
	PAVIFILE	pfile;
	PAVISTREAM	pstream = NULL;
	BOOL res = TRUE;

#ifndef INTERIM_64_BIT	// CCJ

	// RB 5/10/99: Reworked this a bit. Added the current scene dir as a possible search location.
	// Also now using SplitPathFile() instead of doing it by hand.

 	hr = AVIFileOpen(&pfile,name,OF_READ,NULL);
	if (hr) {
		TSTR fileName, tryName;
		SplitPathFile(name, NULL, &fileName);

		// Try the given directory (which is the sound dir)
		tryName = TSTR(dir) + TSTR(_T("\\")) + fileName;
		hr = AVIFileOpen(&pfile,tryName,OF_READ,NULL);
		
		if (hr) {
			// Try the scene directory
			TSTR sceneName = GetCOREInterface()->GetCurFilePath();
			TSTR scenePath;
			SplitPathFile(sceneName, &scenePath, NULL);
			tryName = scenePath + TSTR(_T("\\")) + fileName;
			hr = AVIFileOpen(&pfile,tryName,OF_READ,NULL);
			}

#if 0
		// Try the file in the given directory
		int i = name.Length()-1;
		while (i>0) {
			if (name[i]=='\\' ||
				name[i]==':' ||
				name[i]=='/') {
				i++;
				break;
				}	
			i--;
			}
		if (name.Length()-i>0) {
			TSTR newname = TSTR(dir) + TSTR(_T("\\")) + name.Substr(i,name.Length()-i);
			hr = AVIFileOpen(&pfile,newname,OF_READ,NULL);
			}
#endif
		}
	if (hr) return NULL;

	AVIFileGetStream(pfile,&pstream,streamtypeAUDIO,0);
	AVIFileRelease(pfile);

	if (!pstream) return NULL;

	// Verify it's PCM
	PCMWAVEFORMAT wf;
	LONG l = sizeof(wf);
    AVIStreamReadFormat(pstream,0,&wf,&l);
    if (!l)	{
        AVIStreamRelease(pstream);
		return NULL;
		}
	if (wf.wf.wFormatTag != WAVE_FORMAT_PCM) {
		AVIStreamRelease(pstream);
		return NULL;
		}

#endif	// INTERIM_64_BIT
	return pstream;
	}
Пример #14
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;
}
Пример #15
0
void avi_end(avi_str *s) {
	AVIStreamRelease(s->sp);
	AVIFileRelease(s->fp);
	AVIFileExit();
	free(s);
}
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;
}