public static MFSinkWriter CreateSinkWriterFromMFByteStream(IMFByteStream byteStream, IMFAttributes attributes) { IntPtr p; int result = MFInterops.ExternMFCreateSinkWriterFromURL(null, byteStream, attributes, out p); MediaFoundationException.Try(result, "Interops", "MFCreateSinkWriterFromURL"); return new MFSinkWriter(p); }
public List <object> getOutputNode( List <object> aCompressesMediaTypes, StartSession aStartSession, StartSession aStopSession, WriteClientIP aWriteClientIP) { HttpOutputByteStream.WebServerConfiguration lConfig = new HttpOutputByteStream.WebServerConfiguration(); lConfig.ServerName = "MP4 Screen capture server"; lConfig.IPAddress = IPAddress.Loopback; lConfig.MIME = "video/mp4"; lConfig.Port = 8080; mServer = HttpOutputByteStream.createByteStream(lConfig, aStartSession, aStopSession, aWriteClientIP); mIMFByteStream = mServer; List <object> lTopologyOutputNodesList = new List <object>(); if (mIMFByteStream != null) { mSinkFactory.createOutputNodes( aCompressesMediaTypes, mIMFByteStream, out lTopologyOutputNodesList); } return(lTopologyOutputNodesList); }
/// <summary> /// Writes asynchronously data to a byte stream /// </summary> /// <typeparam name="T">A value type.</typeparam> /// <param name="byteStream">A valid IMFByteStream instance.</param> /// <param name="buffer">An array segment of value types that contain the data to write.</param> /// <returns>A task that represents the asynchronous write operation. The task's result contain the number of items written.</returns> public static Task <int> WriteAsync <T>(this IMFByteStream byteStream, ArraySegment <T> buffer) where T : struct { if (byteStream == null) { throw new ArgumentNullException("byteStream"); } int sizeOfT = Marshal.SizeOf(typeof(T)); // Pin the array to get its addess and to avoid a GC move during the asynchronous operation GCPin pin = new GCPin(buffer.Array); // Get the start address - ArraySegment.Offset is exprimed in item offset IntPtr startAddress = pin.PinnedAddress + (buffer.Offset * sizeOfT); // Get the task for a byte pointer operation Task <int> result = byteStream.WriteAsync(startAddress, buffer.Count * sizeOfT); // return that Task with a continuation to do cleanup and correct the result return(result.ContinueWith <int>((an) => { // Release the GC handle pin.Dispose(); // Result must be exprimed in items count , not in bytes return an.Result / sizeOfT; })); }
public MediaFoundationDecoder(IMFByteStream byteStream) { if (byteStream == null) throw new ArgumentNullException("byteStream"); _byteStream = byteStream; _reader = Initialize(_byteStream); }
/// <summary> /// Creates the reader (overridable by ) /// </summary> protected virtual IMFSourceReader CreateReader(MediaFoundationReaderSettings settings) { IMFSourceReader reader; // If the file exists. if (!String.IsNullOrEmpty(file)) { MediaFoundationInterop.MFCreateSourceReaderFromURL(file, null, out reader); } else { IMFByteStream byteStream = MediaFoundationApi.CreateByteStreamFromStream(_inputStream); MediaFoundationInterop.MFCreateSourceReaderFromByteStream(byteStream, null, out reader); } reader.SetStreamSelection(MediaFoundationInterop.MF_SOURCE_READER_ALL_STREAMS, false); reader.SetStreamSelection(MediaFoundationInterop.MF_SOURCE_READER_FIRST_AUDIO_STREAM, true); // Create a partial media type indicating that we want uncompressed PCM audio var partialMediaType = new MediaType(); partialMediaType.MajorType = MediaTypes.MFMediaType_Audio; partialMediaType.SubType = settings.RequestFloatOutput ? AudioSubtypes.MFAudioFormat_Float : AudioSubtypes.MFAudioFormat_PCM; // set the media type // can return MF_E_INVALIDMEDIATYPE if not supported reader.SetCurrentMediaType(MediaFoundationInterop.MF_SOURCE_READER_FIRST_AUDIO_STREAM, IntPtr.Zero, partialMediaType.MediaFoundationObject); return(reader); }
/// <summary> /// Writes asynchronously data to a byte stream /// </summary> /// <param name="byteStream">A valid IMFByteStream instance.</param> /// <param name="bufferPtr">A pointer designating the memory location that contain the data to write.</param> /// <param name="bufferSize">The maximum number of bytes to write to the byte stream.</param> /// <returns>A task that represents the asynchronous write operation. The task's result contain the number of bytes written.</returns> public static Task <int> WriteAsync(this IMFByteStream byteStream, IntPtr bufferPtr, int bufferSize) { if (byteStream == null) { throw new ArgumentNullException("byteStream"); } TaskCompletionSource <int> tcs = new TaskCompletionSource <int>(); HResult hrBegin = byteStream.BeginWrite(bufferPtr, bufferSize, new MFAsyncCallback((ar) => { int bytesWritten = 0; try { HResult hrEnd = byteStream.EndWrite(ar, out bytesWritten); hrEnd.ThrowExceptionOnError(); tcs.SetResult(bytesWritten); } catch (Exception ex) { tcs.SetException(ex); } }), null); hrBegin.ThrowExceptionOnError(); return(tcs.Task); }
void OpenFile(string sFileName, out IMFByteStream ppStream) { // Open a byte stream for the file. HResult hr = MFExtern.MFCreateFile(MFFileAccessMode.Read, MFFileOpenMode.FailIfNotExist, MFFileFlags.None, sFileName, out ppStream); MFError.ThrowExceptionForHR(hr); }
protected virtual void Dispose(bool disposing) { if (!_disposed) { if (_sinkWriter != null) { while (_sinkWriter.GetStatistics(_streamIndex).DwByteCountQueued > 0) { Thread.Sleep(50); } _sinkWriter.Flush(_streamIndex); _sinkWriter.FinalizeWriting(); _sinkWriter.Dispose(); _sinkWriter = null; } if (_targetStream != null) { _targetStream.Flush(); _targetStream.Close(); Marshal.ReleaseComObject(_targetStream); _targetStream = null; } } _disposed = true; }
private MemoryStream GetBufferedSourceStream() { wc = new WebClient(); using (var ta = new TimedAction((ts) => { log.Debug($"download time {ts.ToString()}"); })) { buffer = new byte[8192 * 2]; //int counter = 0; webStream = wc.OpenRead(musicSource); stream = new MemoryStream(); bytesRead = webStream.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, bytesRead); Task.Run(() => { while (bytesRead > 0) { bytesRead = webStream.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, bytesRead); } }); } IMFByteStream bs = MediaFoundationApi.CreateByteStream(stream); return(stream); }
/// <summary> /// Creates a source reader based on a byte stream /// </summary> /// <param name="byteStream">The byte stream</param> /// <returns>A media foundation source reader</returns> public static IMFSourceReader CreateSourceReaderFromByteStream(IMFByteStream byteStream) { IMFSourceReader reader; MediaFoundationInterop.MFCreateSourceReaderFromByteStream(byteStream, null, out reader); return(reader); }
public static MFSinkWriter CreateSinkWriterFromMFByteStream(IMFByteStream byteStream, IMFAttributes attributes) { IntPtr p; int result = MFInterops.ExternMFCreateSinkWriterFromURL(null, byteStream, attributes, out p); MediaFoundationException.Try(result, "Interops", "MFCreateSinkWriterFromURL"); return(new MFSinkWriter(p)); }
public void Dispose() { if (m_pStream != null) { Marshal.ReleaseComObject(m_pStream); m_pStream = null; } GC.SuppressFinalize(this); }
public MediaFoundationDecoder(IMFByteStream byteStream) { if (byteStream == null) { throw new ArgumentNullException("byteStream"); } _byteStream = byteStream; _reader = Initialize(_byteStream); }
public static ComObject <T> MFCreateSinkWriterFromURL <T>(string outputURL, IMFByteStream byteStream, IMFAttributes attributes) where T : IMFSinkWriter { if (attributes == null) { throw new ArgumentNullException(nameof(attributes)); } MFCreateSinkWriterFromURL(outputURL, byteStream, attributes, out var writer).ThrowOnError(); return(new ComObject <T>((T)writer)); }
public MFByteStream CreateObjectFromByteStreamAsByteStream(IMFByteStream stream, string url, SourceResolverFlags flags = SourceResolverFlags.None, IPropertyStore?propertyStore = null) { CreateObjectFromByteStream(stream, url, (int)(flags | SourceResolverFlags.MediaSource), propertyStore, out ObjectType objectType, out IntPtr nativePtr).CheckError(); if (objectType != ObjectType.ByteStream) { throw new InvalidOperationException("Object type is not ByteStream"); } return(new MFByteStream(nativePtr)); }
//------------------------------------------------------------------- // Name: Create // Description: Static creation function. //------------------------------------------------------------------- public static void Create(IMFByteStream pStream, out CWavRiffParser ppParser) { // Create a riff parser for the 'RIFF' container ppParser = new CWavRiffParser(pStream); // Check the RIFF file type. if (ppParser.RiffType() != new FourCC("WAVE")) { throw new COMException("not a WAVE file", MFError.MF_E_INVALID_FILE_FORMAT); } }
public MediaFoundationDecoder(Stream stream) { if (stream == null) throw new ArgumentNullException("stream"); if (!stream.CanRead) throw new ArgumentException("Stream is not readable.", "stream"); stream = new ComStream(stream); _stream = stream; _byteStream = MediaFoundationCore.IStreamToByteStream((IStream)stream); _reader = Initialize(_byteStream); }
/// <summary> /// Creates a media foundation byte stream based on a stream object /// (usable with WinRT streams) /// </summary> /// <param name="stream">The input stream</param> /// <returns>A media foundation byte stream</returns> public static IMFByteStream CreateByteStreamFromStream(Stream stream) { IMFByteStream byteStream = null; StreamWrapper streamStreamWrapper = new Nequeo.IO.StreamWrapper(stream); IntPtr ptr = Marshal.GetComInterfaceForObject(streamStreamWrapper, typeof(IStream)); IStream pStream = (IStream)Marshal.GetObjectForIUnknown(ptr); MediaFoundationInterop.MFCreateMFByteStreamOnStream(pStream, out byteStream); Marshal.Release(ptr); return(byteStream); }
protected void SetTargetStream(Stream stream, MFMediaType inputMediaType, MFMediaType targetMediaType, Guid containerType) { IMFAttributes attributes = null; try { _targetStream = MediaFoundationCore.IStreamToByteStream(new ComStream(stream)); MFByteStreamCapsFlags flags = MFByteStreamCapsFlags.None; int result = _targetStream.GetCapabilities(ref flags); attributes = MediaFoundationCore.CreateEmptyAttributes(2); attributes.SetUINT32(MediaFoundationAttributes.MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, 1); attributes.SetGUID(MediaFoundationAttributes.MF_TRANSCODE_CONTAINERTYPE, containerType); _sinkWriter = MediaFoundationCore.CreateSinkWriterFromMFByteStream(_targetStream, attributes); _streamIndex = _sinkWriter.AddStream(targetMediaType); _sinkWriter.SetInputMediaType(_streamIndex, inputMediaType, null); _inputMediaType = inputMediaType; _targetMediaType = targetMediaType; _sourceBytesPerSecond = inputMediaType.AverageBytesPerSecond; //initialize the sinkwriter _sinkWriter.BeginWriting(); } catch (Exception) { if (_sinkWriter != null) { _sinkWriter.Dispose(); _sinkWriter = null; } if (_targetStream != null) { _targetStream.Close(); Marshal.ReleaseComObject(_targetStream); _targetStream = null; } throw; } finally { if (attributes != null) { Marshal.ReleaseComObject(attributes); } } }
/// <summary> /// Writes data to a byte stream. /// </summary> /// <typeparam name="T">A value type.</typeparam> /// <param name="byteStream">A valid IMFByteStream instance.</param> /// <param name="buffer">An array of T that contains the data to write.</param> /// <param name="offset">An offset from the start of the buffer at which to begin reading the data written to the byte stream.</param> /// <param name="count">The number of items to write.</param> /// <param name="itemsWritten">Receives the number of items written.</param> /// <returns>If this function succeeds, it returns the S_OK member. Otherwise, it returns another HResult's member that describe the error.</returns> public static HResult Write <T>(this IMFByteStream byteStream, T[] buffer, int offset, int count, out int itemsWritten) where T : struct { if (buffer == null) { throw new ArgumentNullException("value"); } if (count > buffer.Length) { throw new ArgumentOutOfRangeException("count"); } ArraySegment <T> arraySegment = new ArraySegment <T>(buffer, offset, count); return(IMFByteStreamExtensions.Write <T>(byteStream, arraySegment, out itemsWritten)); }
public MediaFoundationDecoder(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanRead) { throw new ArgumentException("Stream is not readable.", "stream"); } stream = new ComStream(stream); _stream = stream; _byteStream = MediaFoundationCore.IStreamToByteStream((IStream)stream); _reader = Initialize(_byteStream); }
/////////////////////////////////////////////////////////////////////// // Name: CreateWavFile // Description: Creates a .wav file from an input file. /////////////////////////////////////////////////////////////////////// static void CreateWavFile(string sURL, string sOutputFile) { IMFByteStream pStream = null; IMFMediaSinkAlt pSink = null; IMFMediaSource pSource = null; IMFTopology pTopology = null; WavSinkNS.CWavSink pObj = null; HResult hr = MFExtern.MFCreateFile(MFFileAccessMode.Write, MFFileOpenMode.DeleteIfExist, MFFileFlags.None, sOutputFile, out pStream); MFError.ThrowExceptionForHR(hr); try { pObj = new WavSinkNS.CWavSink(pStream); pSink = pObj as IMFMediaSinkAlt; // Create the media source from the URL. CreateMediaSource(sURL, out pSource); // Create the topology. CreateTopology(pSource, pSink, out pTopology); // Run the media session. RunMediaSession(pTopology); hr = pSource.Shutdown(); MFError.ThrowExceptionForHR(hr); } finally { if (pStream != null) { Marshal.ReleaseComObject(pStream); } if (pSource != null) { Marshal.ReleaseComObject(pSource); } if (pTopology != null) { Marshal.ReleaseComObject(pTopology); } //pObj.Dispose(); } }
public HResult BeginCreateObject( IMFByteStream pByteStream, string pwszURL, MFResolution dwFlags, IPropertyStore pProps, // Can be NULL. out object ppIUnknownCancelCookie, // Can be NULL. IMFAsyncCallback pCallback, object punkState // Can be NULL ) { // Make sure we *never* leave this entry point with an exception try { HResult hr; m_Log.WriteLine("BeginCreateObject"); ppIUnknownCancelCookie = null; // We don't return a cancellation cookie. if ((pByteStream == null) || (pwszURL == null) || (pCallback == null)) { throw new COMException("bad stream, url, or callback", (int)HResult.E_INVALIDARG); } IMFAsyncResult pResult = null; WavSource pSource = new WavSource(); pSource.Open(pByteStream); hr = MFExtern.MFCreateAsyncResult(pSource as IMFMediaSource, pCallback, punkState, out pResult); MFError.ThrowExceptionForHR(hr); hr = MFExtern.MFInvokeCallback(pResult); MFError.ThrowExceptionForHR(hr); if (pResult != null) { Marshal.ReleaseComObject(pResult); } return(HResult.S_OK); } catch (Exception e) { ppIUnknownCancelCookie = null; return((HResult)Marshal.GetHRForException(e)); } }
/// <summary> /// CRiffParser constructor /// </summary> /// <param name="pStream">Stream to read from RIFF file</param> /// <param name="id">FOURCC of the RIFF container. Should be 'RIFF' or 'LIST'.</param> /// <param name="cbStartOfContainer">Start of the container, as an offset into the stream.</param> public CRiffParser(IMFByteStream pStream, FourCC id, long cbStartOfContainer) { m_chunk = new CRiffChunk(); m_fccID = id; m_llContainerOffset = cbStartOfContainer; if (pStream == null) { throw new COMException("invalid IMFByteStream", E_Pointer); } else { m_pStream = pStream; ReadRiffHeader(); } }
int m_dwBytesRemaining; // How many bytes are left in this chunk? #endregion /// <summary> /// CRiffParser constructor /// </summary> /// <param name="pStream">Stream to read from RIFF file</param> /// <param name="id">FOURCC of the RIFF container. Should be 'RIFF' or 'LIST'.</param> /// <param name="cbStartOfContainer">Start of the container, as an offset into the stream.</param> public CRiffParser(IMFByteStream pStream, FourCC id, long cbStartOfContainer) { m_chunk = new CRiffChunk(); m_fccID = id; m_llContainerOffset = cbStartOfContainer; if (pStream == null) { throw new COMException("invalid IMFByteStream", (int)HResult.E_POINTER); } else { m_pStream = pStream; ReadRiffHeader(); } }
/// <summary> /// Reads data from a byte stream /// </summary> /// <typeparam name="T">A value type.</typeparam> /// <param name="byteStream">A valid IMFByteStream instance.</param> /// <param name="buffer">An array segment of value types that receives the data.</param> /// <param name="itemsRead">The total number of values read into the array segment.</param> /// <returns>If this function succeeds, it returns the S_OK member. Otherwise, it returns another HResult's member that describe the error.</returns> public static HResult Read <T>(this IMFByteStream byteStream, ArraySegment <T> buffer, out int itemsRead) where T : struct { if (byteStream == null) { throw new ArgumentNullException("byteStream"); } int sizeOfT = Marshal.SizeOf(typeof(T)); using (GCPin pin = new GCPin(buffer.Array)) { IntPtr startAddress = pin.PinnedAddress + (buffer.Offset * sizeOfT); HResult hr = byteStream.Read(startAddress, buffer.Count * sizeOfT, out itemsRead); itemsRead /= sizeOfT; return(hr); } }
protected virtual void Dispose(bool disposing) { lock (_lockObj) { if (_reader != null) { _reader.Dispose(); _reader = null; } if (_byteStream != null) { Marshal.ReleaseComObject(_byteStream); _byteStream = null; } if (_stream != null) { _stream.Dispose(); _stream = null; } } }
/// <summary> /// Writes asynchronously data to a byte stream /// </summary> /// <typeparam name="T">A value type.</typeparam> /// <param name="byteStream">A valid IMFByteStream instance.</param> /// <param name="buffer">An array of T that contain the data to write.</param> /// <param name="offset">An index offset in buffer at which to begin storing the data read from the byte stream.</param> /// <param name="count">The maximum number of items to be read from the byte stream.</param> /// <returns>A task that represents the asynchronous write operation. The task's result contain the number of items written.</returns> public static Task <int> WriteAsync <T>(this IMFByteStream byteStream, T[] buffer, int offset, int count) where T : struct { if (buffer == null) { throw new ArgumentNullException("value"); } if (offset > buffer.Length) { throw new ArgumentNullException("offset"); } if ((offset + count) > buffer.Length) { throw new ArgumentOutOfRangeException("count"); } ArraySegment <T> arraySegment = new ArraySegment <T>(buffer, offset, count); return(IMFByteStreamExtensions.WriteAsync <T>(byteStream, arraySegment)); }
///////////////////////////////////////////////////////////////////// // Name: CreateContentInfo // // Reads the ASF Header Object from a byte stream and returns a // pointer to the ASF content information object. // // pStream: Pointer to the byte stream. The byte stream's // current read position must be at the start of the // ASF Header Object. // ppContentInfo: Receives a pointer to the ASF content information // object. ///////////////////////////////////////////////////////////////////// void CreateContentInfo( IMFByteStream pStream, out IMFASFContentInfo ppContentInfo ) { HResult hr; long cbHeader = 0; const int MIN_ASF_HEADER_SIZE = 30; IMFMediaBuffer pBuffer; // Create the ASF content information object. hr = MFExtern.MFCreateASFContentInfo(out ppContentInfo); MFError.ThrowExceptionForHR(hr); // Read the first 30 bytes to find the total header size. ReadDataIntoBuffer(pStream, MIN_ASF_HEADER_SIZE, out pBuffer); try { hr = ppContentInfo.GetHeaderSize(pBuffer, out cbHeader); MFError.ThrowExceptionForHR(hr); // Pass the first 30 bytes to the content information object. hr = ppContentInfo.ParseHeader(pBuffer, 0); MFError.ThrowExceptionForHR(hr); } finally { SafeRelease(pBuffer); } // Read the rest of the header and finish parsing the header. ReadDataIntoBuffer(pStream, (int)(cbHeader - MIN_ASF_HEADER_SIZE), out pBuffer); hr = ppContentInfo.ParseHeader(pBuffer, MIN_ASF_HEADER_SIZE); MFError.ThrowExceptionForHR(hr); }
/// <summary> /// Writes data to a byte stream. /// </summary> /// <typeparam name="T">A value type.</typeparam> /// <param name="byteStream">A valid IMFByteStream instance.</param> /// <param name="structure">A value type to write into the streamIndex.</param> /// <returns>If this function succeeds, it returns the S_OK member. Otherwise, it returns another HResult's member that describe the error.</returns> public static HResult Write <T>(this IMFByteStream byteStream, T structure) where T : struct { if (byteStream == null) { throw new ArgumentNullException("byteStream"); } int sizeOfT = Marshal.SizeOf(typeof(T)); unsafe { void *structPtr = stackalloc byte[sizeOfT]; int bytesWritten; Marshal.StructureToPtr(structure, (IntPtr)structPtr, false); HResult hr = byteStream.Write((IntPtr)structPtr, sizeOfT, out bytesWritten); Debug.Assert(bytesWritten == sizeOfT); return(hr); } }
/// <summary> /// Reads data from a byte stream /// </summary> /// <typeparam name="T">A value type.</typeparam> /// <param name="byteStream">A valid IMFByteStream instance.</param> /// <param name="structure">Receives a structure read from the streamIndex.</param> /// <returns>If this function succeeds, it returns the S_OK member. Otherwise, it returns another HResult's member that describe the error.</returns> public static HResult Read <T>(this IMFByteStream byteStream, out T structure) where T : struct { if (byteStream == null) { throw new ArgumentNullException("byteStream"); } Type typeOfT = typeof(T); int sizeOfT = Marshal.SizeOf(typeOfT); unsafe { void *structPtr = stackalloc byte[sizeOfT]; int bytesRead; HResult hr = byteStream.Read((IntPtr)structPtr, sizeOfT, out bytesRead); Debug.Assert(bytesRead == sizeOfT); structure = (T)Marshal.PtrToStructure((IntPtr)structPtr, typeOfT); return(hr); } }
public override void setOptions(string aOptions) { HttpOutputByteStream.WebServerConfiguration lConfig = new HttpOutputByteStream.WebServerConfiguration(); lConfig.ServerName = "ASF server"; lConfig.IPAddress = IPAddress.Loopback; lConfig.MIME = mMIME; ushort lport; if (ushort.TryParse(aOptions, out lport)) { lConfig.Port = lport; } else { lConfig.Port = 8080; } mIMFByteStream = HttpOutputByteStream.createByteStream(lConfig); }
///////////////////////////////////////////////////////////////////// // Name: ReadDataIntoBuffer // // Reads data from a byte stream and returns a media buffer that // contains the data. // // pStream: Pointer to the byte stream // cbToRead: Number of bytes to read // ppBuffer: Receives a pointer to the buffer. ///////////////////////////////////////////////////////////////////// void ReadDataIntoBuffer( IMFByteStream pStream, // Pointer to the byte stream. int cbToRead, // Number of bytes to read out IMFMediaBuffer ppBuffer // Receives a pointer to the buffer. ) { HResult hr; IntPtr pData; int cbRead; // Actual amount of data read int iMax, iCur; // Create the media buffer. This function allocates the memory. hr = MFExtern.MFCreateMemoryBuffer(cbToRead, out ppBuffer); MFError.ThrowExceptionForHR(hr); // Access the buffer. hr = ppBuffer.Lock(out pData, out iMax, out iCur); MFError.ThrowExceptionForHR(hr); try { // Read the data from the byte stream. hr = pStream.Read(pData, cbToRead, out cbRead); MFError.ThrowExceptionForHR(hr); } finally { hr = ppBuffer.Unlock(); MFError.ThrowExceptionForHR(hr); pData = IntPtr.Zero; } // Update the size of the valid data. hr = ppBuffer.SetCurrentLength(cbRead); MFError.ThrowExceptionForHR(hr); }
public static MFSourceReader CreateSourceReaderFromByteStream(IMFByteStream byteStream, IntPtr attributes) { return CreateSourceReaderFromByteStream(Marshal.GetComInterfaceForObject(byteStream, typeof(IMFByteStream)), attributes); }
void OpenFile(string sFileName, out IMFByteStream ppStream) { // Open a byte stream for the file. int hr = MFExtern.MFCreateFile(MFFileAccessMode.Read, MFFileOpenMode.FailIfNotExist, MFFileFlags.None, sFileName, out ppStream); MFError.ThrowExceptionForHR(hr); }
///////////////////////////////////////////////////////////////////// // Name: DisplayKeyFrames // // Parses the video stream and displays information about the // samples that contain key frames. // // pStream: Pointer to a byte stream. The byte stream's current // read position must be at the start of the ASF Data // Object. // pSplitter: Pointer to the ASF splitter. ///////////////////////////////////////////////////////////////////// void DisplayKeyFrames( IMFByteStream pStream, IMFASFSplitter pSplitter ) { const int cbReadSize = 2048; // Read size (arbitrary value) int cbData; // Amount of data read ASFStatusFlags dwStatus; // Parsing status short wStreamID; // Stream identifier bool bIsKeyFrame = false; // Is the sample a key frame? int cBuffers; // Buffer count int cbTotalLength; // Buffer length long hnsTime; // Time stamp int hr; IMFMediaBuffer pBuffer; IMFSample pSample; while (true) { // Read data into the buffer. ReadDataIntoBuffer(pStream, cbReadSize, out pBuffer); try { hr = pBuffer.GetCurrentLength(out cbData); MFError.ThrowExceptionForHR(hr); if (cbData == 0) { break; // End of file. } // Send the data to the ASF splitter. hr = pSplitter.ParseData(pBuffer, 0, 0); MFError.ThrowExceptionForHR(hr); // Pull samples from the splitter. do { hr = pSplitter.GetNextSample(out dwStatus, out wStreamID, out pSample); MFError.ThrowExceptionForHR(hr); if (pSample == null) { // No samples yet. Parse more data. break; } try { // We received a sample from the splitter. Check to see // if it's a key frame. The default is FALSE. try { int i; hr = pSample.GetUINT32(MFAttributesClsid.MFSampleExtension_CleanPoint, out i); MFError.ThrowExceptionForHR(hr); bIsKeyFrame = i != 0; } catch { bIsKeyFrame = false; } if (bIsKeyFrame) { // Print various information about the key frame. hr = pSample.GetBufferCount(out cBuffers); MFError.ThrowExceptionForHR(hr); hr = pSample.GetTotalLength(out cbTotalLength); MFError.ThrowExceptionForHR(hr); Console.WriteLine(string.Format("Buffer count: {0}", cBuffers)); Console.WriteLine(string.Format("Length: {0} bytes", cbTotalLength)); hr = pSample.GetSampleTime(out hnsTime); MFError.ThrowExceptionForHR(hr); // Convert the time stamp to seconds. double sec = (double)(hnsTime / 10000) / 1000; Console.WriteLine(string.Format("Time stamp: {0} sec.", sec)); } } finally { SafeRelease(pSample); } } while ((dwStatus & ASFStatusFlags.Incomplete) > 0); } finally { SafeRelease(pBuffer); } } Console.WriteLine("Done"); }
public static extern void MFCreateSinkWriterFromURL([In, MarshalAs(UnmanagedType.LPWStr)] string pwszOutputURL, [In] IMFByteStream pByteStream, [In] IMFAttributes pAttributes, [Out] out IMFSinkWriter ppSinkWriter);
private void GetInterface() { MFObjectType pObjectType; object pSource; IMFSourceResolver sr; int hr = MFExtern.MFCreateSourceResolver(out sr); MFError.ThrowExceptionForHR(hr); hr = sr.CreateObjectFromURL( @"file://c:/sourceforge/mflib/test/media/AspectRatio4x3.wmv", MFResolution.ByteStream, null, out pObjectType, out pSource); MFError.ThrowExceptionForHR(hr); m_bs = pSource as IMFByteStream; }
//------------------------------------------------------------------- // Name: Shutdown // Description: Shuts down the stream sink. //------------------------------------------------------------------- public void Shutdown() { int hr; Debug.Assert(!m_IsShutdown); GC.SuppressFinalize(this); if (m_pEventQueue != null) { hr = m_pEventQueue.Shutdown(); MFError.ThrowExceptionForHR(hr); } hr = MFExtern.MFUnlockWorkQueue(m_WorkQueueId); MFError.ThrowExceptionForHR(hr); m_SampleQueue.Clear(); SafeRelease(m_pSink); SafeRelease(m_pEventQueue); SafeRelease(m_pByteStream); SafeRelease(m_pCurrentType); SafeRelease(m_pFinalizeResult); m_pSink = null; m_pEventQueue = null; m_pByteStream = null; m_pCurrentType = null; m_pFinalizeResult = null; m_IsShutdown = true; }
public void Dispose() { TRACE("CWavStream::Dispose"); SafeRelease(m_pEventQueue); SafeRelease(m_pByteStream); SafeRelease(m_pCurrentType); SafeRelease(m_pFinalizeResult); m_pEventQueue = null; m_pByteStream = null; m_pCurrentType = null; m_pFinalizeResult = null; //m_pSink.Dispose(); // break deadly embrace m_pSink = null; GC.SuppressFinalize(this); }
///////////////////////////////////////////////////////////////////// // Name: CreateContentInfo // // Reads the ASF Header Object from a byte stream and returns a // pointer to the ASF content information object. // // pStream: Pointer to the byte stream. The byte stream's // current read position must be at the start of the // ASF Header Object. // ppContentInfo: Receives a pointer to the ASF content information // object. ///////////////////////////////////////////////////////////////////// void CreateContentInfo( IMFByteStream pStream, out IMFASFContentInfo ppContentInfo ) { long cbHeader = 0; const int MIN_ASF_HEADER_SIZE = 30; IMFMediaBuffer pBuffer; // Create the ASF content information object. int hr = MFExtern.MFCreateASFContentInfo(out ppContentInfo); MFError.ThrowExceptionForHR(hr); // Read the first 30 bytes to find the total header size. ReadDataIntoBuffer(pStream, MIN_ASF_HEADER_SIZE, out pBuffer); try { hr = ppContentInfo.GetHeaderSize(pBuffer, out cbHeader); MFError.ThrowExceptionForHR(hr); // Pass the first 30 bytes to the content information object. hr = ppContentInfo.ParseHeader(pBuffer, 0); MFError.ThrowExceptionForHR(hr); } finally { SafeRelease(pBuffer); } // Read the rest of the header and finish parsing the header. ReadDataIntoBuffer(pStream, (int)(cbHeader - MIN_ASF_HEADER_SIZE), out pBuffer); hr = ppContentInfo.ParseHeader(pBuffer, MIN_ASF_HEADER_SIZE); MFError.ThrowExceptionForHR(hr); }
public static extern int MFCreateMFByteStreamOnStreamEx(IStream stream, out IMFByteStream byteStream);
private MFSourceReader Initialize(IMFByteStream stream) { MediaFoundationCore.Startup(); return Initialize(MediaFoundationCore.CreateSourceReaderFromByteStream(stream, IntPtr.Zero)); }
///////////////////////////////////////////////////////////////////// // Name: DisplayKeyFrames // // Parses the video stream and displays information about the // samples that contain key frames. // // pStream: Pointer to a byte stream. The byte stream's current // read position must be at the start of the ASF Data // Object. // pSplitter: Pointer to the ASF splitter. ///////////////////////////////////////////////////////////////////// void DisplayKeyFrames( IMFASFIndexer ai, IMFByteStream pStream, IMFASFSplitter pSplitter ) { const int cbReadSize = 2048; // Read size (arbitrary value) int cbData; // Amount of data read ASFStatusFlags dwStatus; // Parsing status short wStreamID; // Stream identifier bool bIsKeyFrame = false; // Is the sample a key frame? int cBuffers; // Buffer count int cbTotalLength; // Buffer length long hnsTime; // Time stamp IMFMediaBuffer pBuffer; IMFSample pSample; IMFByteStream[] aia = new IMFByteStream[1]; aia[0] = pStream; int hr = ai.SetIndexByteStreams(aia, 1); MFError.ThrowExceptionForHR(hr); ASFIndexIdentifier ii = new ASFIndexIdentifier(); ii.guidIndexType = Guid.Empty; ii.wStreamNumber = 2; bool b; int i1 = 100; IntPtr ip = Marshal.AllocCoTaskMem(i1); ai.GetIndexStatus(ii, out b, ip, ref i1); long l; PropVariant pv = new PropVariant(50000000L); hr = ai.GetSeekPositionForValue(pv, ii, out l, IntPtr.Zero, out i1); MFError.ThrowExceptionForHR(hr); while (true) { // Read data into the buffer. ReadDataIntoBuffer(pStream, cbReadSize, out pBuffer); try { hr = pBuffer.GetCurrentLength(out cbData); MFError.ThrowExceptionForHR(hr); if (cbData == 0) { break; // End of file. } // Send the data to the ASF splitter. hr = pSplitter.ParseData(pBuffer, 0, 0); MFError.ThrowExceptionForHR(hr); // Pull samples from the splitter. do { hr = pSplitter.GetNextSample(out dwStatus, out wStreamID, out pSample); MFError.ThrowExceptionForHR(hr); if (pSample == null) { // No samples yet. Parse more data. break; } try { // We received a sample from the splitter. Check to see // if it's a key frame. The default is FALSE. try { int i; hr = pSample.GetUINT32(MFAttributesClsid.MFSampleExtension_CleanPoint, out i); MFError.ThrowExceptionForHR(hr); bIsKeyFrame = i != 0; } catch { bIsKeyFrame = false; } if (bIsKeyFrame) { // Print various information about the key frame. hr = pSample.GetBufferCount(out cBuffers); MFError.ThrowExceptionForHR(hr); hr = pSample.GetTotalLength(out cbTotalLength); MFError.ThrowExceptionForHR(hr); Console.WriteLine(string.Format("Buffer count: {0}", cBuffers)); Console.WriteLine(string.Format("Length: {0} bytes", cbTotalLength)); hr = pSample.GetSampleTime(out hnsTime); MFError.ThrowExceptionForHR(hr); // Convert the time stamp to seconds. double sec = (double)(hnsTime / 10000) / 1000; Console.WriteLine(string.Format("Time stamp: {0} sec.", sec)); } } finally { SafeRelease(pSample); } } while ((dwStatus & ASFStatusFlags.Incomplete) > 0); } finally { SafeRelease(pBuffer); } } Console.WriteLine("Done"); }
void TestSetLength() { MFObjectType pObjectType; object pSource; IMFSourceResolver sr; int hr; if (File.Exists(path)) { File.Delete(path); } using (FileStream fs = File.Create(path, 1024)) { } hr = MFExtern.MFCreateSourceResolver(out sr); MFError.ThrowExceptionForHR(hr); hr = sr.CreateObjectFromURL( @"file://" + path, MFResolution.ByteStream | MFResolution.Write, null, out pObjectType, out pSource); MFError.ThrowExceptionForHR(hr); m_bs = (IMFByteStream)pSource; hr = m_bs.SetLength(100); MFError.ThrowExceptionForHR(hr); m_write = true; }
long m_rtDuration; // File duration. #endregion Fields #region Constructors // CWavRiffParser is a specialization of the generic RIFF parser object, // and is designed to parse .wav files. CWavRiffParser(IMFByteStream pStream) : base(pStream, new FourCC("RIFF"), 0) { }
public CWavSink(IMFByteStream pStream) { TRACE("CWavSink::CWavSink(IMFByteStream)"); if (pStream != null) { Init(); m_pStream = new CWavStream(this, (IMFByteStream)pStream); } else { throw new COMException("Null pstream", E_Pointer); } }
protected void SetTargetStream(Stream stream, MFMediaType inputMediaType, MFMediaType targetMediaType, Guid containerType) { IMFAttributes attributes = null; try { _targetStream = MediaFoundationCore.IStreamToByteStream(new ComStream(stream)); MFByteStreamCapsFlags flags = MFByteStreamCapsFlags.None; int result = _targetStream.GetCapabilities(ref flags); attributes = MediaFoundationCore.CreateEmptyAttributes(2); attributes.SetUINT32(MediaFoundationAttributes.MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, 1); attributes.SetGUID(MediaFoundationAttributes.MF_TRANSCODE_CONTAINERTYPE, containerType); _sinkWriter = MediaFoundationCore.CreateSinkWriterFromMFByteStream(_targetStream, attributes); _streamIndex = _sinkWriter.AddStream(targetMediaType); _sinkWriter.SetInputMediaType(_streamIndex, inputMediaType, null); _inputMediaType = inputMediaType; _targetMediaType = targetMediaType; _sourceBytesPerSecond = inputMediaType.AverageBytesPerSecond; //initialize the sinkwriter _sinkWriter.BeginWriting(); } catch (Exception) { if (_sinkWriter != null) { _sinkWriter.Dispose(); _sinkWriter = null; } if (_targetStream != null) { _targetStream.Close(); Marshal.ReleaseComObject(_targetStream); _targetStream = null; } throw; } finally { if (attributes != null) Marshal.ReleaseComObject(attributes); } }
int m_WorkQueueId; // ID of the work queue for asynchronous operations. #endregion Fields #region Constructors public CWavStream(CWavSink pParent, IMFByteStream pByteStream) { int hr; TRACE("CWavStream::CWavStream"); m_SampleQueue = new Queue(); m_state = State.TypeNotSet; m_IsShutdown = false; m_pSink = null; m_pEventQueue = null; m_pByteStream = null; m_pCurrentType = null; m_pFinalizeResult = null; m_StartTime = 0; m_cbDataWritten = 0; m_WorkQueueId = 0; Debug.Assert(pParent != null); Debug.Assert(pByteStream != null); MFByteStreamCapabilities dwCaps = MFByteStreamCapabilities.None; const MFByteStreamCapabilities dwRequiredCaps = (MFByteStreamCapabilities.IsWritable | MFByteStreamCapabilities.IsSeekable); // Make sure the byte stream has the necessary caps bits. hr = pByteStream.GetCapabilities(out dwCaps); MFError.ThrowExceptionForHR(hr); if ((dwCaps & dwRequiredCaps) != dwRequiredCaps) { throw new COMException("stream doesn't have required caps", E_Fail); } // Move the file pointer to leave room for the RIFF headers. hr = pByteStream.SetCurrentPosition(Marshal.SizeOf(typeof(WAV_FILE_HEADER))); MFError.ThrowExceptionForHR(hr); // Create the event queue helper. hr = MFExternAlt.MFCreateEventQueue(out m_pEventQueue); MFError.ThrowExceptionForHR(hr); // Allocate a new work queue for async operations. hr = MFExtern.MFAllocateWorkQueue(out m_WorkQueueId); MFError.ThrowExceptionForHR(hr); m_pByteStream = pByteStream; m_pSink = pParent; }
public static extern void MFCreateMFByteStreamOnStreamEx([MarshalAs(UnmanagedType.IUnknown)] object punkStream, out IMFByteStream ppByteStream);
/// <summary> /// Creates a source reader based on a byte stream /// </summary> /// <param name="byteStream">The byte stream</param> /// <returns>A media foundation source reader</returns> public static IMFSourceReader CreateSourceReaderFromByteStream(IMFByteStream byteStream) { IMFSourceReader reader; MediaFoundationInterop.MFCreateSourceReaderFromByteStream(byteStream, null, out reader); return reader; }
//------------------------------------------------------------------- // Name: Open // Description: Opens the source from a bytestream. // // The bytestream handler calls this method after it creates the // source. // // Note: This method is not a public API. It is a custom method on // for our bytestream class to use. //------------------------------------------------------------------- internal void Open(IMFByteStream pStream) { m_Log.WriteLine("Open"); lock (this) { if (m_pRiff != null) { // The media source has already been opened. throw new COMException("The media source has already been opened", MFError.MF_E_INVALIDREQUEST); } try { // Create a new WAVE RIFF parser object to parse the stream. CWavRiffParser.Create(pStream, out m_pRiff); // Parse the WAVE header. This fails if the header is not // well-formed. m_pRiff.ParseWAVEHeader(); // Validate the WAVEFORMATEX structure from the file header. ValidateWaveFormat(m_pRiff.Format(), m_pRiff.FormatSize()); } catch { Shutdown(); throw; } } }
public int BeginCreateObject( IMFByteStream pByteStream, string pwszURL, MFResolution dwFlags, IPropertyStore pProps, // Can be NULL. out object ppIUnknownCancelCookie, // Can be NULL. IMFAsyncCallback pCallback, object punkState // Can be NULL ) { // Make sure we *never* leave this entry point with an exception try { int hr; m_Log.WriteLine("BeginCreateObject"); ppIUnknownCancelCookie = null; // We don't return a cancellation cookie. if ((pByteStream == null) || (pwszURL == null) || (pCallback == null)) { throw new COMException("bad stream, url, or callback", E_InvalidArgument); } IMFAsyncResult pResult = null; WavSource pSource = new WavSource(); pSource.Open(pByteStream); hr = MFExtern.MFCreateAsyncResult(pSource as IMFMediaSource, pCallback, punkState, out pResult); MFError.ThrowExceptionForHR(hr); hr = MFExtern.MFInvokeCallback(pResult); MFError.ThrowExceptionForHR(hr); if (pResult != null) { Marshal.ReleaseComObject(pResult); } return S_Ok; } catch (Exception e) { ppIUnknownCancelCookie = null; return Marshal.GetHRForException(e); } }
///////////////////////////////////////////////////////////////////// // Name: ReadDataIntoBuffer // // Reads data from a byte stream and returns a media buffer that // contains the data. // // pStream: Pointer to the byte stream // cbToRead: Number of bytes to read // ppBuffer: Receives a pointer to the buffer. ///////////////////////////////////////////////////////////////////// void ReadDataIntoBuffer( IMFByteStream pStream, // Pointer to the byte stream. int cbToRead, // Number of bytes to read out IMFMediaBuffer ppBuffer // Receives a pointer to the buffer. ) { IntPtr pData; int cbRead; // Actual amount of data read int iMax, iCur; // Create the media buffer. This function allocates the memory. int hr = MFExtern.MFCreateMemoryBuffer(cbToRead, out ppBuffer); MFError.ThrowExceptionForHR(hr); // Access the buffer. hr = ppBuffer.Lock(out pData, out iMax, out iCur); MFError.ThrowExceptionForHR(hr); try { // Read the data from the byte stream. hr = pStream.Read(pData, cbToRead, out cbRead); MFError.ThrowExceptionForHR(hr); } finally { hr = ppBuffer.Unlock(); MFError.ThrowExceptionForHR(hr); pData = IntPtr.Zero; } // Update the size of the valid data. hr = ppBuffer.SetCurrentLength(cbRead); MFError.ThrowExceptionForHR(hr); }