Esempio n. 1
0
/**
 * Creates a Media Source Reader.
 *
 * @param env JNI env
 * @param path path
 * @param ppMediaSrcReader media source reader
 * @return HRESULT
 */
HRESULT mf_createMediaSourceReader(JNIEnv *env, jstring path, IMFSourceReader **ppMediaSrcReader) {

    HRESULT res = S_OK;
    const LPWSTR pwszFilePath = (LPWSTR)env->GetStringChars(path, NULL);

    res = MFCreateSourceReaderFromURL(
        pwszFilePath, 
        NULL, 
        ppMediaSrcReader);
	if (HRESULT_CODE(res) == ERROR_FILE_NOT_FOUND
			|| HRESULT_CODE(res) == ERROR_PATH_NOT_FOUND
			|| HRESULT_CODE(res) == ERROR_NOT_DOS_DISK
			|| HRESULT_CODE(res) == ERROR_BAD_NETPATH) {
		const char * filePath = env->GetStringUTFChars(path, NULL);
        throwFileNotFoundExceptionIfError(env, res, filePath);
	    env->ReleaseStringUTFChars(path, filePath);
        goto bail;
	}
    if (res != S_OK) {
        throwUnsupportedAudioFileExceptionIfError(env, res, "Failed to create source reader from url");
        goto bail;
    }

bail:

    env->ReleaseStringChars(path, (jchar *)pwszFilePath);

    return res;
}
Esempio n. 2
0
//-------------------------------------------------------------------
// Initialise the source reader
//
HRESULT VidReader::initSourceReader(WCHAR *filename)
{
    HRESULT hr = S_OK;
    IMFAttributes *pAttributes = NULL;

    SafeRelease(&m_pReader);

	// Configure the source reader to perform video processing
    hr = MFCreateAttributes(&pAttributes, 1);
	if (FAILED(hr)) goto done;    
	hr = pAttributes->SetUINT32(MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING, TRUE);
    if (FAILED(hr)) goto done;

    // Create the source reader from the URL
    hr = MFCreateSourceReaderFromURL(filename, pAttributes, &m_pReader);
    if (FAILED(hr)) goto done;

	// Attempt to find a video stream
    hr = selectVideoStream();
    if (FAILED(hr)) goto done;

	// Get the stream format
	hr = getVideoFormat();
    if (FAILED(hr)) goto done;

	// Get the duration
	hr = getDuration();

done:    
    return hr;
}
Esempio n. 3
0
SoundSource::OpenResult SoundSourceMediaFoundation::tryOpen(const AudioSourceConfig& audioSrcCfg) {
    if (SUCCEEDED(m_hrCoInitialize)) {
        qWarning() << "Cannot reopen MediaFoundation file" << getUrlString();
        return OpenResult::FAILED;
    }

    const QString fileName(getLocalFileName());

    if (sDebug) {
        qDebug() << "open()" << fileName;
    }

    // Initialize the COM library.
    m_hrCoInitialize = CoInitializeEx(nullptr,
            COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    if (FAILED(m_hrCoInitialize)) {
        qWarning() << "SSMF: failed to initialize COM";
        return OpenResult::FAILED;
    }
    // Initialize the Media Foundation platform.
    m_hrMFStartup = MFStartup(MF_VERSION);
    if (FAILED(m_hrCoInitialize)) {
        qWarning() << "SSMF: failed to initialize Media Foundation";
        return OpenResult::FAILED;
    }

    // Create the source reader to read the input file.
    // Note: we cannot use QString::toStdWString since QT 4 is compiled with
    // '/Zc:wchar_t-' flag and QT 5 not
    const ushort* const fileNameUtf16 = fileName.utf16();
    static_assert(sizeof(wchar_t) == sizeof(ushort), "QString::utf16(): wchar_t and ushort have different sizes");
    HRESULT hr = MFCreateSourceReaderFromURL(
            reinterpret_cast<const wchar_t*>(fileNameUtf16),
            nullptr,
            &m_pReader);

    if (FAILED(hr)) {
        qWarning() << "SSMF: Error opening input file:" << fileName;
        return OpenResult::FAILED;
    }

    if (!configureAudioStream(audioSrcCfg)) {
        qWarning() << "SSMF: Error configuring audio stream.";
        return OpenResult::FAILED;
    }

    if (!readProperties()) {
        qWarning() << "SSMF::readProperties failed";
        return OpenResult::FAILED;
    }

    //Seek to position 0, which forces us to skip over all the header frames.
    //This makes sure we're ready to just let the Analyzer rip and it'll
    //get the number of samples it expects (ie. no header frames).
    seekSampleFrame(0);

    return OpenResult::SUCCEEDED;
}
Result SoundSourceMediaFoundation::tryOpen(const Mixxx::AudioSourceConfig& audioSrcCfg) {
    if (SUCCEEDED(m_hrCoInitialize)) {
        qWarning() << "Cannot reopen MediaFoundation file" << getUrlString();
        return ERR;
    }

    const QString fileName(getLocalFileName());

    if (sDebug) {
        qDebug() << "open()" << fileName;
    }

    // Initialize the COM library.
    m_hrCoInitialize = CoInitializeEx(NULL,
            COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    if (FAILED(m_hrCoInitialize)) {
        qWarning() << "SSMF: failed to initialize COM";
        return ERR;
    }
    // Initialize the Media Foundation platform.
    m_hrMFStartup = MFStartup(MF_VERSION);
    if (FAILED(m_hrCoInitialize)) {
        qWarning() << "SSMF: failed to initialize Media Foundation";
        return ERR;
    }

    QString qurlStr(fileName);
    // http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/35c6a451-3507-40c8-9d1c-8d4edde7c0cc
    // gives maximum path + file length as 248 + 260, using that -bkgood
    m_wcFilename = new wchar_t[248 + 260];
    int wcFilenameLength(fileName.toWCharArray(m_wcFilename));
    // toWCharArray does not append a null terminator to the string!
    m_wcFilename[wcFilenameLength] = '\0';

    // Create the source reader to read the input file.
    HRESULT hr = MFCreateSourceReaderFromURL(m_wcFilename, NULL, &m_pReader);
    if (FAILED(hr)) {
        qWarning() << "SSMF: Error opening input file:" << fileName;
        return ERR;
    }

    if (!configureAudioStream(audioSrcCfg)) {
        qWarning() << "SSMF: Error configuring audio stream.";
        return ERR;
    }

    //Seek to position 0, which forces us to skip over all the header frames.
    //This makes sure we're ready to just let the Analyser rip and it'll
    //get the number of samples it expects (ie. no header frames).
    seekSampleFrame(0);

    return OK;
}
int SoundSourceMediaFoundation::open()
{
    if (sDebug) {
        qDebug() << "open()" << m_qFilename;
    }

    QString qurlStr(m_qFilename);
    int wcFilenameLength(m_qFilename.toWCharArray(m_wcFilename));
    // toWCharArray does not append a null terminator to the string!
    m_wcFilename[wcFilenameLength] = '\0';

    HRESULT hr(S_OK);
    // Initialize the COM library.
    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    if (FAILED(hr)) {
        qWarning() << "SSMF: failed to initialize COM";
        return ERR;
    }

    // Initialize the Media Foundation platform.
    hr = MFStartup(MF_VERSION);
    if (FAILED(hr)) {
        qWarning() << "SSMF: failed to initialize Media Foundation";
        return ERR;
    }

    // Create the source reader to read the input file.
    hr = MFCreateSourceReaderFromURL(m_wcFilename, NULL, &m_pReader);
    if (FAILED(hr)) {
        qWarning() << "SSMF: Error opening input file:" << m_qFilename;
        return ERR;
    }

    if (!configureAudioStream()) {
        qWarning() << "SSMF: Error configuring audio stream.";
        return ERR;
    }

    if (!readProperties()) {
        qWarning() << "SSMF::readProperties failed";
        return ERR;
    }

    //Seek to position 0, which forces us to skip over all the header frames.
    //This makes sure we're ready to just let the Analyser rip and it'll
    //get the number of samples it expects (ie. no header frames).
    seek(0);

    return OK;
}
HRESULT MFMovieSource::Open( const wchar_t* pszFilePath )
{
  HRESULT hr;
  hr=MFCreateSourceReaderFromURL( pszFilePath, CreateSourceReaderAttribute(), &_reader );
  PKY_IF_ERR_RETURN( hr, "Create SourceReader Failed" );

  hr=GetDuration( _reader, m_Duration );
  PKY_IF_ERR_RETURN( hr, "GetDuration Failed" );

  hr=GetSourceFlags( _reader, &m_SeekingFlag );

  hr=EnumerateTypsForStream( _reader,(DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, [this]( IMFMediaType*pType )->bool {
    UINT32 wd;
    UINT32 ht;
    if( SUCCEEDED( GetFrameSize( pType, &wd, &ht ) ) )
    {
      this->_wd=wd;
      this->_ht=ht;
    }
    if( SUCCEEDED( GetKeyFrameDelta( pType, &this->_keyFrameDelta ) ) )
    {

    }
    uint32_t numer, denum;
    if( SUCCEEDED(GetFrameRate(pType, numer, denum)) )
    {
      this->_numer = numer;
      this->_denum = denum;
    }
    return true;
  } );

  _frameCount = (UINT64)(m_Duration * _numer/_denum/10000000.0 + 0.001);

  hr=ConfigureDecoder( _reader, (DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM );
  hr=ConfigureDecoder( _reader, (DWORD)MF_SOURCE_READER_FIRST_AUDIO_STREAM );

  //Jump(0);

  return E_NOTIMPL;
}
Esempio n. 7
0
unsigned char *BBWin8Game::LoadAudioData( String path,int *length,int *channels,int *format,int *hertz ){

	String url=PathToFilePath( path );
	
	DXASS( MFStartup( MF_VERSION ) );
	
	IMFAttributes *attrs;
	DXASS( MFCreateAttributes( &attrs,1 ) );
	DXASS( attrs->SetUINT32( MF_LOW_LATENCY,TRUE ) );
	
	IMFSourceReader *reader;
	DXASS( MFCreateSourceReaderFromURL( url.ToCString<wchar_t>(),attrs,&reader ) );
	
	attrs->Release();

	IMFMediaType *mediaType;
	DXASS( MFCreateMediaType( &mediaType ) );
	DXASS( mediaType->SetGUID( MF_MT_MAJOR_TYPE,MFMediaType_Audio ) );
	DXASS( mediaType->SetGUID( MF_MT_SUBTYPE,MFAudioFormat_PCM ) );

	DXASS( reader->SetCurrentMediaType( MF_SOURCE_READER_FIRST_AUDIO_STREAM,0,mediaType ) );
    
	mediaType->Release();

	IMFMediaType *outputMediaType;
	DXASS( reader->GetCurrentMediaType( MF_SOURCE_READER_FIRST_AUDIO_STREAM,&outputMediaType ) );
	
	WAVEFORMATEX *wformat;
	uint32 formatByteCount=0;
	DXASS( MFCreateWaveFormatExFromMFMediaType( outputMediaType,&wformat,&formatByteCount ) );

	*channels=wformat->nChannels;
	*format=wformat->wBitsPerSample/8;
	*hertz=wformat->nSamplesPerSec;

	CoTaskMemFree( wformat );
    
	outputMediaType->Release();
/*    
	PROPVARIANT var;
	DXASS( reader->GetPresentationAttribute( MF_SOURCE_READER_MEDIASOURCE,MF_PD_DURATION,&var ) );
	LONGLONG duration=var.uhVal.QuadPart;
	float64 durationInSeconds=(duration / (float64)(10000 * 1000));
	m_maxStreamLengthInBytes=(uint32)( durationInSeconds * m_waveFormat.nAvgBytesPerSec );
*/
	std::vector<unsigned char*> bufs;
	std::vector<uint32> lens;
	uint32 len=0;
    
	for( ;; ){
		uint32 flags=0;
		IMFSample *sample;
		DXASS( reader->ReadSample( MF_SOURCE_READER_FIRST_AUDIO_STREAM,0,0,reinterpret_cast<DWORD*>(&flags),0,&sample ) );
		
		if( flags & MF_SOURCE_READERF_ENDOFSTREAM ){
			break;
		}
		if( sample==0 ){ 
			abort();
		}
		
		IMFMediaBuffer *mediaBuffer;
		DXASS( sample->ConvertToContiguousBuffer( &mediaBuffer ) );

		uint8 *audioData=0;
		uint32 sampleBufferLength=0;
		DXASS( mediaBuffer->Lock( &audioData,0,reinterpret_cast<DWORD*>( &sampleBufferLength ) ) );
		
		unsigned char *buf=(unsigned char*)malloc( sampleBufferLength );
		memcpy( buf,audioData,sampleBufferLength );
		
		bufs.push_back( buf );
		lens.push_back( sampleBufferLength );
		len+=sampleBufferLength;
		
		DXASS( mediaBuffer->Unlock() );
		mediaBuffer->Release();
		
		sample->Release();
	}
	
	reader->Release();
	
	*length=len/(*channels * *format);

	unsigned char *data=(unsigned char*)malloc( len );
	unsigned char *p=data;
	
	for( int i=0;i<bufs.size();++i ){
		memcpy( p,bufs[i],lens[i] );
		free( bufs[i] );
		p+=lens[i];
	}
	
	gc_force_sweep=true;
	
	return data;
}	
    // This sample is using the flag on a music track for demonstrative purposes.
    //
    Microsoft::WRL::ComPtr<IMFAttributes> lowLatencyAttribute;
    DX::ThrowIfFailed(
        MFCreateAttributes(&lowLatencyAttribute, 1)
        );

    DX::ThrowIfFailed(
        lowLatencyAttribute->SetUINT32(MF_LOW_LATENCY, TRUE)
        );

    //
    // Create the source reader on the url (file) with the low latency attributes
    //
    DX::ThrowIfFailed(
        MFCreateSourceReaderFromURL(url->Data(), lowLatencyAttribute.Get(), &m_reader)
        );

    // Set the decoded output format as PCM
    // XAudio2 on Windows can process PCM and ADPCM-encoded buffers.
    // When using MF, this sample always decodes into PCM.

    DX::ThrowIfFailed(
        MFCreateMediaType(&mediaType)
        );

    DX::ThrowIfFailed(
        mediaType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio)
        );

    DX::ThrowIfFailed(
int AudioDecoderMediaFoundation::open()
{
    if (sDebug) {
        std::cout << "open() " << m_filename << std::endl;
    }

    //Assumes m_filename is ASCII and converts it to UTF-16 (wide char).
    /*
	int wcFilenameLength = m_filename.size();
	for(std::wstring::size_type i=0; i < m_filename.size(); ++i)
	{
		m_wcFilename[i] = m_filename[i];
	}
	m_wcFilename[wcFilenameLength] = (wchar_t)'\0';

	std::string s;

	std::wstring stemp = s2ws(m_filename); // Temporary buffer is required
	LPCWSTR result = (LPCWSTR)stemp.c_str();
    */
   
    //LPCWSTR result; 
    const char* utf8Str = m_filename.c_str();
    MultiByteToWideChar(CP_ACP, 
                        0, 
                        utf8Str, 
                        -1, //assume utf8Str is NULL terminated and give us back a NULL terminated string
                        (LPWSTR)m_wcFilename,
                        512);
    
    LPCWSTR result = m_wcFilename;

    HRESULT hr(S_OK);
    // Initialize the COM library.
    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    if (FAILED(hr)) {
        std::cerr << "SSMF: failed to initialize COM" << std::endl;
        return AUDIODECODER_ERROR;
    }

    // Initialize the Media Foundation platform.
    hr = MFStartup(MF_VERSION);
    if (FAILED(hr)) {
        std::cerr << "SSMF: failed to initialize Media Foundation" << std::endl;
        return AUDIODECODER_ERROR;
    }

    // Create the source reader to read the input file.
    hr = MFCreateSourceReaderFromURL(/*m_wcFilename*/result, NULL, &m_pReader);
    if (FAILED(hr)) {
        std::cerr << "SSMF: Error opening input file:" << m_filename << ", with error: " << HRESULT_CODE(hr) << std::endl;
        return AUDIODECODER_ERROR;
    }

    if (!configureAudioStream()) {
        std::cerr << "SSMF: Error configuring audio stream." << std::endl;
        return AUDIODECODER_ERROR;
    }

    if (!readProperties()) {
        std::cerr << "SSMF::readProperties failed" << std::endl;
        return AUDIODECODER_ERROR;
    }

    //Seek to position 0, which forces us to skip over all the header frames.
    //This makes sure we're ready to just let the Analyser rip and it'll
    //get the number of samples it expects (ie. no header frames).
    seek(0);

    return AUDIODECODER_OK;
}
Esempio n. 10
0
void MediaStreamer::Initialize(_In_ const WCHAR* url)
{
    Microsoft::WRL::ComPtr<IMFMediaType> outputMediaType;
    Microsoft::WRL::ComPtr<IMFMediaType> mediaType;

    DX::ThrowIfFailed(
        MFStartup(MF_VERSION)
        );

    DX::ThrowIfFailed(
        MFCreateSourceReaderFromURL(url, nullptr, &m_reader)
        );

    // Set the decoded output format as PCM.
    // XAudio2 on Windows can process PCM and ADPCM-encoded buffers.
    // When this sample uses Media Foundation, it always decodes into PCM.

    DX::ThrowIfFailed(
        MFCreateMediaType(&mediaType)
        );

    DX::ThrowIfFailed(
        mediaType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio)
        );

    DX::ThrowIfFailed(
        mediaType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM)
        );

    DX::ThrowIfFailed(
        m_reader->SetCurrentMediaType(MF_SOURCE_READER_FIRST_AUDIO_STREAM, 0, mediaType.Get())
        );

    // Get the complete WAVEFORMAT from the Media Type.
    DX::ThrowIfFailed(
        m_reader->GetCurrentMediaType(MF_SOURCE_READER_FIRST_AUDIO_STREAM, &outputMediaType)
        );

    uint32 formatSize = 0;
    WAVEFORMATEX* waveFormat;
    DX::ThrowIfFailed(
        MFCreateWaveFormatExFromMFMediaType(outputMediaType.Get(), &waveFormat, &formatSize)
        );
    CopyMemory(&m_waveFormat, waveFormat, sizeof(m_waveFormat));
    CoTaskMemFree(waveFormat);

    // Get the total length of the stream, in bytes.
    PROPVARIANT var;
    DX::ThrowIfFailed(
        m_reader->GetPresentationAttribute(MF_SOURCE_READER_MEDIASOURCE, MF_PD_DURATION, &var)
        );

    // duration is in 100ns units; convert to seconds, and round up
    // to the nearest whole byte.
    ULONGLONG duration = var.uhVal.QuadPart;
    m_maxStreamLengthInBytes =
        static_cast<unsigned int>(
            ((duration * static_cast<ULONGLONG>(m_waveFormat.nAvgBytesPerSec)) + 10000000) /
            10000000
            );
}