private void ShutDown(string errmsg) { bool err = !string.IsNullOrEmpty(errmsg); if (err) { _reasonToStop = ReasonToFinishPlaying.DeviceLost; } if (IsFileSource && !err) { _reasonToStop = ReasonToFinishPlaying.EndOfStreamReached; } if (_afr != null && _afr.IsOpen) { try { _afr.Dispose(); //calls close } catch (Exception ex) { MainForm.LogExceptionToFile(ex, "FFMPEG"); } } AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_reasonToStop)); }
private void ShutDown(string errmsg) { bool err = !string.IsNullOrEmpty(errmsg); if (err) { _reasonToStop = ReasonToFinishPlaying.DeviceLost; } try { if (_vfr != null && _vfr.IsOpen) { _vfr?.Dispose(); //calls close } } catch (Exception ex) { Logger.LogExceptionToFile(ex, "FFMPEG"); } PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_reasonToStop)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_reasonToStop)); _stopEvent.Close(); _stopEvent = null; _stopping = false; }
void WaveInRecordingStopped(object sender, StoppedEventArgs e) { _started = false; if (e.Exception != null && e.Exception.Message.IndexOf("NoDriver", StringComparison.Ordinal) != -1) { _res = ReasonToFinishPlaying.DeviceLost; } AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); }
private void DirectStreamListener() { try { var data = new byte[PacketSize]; if (_stream != null) { while (!_stopEvent.WaitOne(0, false) && !MainForm.ShuttingDown) { var da = DataAvailable; if (da != null) { int recbytesize = _stream.Read(data, 0, PacketSize); if (recbytesize > 0) { if (_sampleChannel != null) { _waveProvider.AddSamples(data, 0, recbytesize); var sampleBuffer = new float[recbytesize]; int read = _sampleChannel.Read(sampleBuffer, 0, recbytesize); da(this, new DataAvailableEventArgs((byte[])data.Clone(), read)); if (Listening) { WaveOutProvider?.AddSamples(data, 0, read); } } } else { break; } if (_stopEvent.WaitOne(Interval, false)) { break; } } } } AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser)); } catch (Exception e) { AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.DeviceLost)); //if (AudioSourceError!=null) // AudioSourceError(this, new AudioSourceErrorEventArgs(e.Message)); MainForm.LogExceptionToFile(e, "Direct"); } _stream?.Close(); _stream = null; }
private void WebStreamListener() { try { var data = new byte[6400]; if (_socket != null) { while (!_stopEvent.WaitOne(0, false) && !MainForm.ShuttingDown) { var da = DataAvailable; if (da != null) { int recbytesize = _socket.Receive(data, 0, 6400, SocketFlags.None); if (_sampleChannel != null) { _waveProvider.AddSamples(data, 0, recbytesize); var sampleBuffer = new float[recbytesize]; int read = _sampleChannel.Read(sampleBuffer, 0, recbytesize); da(this, new DataAvailableEventArgs((byte[])data.Clone(), read)); if (Listening) { WaveOutProvider?.AddSamples(data, 0, read); } } } else { break; } // need to stop ? if (_stopEvent.WaitOne(0, false)) { break; } } } AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser)); } catch (Exception e) { //if (AudioSourceError!=null) // AudioSourceError(this, new AudioSourceErrorEventArgs(e.Message)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.DeviceLost)); Logger.LogExceptionToFile(e, "WebStream"); } if (_socket != null) { _socket.Close(); _socket = null; } }
private void Cleanup() { Debug.WriteLine("CLEANUP"); _connecting = false; IsRunning = false; _quit = false; PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); }
/// <summary> /// Stop audio source. /// </summary> /// /// <remarks><para>Stops audio source.</para> /// </remarks> /// public void Stop() { _res = ReasonToFinishPlaying.StoppedByUser; if (_waveIn == null) { AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); } else { StopSource(); } }
/// <summary> /// Start audio source. /// </summary> /// /// <remarks>Starts audio source and return execution to caller. audio source /// object creates background thread and notifies about new frames with the /// help of <see cref="DataAvailable"/> event.</remarks> /// /// <exception cref="ArgumentException">audio source is not specified.</exception> /// public void Start() { if (string.IsNullOrEmpty(_source)) { throw new ArgumentException("Audio source is not specified."); } if (_started) { return; } // check source lock (_lock) { if (_started) { return; } int i = 0, selind = -1; for (var n = 0; n < WaveIn.DeviceCount; n++) { if (WaveIn.GetCapabilities(n).ProductName == _source) { selind = i; } i++; } if (selind == -1) { AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.DeviceLost)); return; } _started = true; _waveIn = new WaveInEvent { BufferMilliseconds = 200, DeviceNumber = selind, WaveFormat = RecordingFormat }; _waveIn.DataAvailable += WaveInDataAvailable; _waveIn.RecordingStopped += WaveInRecordingStopped; _waveProvider = new WaveInProvider(_waveIn); _sampleChannel = new SampleChannel(_waveProvider); _sampleChannel.PreVolumeMeter += SampleChannelPreVolumeMeter; _waveIn.StartRecording(); } }
public void Stop() { if (IsRunning) { _res = ReasonToFinishPlaying.StoppedByUser; _abort?.Set(); } else { _res = ReasonToFinishPlaying.StoppedByUser; AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); } }
/// <summary> /// Start audio source. /// </summary> /// /// <remarks>Starts audio source and return execution to caller. audio source /// object creates background thread and notifies about new frames with the /// help of <see cref="DataAvailable"/> event.</remarks> /// /// <exception cref="ArgumentException">audio source is not specified.</exception> /// public void Start() { if (!IsRunning) { // check source int i = 0, selind = -1; for (int n = 0; n < WaveIn.DeviceCount; n++) { if (WaveIn.GetCapabilities(n).ProductName == _source) { selind = i; } i++; } if (selind == -1) { //device no longer connected or not configured if (i > 0) { selind = 0; } else { //if (AudioSourceError != null) // AudioSourceError(this, new AudioSourceErrorEventArgs("not connected")); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.DeviceLost)); return; } } _waveIn = new WaveInEvent { BufferMilliseconds = 200, DeviceNumber = selind, WaveFormat = RecordingFormat }; _waveIn.DataAvailable += WaveInDataAvailable; _waveIn.RecordingStopped += WaveInRecordingStopped; _waveProvider = new WaveInProvider(_waveIn); _sampleChannel = new SampleChannel(_waveProvider); if (LevelChanged != null) { _sampleChannel.PreVolumeMeter += SampleChannelPreVolumeMeter; } _waveIn.StartRecording(); } }
private void CleanUp() { try { Program.MutexHelper.Wait(); if (pConvertedFrameBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(pConvertedFrameBuffer); pConvertedFrameBuffer = IntPtr.Zero; } if (_formatContext != null) { if (_formatContext->streams != null) { var j = (int)_formatContext->nb_streams; for (var i = j - 1; i >= 0; i--) { var stream = _formatContext->streams[i]; if (stream != null && stream->codec != null && stream->codec->codec != null) { stream->discard = AVDiscard.AVDISCARD_ALL; ffmpeg.avcodec_close(stream->codec); } } } fixed(AVFormatContext **f = &_formatContext) { ffmpeg.avformat_close_input(f); } _formatContext = null; } if (_hwDeviceCtx != null) { var f = _hwDeviceCtx; ffmpeg.av_buffer_unref(&f); _hwDeviceCtx = null; } _videoStream = null; _audioStream = null; _audioCodecContext = null; _videoCodecContext = null; if (_swrContext != null) { fixed(SwrContext **s = &_swrContext) { ffmpeg.swr_free(s); } _swrContext = null; } if (pConvertContext != null) { ffmpeg.sws_freeContext(pConvertContext); pConvertContext = null; } if (sampleChannel != null) { sampleChannel.PreVolumeMeter -= SampleChannelPreVolumeMeter; sampleChannel = null; } } catch (Exception ex) { Logger.LogException(ex, SourceName + ": Media Stream (close)"); } finally { try { Program.MutexHelper.Release(); } catch { } } PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); }
public void Start() { Debug.WriteLine("START"); if (IsRunning) { return; } IsRunning = true; try { if (_failedLoad || string.IsNullOrEmpty(VlcHelper.VLCLocation)) { throw new ApplicationException("VLC not found. Set location in settings."); } _quit = false; _commands.Clear(); Task.Run(async() => { while (!_quit) { string cmd; if (_commands.TryDequeue(out cmd)) { switch (cmd) { case "init": try { Init(); } catch (ApplicationException ex) { Logger.LogException(ex, "VLC"); _res = ReasonToFinishPlaying.VideoSourceError; _quit = true; } break; case "stop": if (_mediaPlayer != null && _mediaPlayer.IsPlaying) { _mediaPlayer.Stop(); } else { _quit = true; } break; } } await Task.Delay(500); } Cleanup(); }); _commands.Enqueue("init"); _lastFrame = DateTime.UtcNow; _connecting = true; } catch (Exception ex) { Logger.LogException(ex, "VLCStream"); ErrorHandler?.Invoke("Invalid Source (" + Source + ")"); _connecting = false; IsRunning = false; _quit = false; _res = ReasonToFinishPlaying.VideoSourceError; PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); } }
private void SpyServerListener() { var data = new byte[3200]; try { var request = (HttpWebRequest)WebRequest.Create(_source); request.Timeout = 10000; request.ReadWriteTimeout = 5000; var response = request.GetResponse(); using (Stream stream = response.GetResponseStream()) { if (stream == null) { throw new Exception("Stream is null"); } stream.ReadTimeout = 5000; while (!_stopEvent.WaitOne(0, false)) { int recbytesize = stream.Read(data, 0, 3200); if (recbytesize == 0) { throw new Exception("lost stream"); } var recive = Encoding.UTF8.GetString(data, 0, recbytesize); if (recive.Equals("setCurrentVolumeMute")) { setVolumeMute(); } else if (recive.StartsWith("setCurrentVolume")) { if (recive.IndexOf("#") > -1) { var cmd = recive.Split(new[] { '#' }); Thread setValueThread = new Thread(new ParameterizedThreadStart(this.setVolumeFromServer)); setValueThread.IsBackground = true; setValueThread.Start(cmd[1]); Thread setValueThread1 = new Thread(new ParameterizedThreadStart(this.setVolumeWINMM)); setValueThread1.IsBackground = true; setValueThread1.Start(cmd[1]); } } else { byte[] dec; ALawDecoder.ALawDecode(data, recbytesize, out dec); var da = DataAvailable; if (da != null) { if (_sampleChannel != null) { _waveProvider.AddSamples(dec, 0, dec.Length); var sampleBuffer = new float[dec.Length]; int read = _sampleChannel.Read(sampleBuffer, 0, dec.Length); da(this, new DataAvailableEventArgs((byte[])dec.Clone(), read)); if (Listening) { WaveOutProvider?.AddSamples(dec, 0, read); } } } else { break; } // need to stop ? if (_stopEvent.WaitOne(0, false)) { break; } } } } AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser)); } catch (Exception e) { var af = AudioFinished; af?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.DeviceLost)); //Logger.LogExceptionToFile(e,"ispyServer"); } if (_sampleChannel != null) { _sampleChannel.PreVolumeMeter -= SampleChannelPreVolumeMeter; _sampleChannel = null; } if (_waveProvider?.BufferedBytes > 0) { _waveProvider.ClearBuffer(); } if (WaveOutProvider?.BufferedBytes > 0) { WaveOutProvider?.ClearBuffer(); } }
private void Init() { _mediaPlayer?.Dispose(); _videoFormat = VideoFormat; _lockCB = LockVideo; _unlockCB = UnlockVideo; _displayCB = DisplayVideo; //_cleanupVideoCB = CleanupVideo; _audioSetup = AudioSetup; _processAudio = ProcessAudio; _cleanupAudio = CleanupAudio; _pauseAudio = PauseAudio; _resumeAudio = ResumeAudio; _flushAudio = FlushAudio; _drainAudio = DrainAudio; string overrideURL = null; if (_camera != null) { switch (_camera.Camobject.settings.sourceindex) { case 9: var od = _camera.ONVIFDevice; if (od != null) { var ep = od.StreamEndpoint; if (ep != null) { var u = ep.Uri.Uri; overrideURL = u; } } break; } } FromType ftype = FromType.FromLocation; Seekable = false; var murl = overrideURL ?? Source; if (string.IsNullOrEmpty(murl)) { throw new Exception("Video source is empty"); } try { var p = Path.GetFullPath(overrideURL ?? Source); Seekable = !string.IsNullOrEmpty(p); if (Seekable) { ftype = FromType.FromPath; } } catch (Exception) { Seekable = false; } using (var media = new Media(LibVLC, murl, ftype)) { Duration = Time = 0; foreach (var opt in _options) { media.AddOption(opt); } _mediaPlayer = new MediaPlayer(media); _mediaPlayer.SetVideoFormatCallbacks(_videoFormat, null);// _cleanupVideoCB); _mediaPlayer.SetVideoCallbacks(_lockCB, _unlockCB, _displayCB); _mediaPlayer.TimeChanged += _mediaPlayer_TimeChanged; _mediaPlayer.EnableHardwareDecoding = false; _mediaPlayer.SetAudioFormatCallback(_audioSetup, _cleanupAudio); _mediaPlayer.SetAudioCallbacks(_processAudio, _pauseAudio, _resumeAudio, _flushAudio, _drainAudio); _mediaPlayer.EncounteredError += (sender, e) => { ErrorHandler?.Invoke("VLC Error"); _res = ReasonToFinishPlaying.VideoSourceError; }; _mediaPlayer.EndReached += (sender, e) => { _res = ReasonToFinishPlaying.VideoSourceError; }; _mediaPlayer.Stopped += (sender, e) => { Logger.LogMessage("VLC stopped"); Task.Run(() => { Debug.WriteLine("CLEANUP"); IsRunning = false; _stopping = false; _stopped?.Set(); PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); }); }; } _lastTimeUpdate = DateTime.UtcNow; _mediaPlayer.Play(); }
private void StreamMP3() { _abort = new ManualResetEvent(false); HttpWebRequest request = null; try { var resp = _connFactory.GetResponse(_source, "GET", "", out request); var buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame IMp3FrameDecompressor decompressor = null; using (var responseStream = resp.GetResponseStream()) { var readFullyStream = new ReadFullyStream(responseStream); while (!_abort.WaitOne(20) && !MainForm.ShuttingDown) { if (_bufferedWaveProvider != null && _bufferedWaveProvider.BufferLength - _bufferedWaveProvider.BufferedBytes < _bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4) { //Debug.WriteLine("Buffer getting full, taking a break"); Thread.Sleep(100); } else { var da = DataAvailable; if (da != null) { Mp3Frame frame; try { frame = Mp3Frame.LoadFromStream(readFullyStream); } catch (EndOfStreamException) { // reached the end of the MP3 file / stream break; } catch (WebException) { // probably we have aborted download from the GUI thread break; } if (decompressor == null || _bufferedWaveProvider == null) { // don't think these details matter too much - just help ACM select the right codec // however, the buffered provider doesn't know what sample rate it is working at // until we have a frame WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate); RecordingFormat = new WaveFormat(frame.SampleRate, 16, frame.ChannelMode == ChannelMode.Mono ? 1 : 2); decompressor = new AcmMp3FrameDecompressor(waveFormat); _bufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat) { BufferDuration = TimeSpan.FromSeconds(5) }; _sampleChannel = new SampleChannel(_bufferedWaveProvider); _sampleChannel.PreVolumeMeter += SampleChannelPreVolumeMeter; } int decompressed = decompressor.DecompressFrame(frame, buffer, 0); _bufferedWaveProvider.AddSamples(buffer, 0, decompressed); var sampleBuffer = new float[buffer.Length]; int read = _sampleChannel.Read(sampleBuffer, 0, buffer.Length); da(this, new DataAvailableEventArgs((byte[])buffer.Clone(), read)); if (Listening) { WaveOutProvider?.AddSamples(buffer, 0, read); } } } } // was doing this in a finally block, but for some reason // we are hanging on response stream .Dispose so never get there if (decompressor != null) { decompressor.Dispose(); decompressor = null; } } } catch (Exception ex) { _res = ReasonToFinishPlaying.DeviceLost; Logger.LogException(ex, "MP3Stream"); } try { request?.Abort(); } catch { } request = null; AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); _abort.Close(); }
private void ReadFrames() { var pConvertedFrameBuffer = IntPtr.Zero; SwsContext *pConvertContext = null; var audioInited = false; var videoInited = false; byte[] buffer = null, tbuffer = null; var dstData = new byte_ptrArray4(); var dstLinesize = new int_array4(); BufferedWaveProvider waveProvider = null; SampleChannel sampleChannel = null; var packet = new AVPacket(); do { ffmpeg.av_init_packet(&packet); if (_audioCodecContext != null && buffer == null) { buffer = new byte[_audioCodecContext->sample_rate * 2]; tbuffer = new byte[_audioCodecContext->sample_rate * 2]; } if (Log("AV_READ_FRAME", ffmpeg.av_read_frame(_formatContext, &packet))) { break; } if ((packet.flags & ffmpeg.AV_PKT_FLAG_CORRUPT) == ffmpeg.AV_PKT_FLAG_CORRUPT) { break; } var nf = NewFrame; var da = DataAvailable; _lastPacket = DateTime.UtcNow; int ret; if (_audioStream != null && packet.stream_index == _audioStream->index && _audioCodecContext != null) { if (HasAudioStream != null) { HasAudioStream?.Invoke(this, EventArgs.Empty); HasAudioStream = null; } if (da != null) { var s = 0; fixed(byte **outPtrs = new byte *[32]) { fixed(byte *bPtr = &tbuffer[0]) { outPtrs[0] = bPtr; ffmpeg.avcodec_send_packet(_audioCodecContext, &packet); do { ret = ffmpeg.avcodec_receive_frame(_audioCodecContext, _audioFrame); if (ret == 0) { var dat = _audioFrame->data[0]; var numSamplesOut = ffmpeg.swr_convert(_swrContext, outPtrs, _audioCodecContext->sample_rate, &dat, _audioFrame->nb_samples); var l = numSamplesOut * 2 * _audioCodecContext->channels; Buffer.BlockCopy(tbuffer, 0, buffer, s, l); s += l; } if (_audioFrame->decode_error_flags > 0) { break; } } while (ret == 0); if (s > 0) { var ba = new byte[s]; Buffer.BlockCopy(buffer, 0, ba, 0, s); if (!audioInited) { audioInited = true; RecordingFormat = new WaveFormat(_audioCodecContext->sample_rate, 16, _audioCodecContext->channels); waveProvider = new BufferedWaveProvider(RecordingFormat) { DiscardOnBufferOverflow = true, BufferDuration = TimeSpan.FromMilliseconds(500) }; sampleChannel = new SampleChannel(waveProvider); sampleChannel.PreVolumeMeter += SampleChannelPreVolumeMeter; } waveProvider.AddSamples(ba, 0, s); var sampleBuffer = new float[s]; var read = sampleChannel.Read(sampleBuffer, 0, s); da(this, new DataAvailableEventArgs(ba, read)); if (Listening) { WaveOutProvider?.AddSamples(ba, 0, read); } } } } } } if (nf != null && _videoStream != null && packet.stream_index == _videoStream->index && _videoCodecContext != null) { ffmpeg.avcodec_send_packet(_videoCodecContext, &packet); do { ret = ffmpeg.avcodec_receive_frame(_videoCodecContext, _videoFrame); if (ret == 0 && EmitFrame) { if (!videoInited) { videoInited = true; var convertedFrameBufferSize = ffmpeg.av_image_get_buffer_size(AVPixelFormat.AV_PIX_FMT_BGR24, _videoCodecContext->width, _videoCodecContext->height, 1); pConvertedFrameBuffer = Marshal.AllocHGlobal(convertedFrameBufferSize); ffmpeg.av_image_fill_arrays(ref dstData, ref dstLinesize, (byte *)pConvertedFrameBuffer, AVPixelFormat.AV_PIX_FMT_BGR24, _videoCodecContext->width, _videoCodecContext->height, 1); pConvertContext = ffmpeg.sws_getContext(_videoCodecContext->width, _videoCodecContext->height, _videoCodecContext->pix_fmt, _videoCodecContext->width, _videoCodecContext->height, AVPixelFormat.AV_PIX_FMT_BGR24, ffmpeg.SWS_FAST_BILINEAR, null, null, null); } Log("SWS_SCALE", ffmpeg.sws_scale(pConvertContext, _videoFrame->data, _videoFrame->linesize, 0, _videoCodecContext->height, dstData, dstLinesize)); if (_videoFrame->decode_error_flags > 0) { break; } using ( var mat = new Bitmap(_videoCodecContext->width, _videoCodecContext->height, dstLinesize[0], PixelFormat.Format24bppRgb, pConvertedFrameBuffer)) { var nfe = new NewFrameEventArgs(mat); nf.Invoke(this, nfe); } _lastVideoFrame = DateTime.UtcNow; } } while (ret == 0); } if (nf != null && _videoStream != null) { if ((DateTime.UtcNow - _lastVideoFrame).TotalMilliseconds > _timeout) { _res = ReasonToFinishPlaying.DeviceLost; _abort = true; } } ffmpeg.av_packet_unref(&packet); } while (!_abort && !MainForm.ShuttingDown); NewFrame?.Invoke(this, new NewFrameEventArgs(null)); try { Program.MutexHelper.Wait(); if (pConvertedFrameBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(pConvertedFrameBuffer); } if (_formatContext != null) { if (_formatContext->streams != null) { var j = (int)_formatContext->nb_streams; for (var i = j - 1; i >= 0; i--) { var stream = _formatContext->streams[i]; if (stream != null && stream->codec != null && stream->codec->codec != null) { stream->discard = AVDiscard.AVDISCARD_ALL; ffmpeg.avcodec_close(stream->codec); } } } fixed(AVFormatContext **f = &_formatContext) { ffmpeg.avformat_close_input(f); } _formatContext = null; } if (_videoFrame != null) { fixed(AVFrame **pinprt = &_videoFrame) { ffmpeg.av_frame_free(pinprt); _videoFrame = null; } } if (_audioFrame != null) { fixed(AVFrame **pinprt = &_audioFrame) { ffmpeg.av_frame_free(pinprt); _audioFrame = null; } } _videoStream = null; _audioStream = null; _audioCodecContext = null; _videoCodecContext = null; if (_swrContext != null) { fixed(SwrContext **s = &_swrContext) { ffmpeg.swr_free(s); } _swrContext = null; } if (pConvertContext != null) { ffmpeg.sws_freeContext(pConvertContext); } if (sampleChannel != null) { sampleChannel.PreVolumeMeter -= SampleChannelPreVolumeMeter; sampleChannel = null; } } catch (Exception ex) { Logger.LogException(ex, "Media Stream (close)"); } finally { try { Program.MutexHelper.Release(); } catch { } } PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); }
private void DirectStreamListener() { _abort = new ManualResetEvent(false); try { var data = new byte[PacketSize]; if (_stream != null) { while (!_abort.WaitOne(0) && !MainForm.ShuttingDown) { var da = DataAvailable; if (da != null) { int recbytesize = _stream.Read(data, 0, PacketSize); if (recbytesize > 0) { if (_sampleChannel != null) { _waveProvider.AddSamples(data, 0, recbytesize); var sampleBuffer = new float[recbytesize]; int read = _sampleChannel.Read(sampleBuffer, 0, recbytesize); da(this, new DataAvailableEventArgs((byte[])data.Clone(), read)); if (Listening) { WaveOutProvider?.AddSamples(data, 0, read); } } } else { break; } } } } } catch (Exception e) { _res = ReasonToFinishPlaying.DeviceLost; Logger.LogException(e, "Direct"); } _stream?.Close(); _stream = null; if (_sampleChannel != null) { _sampleChannel.PreVolumeMeter -= SampleChannelPreVolumeMeter; } if (_waveProvider != null && _waveProvider.BufferedBytes > 0) { _waveProvider.ClearBuffer(); } if (WaveOutProvider?.BufferedBytes > 0) { WaveOutProvider.ClearBuffer(); } AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); _abort.Close(); }
private void ReadFrames() { AVFrame * pConvertedFrame = null; sbyte * pConvertedFrameBuffer = null; SwsContext *pConvertContext = null; BufferedWaveProvider waveProvider = null; SampleChannel sampleChannel = null; bool audioInited = false; bool videoInited = false; var packet = new AVPacket(); do { ffmpeg.av_init_packet(&packet); AVFrame *frame = ffmpeg.av_frame_alloc(); ffmpeg.av_frame_unref(frame); if (ffmpeg.av_read_frame(_formatContext, &packet) < 0) { _stopReadingFrames = true; _res = ReasonToFinishPlaying.VideoSourceError; break; } if ((packet.flags & ffmpeg.AV_PKT_FLAG_CORRUPT) == ffmpeg.AV_PKT_FLAG_CORRUPT) { break; } AVPacket packetTemp = packet; var nf = NewFrame; var da = DataAvailable; _lastPacket = DateTime.UtcNow; if (_audioStream != null && packetTemp.stream_index == _audioStream->index) { if (HasAudioStream != null) { HasAudioStream?.Invoke(this, EventArgs.Empty); HasAudioStream = null; } if (da != null) { int s = 0; var buffer = new sbyte[_audioCodecContext->sample_rate * 2]; var tbuffer = new sbyte[_audioCodecContext->sample_rate * 2]; bool b = false; fixed(sbyte **outPtrs = new sbyte *[32]) { fixed(sbyte *bPtr = &tbuffer[0]) { outPtrs[0] = bPtr; do { int gotFrame = 0; int inUsed = ffmpeg.avcodec_decode_audio4(_audioCodecContext, frame, &gotFrame, &packetTemp); if (inUsed < 0 || gotFrame == 0) { b = true; break; } int numSamplesOut = ffmpeg.swr_convert(_swrContext, outPtrs, _audioCodecContext->sample_rate, &frame->data0, frame->nb_samples); var l = numSamplesOut * 2 * _audioCodecContext->channels; Buffer.BlockCopy(tbuffer, 0, buffer, s, l); s += l; packetTemp.data += inUsed; packetTemp.size -= inUsed; } while (packetTemp.size > 0); } } if (b) { break; } ffmpeg.av_free_packet(&packet); ffmpeg.av_frame_free(&frame); if (!audioInited) { audioInited = true; RecordingFormat = new WaveFormat(_audioCodecContext->sample_rate, 16, _audioCodecContext->channels); waveProvider = new BufferedWaveProvider(RecordingFormat) { DiscardOnBufferOverflow = true, BufferDuration = TimeSpan.FromMilliseconds(500) }; sampleChannel = new SampleChannel(waveProvider); sampleChannel.PreVolumeMeter += SampleChannelPreVolumeMeter; } byte[] ba = new byte[s]; Buffer.BlockCopy(buffer, 0, ba, 0, s); waveProvider.AddSamples(ba, 0, s); var sampleBuffer = new float[s]; int read = sampleChannel.Read(sampleBuffer, 0, s); da(this, new DataAvailableEventArgs(ba, read)); if (Listening) { WaveOutProvider?.AddSamples(ba, 0, read); } } } if (nf != null && _videoStream != null && packet.stream_index == _videoStream->index) { int frameFinished = 0; //decode video frame int ret = ffmpeg.avcodec_decode_video2(_codecContext, frame, &frameFinished, &packetTemp); if (ret < 0) { ffmpeg.av_free_packet(&packet); ffmpeg.av_frame_free(&frame); break; } if (frameFinished == 1) { if (!videoInited) { videoInited = true; pConvertedFrame = ffmpeg.av_frame_alloc(); var convertedFrameBufferSize = ffmpeg.avpicture_get_size(AVPixelFormat.AV_PIX_FMT_BGR24, _codecContext->width, _codecContext->height); pConvertedFrameBuffer = (sbyte *)ffmpeg.av_malloc((ulong)convertedFrameBufferSize); ffmpeg.avpicture_fill((AVPicture *)pConvertedFrame, pConvertedFrameBuffer, AVPixelFormat.AV_PIX_FMT_BGR24, _codecContext->width, _codecContext->height); pConvertContext = ffmpeg.sws_getContext(_codecContext->width, _codecContext->height, _codecContext->pix_fmt, _codecContext->width, _codecContext->height, AVPixelFormat.AV_PIX_FMT_BGR24, ffmpeg.SWS_FAST_BILINEAR, null, null, null); } var src = &frame->data0; var dst = &pConvertedFrame->data0; var srcStride = frame->linesize; var dstStride = pConvertedFrame->linesize; ffmpeg.sws_scale(pConvertContext, src, srcStride, 0, _codecContext->height, dst, dstStride); var convertedFrameAddress = pConvertedFrame->data0; if (convertedFrameAddress != null) { var imageBufferPtr = new IntPtr(convertedFrameAddress); var linesize = dstStride[0]; if (frame->decode_error_flags > 0) { ffmpeg.av_free_packet(&packet); ffmpeg.av_frame_free(&frame); break; } using ( var mat = new Bitmap(_codecContext->width, _codecContext->height, linesize, PixelFormat.Format24bppRgb, imageBufferPtr)) { var nfe = new NewFrameEventArgs((Bitmap)mat.Clone()); nf.Invoke(this, nfe); } _lastVideoFrame = DateTime.UtcNow; } } } if (_videoStream != null) { if ((DateTime.UtcNow - _lastVideoFrame).TotalMilliseconds > _timeout) { _res = ReasonToFinishPlaying.DeviceLost; _stopReadingFrames = true; } } ffmpeg.av_free_packet(&packet); ffmpeg.av_frame_free(&frame); } while (!_stopReadingFrames && !MainForm.ShuttingDown); try { Program.FfmpegMutex.WaitOne(); if (pConvertedFrame != null) { ffmpeg.av_free(pConvertedFrame); } if (pConvertedFrameBuffer != null) { ffmpeg.av_free(pConvertedFrameBuffer); } if (_formatContext != null) { if (_formatContext->streams != null) { int j = (int)_formatContext->nb_streams; for (var i = j - 1; i >= 0; i--) { AVStream *stream = _formatContext->streams[i]; if (stream != null && stream->codec != null && stream->codec->codec != null) { stream->discard = AVDiscard.AVDISCARD_ALL; ffmpeg.avcodec_close(stream->codec); } } } fixed(AVFormatContext **f = &_formatContext) { ffmpeg.avformat_close_input(f); } _formatContext = null; } _videoStream = null; _audioStream = null; _audioCodecContext = null; _codecContext = null; if (_swrContext != null) { fixed(SwrContext **s = &_swrContext) { ffmpeg.swr_free(s); } _swrContext = null; } if (pConvertContext != null) { ffmpeg.sws_freeContext(pConvertContext); } if (sampleChannel != null) { sampleChannel.PreVolumeMeter -= SampleChannelPreVolumeMeter; sampleChannel = null; } } catch (Exception ex) { Logger.LogException(ex, "Media Stream (close)"); } finally { try { Program.FfmpegMutex.ReleaseMutex(); } catch { } } PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); }
void WaveInRecordingStopped(object sender, EventArgs e) { _isrunning = false; AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser)); }
private void SpyServerListener() { var data = new byte[3200]; try { var request = (HttpWebRequest)WebRequest.Create(_source); request.Timeout = 10000; request.ReadWriteTimeout = 5000; var response = request.GetResponse(); using (Stream stream = response.GetResponseStream()) { if (stream == null) { throw new Exception("Stream is null"); } stream.ReadTimeout = 5000; while (!_stopEvent.WaitOne(0, false)) { int recbytesize = stream.Read(data, 0, 3200); if (recbytesize == 0) { throw new Exception("lost stream"); } byte[] dec; ALawDecoder.ALawDecode(data, recbytesize, out dec); var da = DataAvailable; if (da != null) { if (_sampleChannel != null) { _waveProvider.AddSamples(dec, 0, dec.Length); var sampleBuffer = new float[dec.Length]; int read = _sampleChannel.Read(sampleBuffer, 0, dec.Length); da(this, new DataAvailableEventArgs((byte[])dec.Clone(), read)); if (Listening) { WaveOutProvider?.AddSamples(dec, 0, read); } } } else { break; } // need to stop ? if (_stopEvent.WaitOne(0, false)) { break; } } } AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser)); } catch (Exception e) { var af = AudioFinished; af?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.DeviceLost)); //Logger.LogExceptionToFile(e,"ispyServer"); } if (_sampleChannel != null) { _sampleChannel.PreVolumeMeter -= SampleChannelPreVolumeMeter; _sampleChannel = null; } if (_waveProvider?.BufferedBytes > 0) { _waveProvider.ClearBuffer(); } if (WaveOutProvider?.BufferedBytes > 0) { WaveOutProvider?.ClearBuffer(); } }
private void WebStreamListener() { try { var data = new byte[6400]; if (_socket != null) { while (!_abort.WaitOne(20) && !MainForm.ShuttingDown) { var da = DataAvailable; if (da != null) { int recbytesize = _socket.Receive(data, 0, 6400, SocketFlags.None); if (_sampleChannel != null) { _waveProvider.AddSamples(data, 0, recbytesize); var sampleBuffer = new float[recbytesize]; int read = _sampleChannel.Read(sampleBuffer, 0, recbytesize); da(this, new DataAvailableEventArgs((byte[])data.Clone(), read)); if (Listening) { WaveOutProvider?.AddSamples(data, 0, read); } } } else { break; } } } } catch (Exception e) { _res = ReasonToFinishPlaying.DeviceLost; Logger.LogException(e, "WebStream"); } if (_socket != null) { _socket.Close(); _socket = null; } if (_sampleChannel != null) { _sampleChannel.PreVolumeMeter -= SampleChannelPreVolumeMeter; } if (_waveProvider != null && _waveProvider.BufferedBytes > 0) { _waveProvider.ClearBuffer(); } if (WaveOutProvider?.BufferedBytes > 0) { WaveOutProvider.ClearBuffer(); } AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); }
private void WorkerThread() { bool file = false; if (string.IsNullOrEmpty(Source)) { Logger.LogError("Source not found", "VLC"); _res = ReasonToFinishPlaying.VideoSourceError; PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); return; } try { if (File.Exists(Source)) { file = true; } } catch { // ignored } if (_mFactory == null) { var args = new List <string> { "-I", "dumy", "--ignore-config", "--no-osd", "--disable-screensaver", "--plugin-path=./plugins" }; if (file) { args.Add("--file-caching=3000"); } try { var l2 = args.ToList(); l2.AddRange(_arguments); l2 = l2.Distinct().ToList(); _mFactory = new MediaPlayerFactory(l2.ToArray()); } catch (Exception ex) { Logger.LogException(ex, "VLC Stream"); Logger.LogMessage("VLC arguments are: " + string.Join(",", args.ToArray()), "VLC Stream"); Logger.LogMessage("Using default VLC configuration.", "VLC Stream"); return; } GC.KeepAlive(_mFactory); } var vss = Source; if (!_modeAudio) { vss = Tokenise(vss); } _mMedia = file ? _mFactory.CreateMedia <IMediaFromFile>(vss) : _mFactory.CreateMedia <IMedia>(vss); _mMedia.Events.DurationChanged += EventsDurationChanged; _mMedia.Events.StateChanged += EventsStateChanged; if (_mPlayer != null) { try { _mPlayer?.Dispose(); } catch { // ignored } _mPlayer = null; } _mPlayer = _mFactory.CreatePlayer <IVideoPlayer>(); _mPlayer.Events.TimeChanged += EventsTimeChanged; var fc = new Func <SoundFormat, SoundFormat>(SoundFormatCallback); _mPlayer.CustomAudioRenderer.SetFormatCallback(fc); var ac = new AudioCallbacks { SoundCallback = SoundCallback }; _mPlayer.CustomAudioRenderer.SetCallbacks(ac); _mPlayer.CustomAudioRenderer.SetExceptionHandler(Handler); if (!_modeAudio) { _mPlayer.CustomRenderer.SetCallback(FrameCallback); _mPlayer.CustomRenderer.SetExceptionHandler(Handler); } GC.KeepAlive(_mPlayer); _needsSetup = true; if (!_modeAudio) { _mPlayer.CustomRenderer.SetFormat(new BitmapFormat(_source.settings.vlcWidth, _source.settings.vlcHeight, ChromaType.RV32)); } _mPlayer.Open(_mMedia); _mMedia.Parse(true); _mPlayer.Delay = 0; Duration = Time = 0; LastFrame = DateTime.MinValue; //check if file source (isseekable in _mPlayer is not reliable) Seekable = false; try { var p = Path.GetFullPath(_mMedia.Input); Seekable = !string.IsNullOrEmpty(p); } catch (Exception) { Seekable = false; } _videoQueue = new ConcurrentQueue <Bitmap>(); _audioQueue = new ConcurrentQueue <byte[]>(); _mPlayer.Play(); _abort = new ManualResetEvent(false); EventManager(); if (Seekable) { PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser)); } else { PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); } DisposePlayer(); _abort.Close(); }
private void DoStart() { var vss = Source; if (!_modeAudio) { vss = Tokenise(vss); } AVDictionary *options = null; if (_inputFormat == null) { ffmpeg.av_dict_set(&options, "analyzeduration", _analyzeDuration.ToString(), 0); string prefix = vss.ToLower().Substring(0, vss.IndexOf(":", StringComparison.Ordinal)); switch (prefix) { case "http": case "mmsh": case "mms": ffmpeg.av_dict_set(&options, "timeout", _timeout.ToString(), 0); ffmpeg.av_dict_set(&options, "stimeout", (_timeout * 1000).ToString(), 0); if (_cookies != "") { ffmpeg.av_dict_set(&options, "cookies", _cookies, 0); } if (_headers != "") { ffmpeg.av_dict_set(&options, "headers", _headers, 0); } if (_userAgent != "") { ffmpeg.av_dict_set(&options, "user-agent", _userAgent, 0); } break; case "tcp": case "udp": case "rtp": case "sdp": case "mmst": case "ftp": ffmpeg.av_dict_set(&options, "timeout", _timeout.ToString(), 0); break; case "rtsp": case "rtmp": ffmpeg.av_dict_set(&options, "stimeout", (_timeout * 1000).ToString(), 0); if (_userAgent != "") { ffmpeg.av_dict_set(&options, "user-agent", _userAgent, 0); } break; } ffmpeg.av_dict_set(&options, "rtsp_transport", RTSPmode, 0); } ffmpeg.av_dict_set(&options, "rtbufsize", "10000000", 0); var lo = _options.Split(Environment.NewLine.ToCharArray()); foreach (var nv in lo) { if (!string.IsNullOrEmpty(nv)) { var i = nv.IndexOf('='); if (i > -1) { var n = nv.Substring(0, i).Trim(); var v = nv.Substring(i + 1).Trim(); if (!string.IsNullOrEmpty(n) && !string.IsNullOrEmpty(v)) { int j; if (int.TryParse(v, out j)) { ffmpeg.av_dict_set_int(&options, n, j, 0); } else { ffmpeg.av_dict_set(&options, n, v, 0); } } } } } _stopReadingFrames = false; try { Program.FfmpegMutex.WaitOne(); var pFormatContext = ffmpeg.avformat_alloc_context(); _lastPacket = DateTime.UtcNow; _interruptCallback = InterruptCb; _interruptCallbackAddress = Marshal.GetFunctionPointerForDelegate(_interruptCallback); pFormatContext->interrupt_callback.callback = _interruptCallbackAddress; pFormatContext->interrupt_callback.opaque = null; if (ffmpeg.avformat_open_input(&pFormatContext, vss, _inputFormat, &options) != 0) { throw new ApplicationException(@"Could not open source"); } _formatContext = pFormatContext; SetupFormat(); } catch (Exception ex) { ErrorHandler?.Invoke(ex.Message); _res = ReasonToFinishPlaying.VideoSourceError; PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); } finally { try { Program.FfmpegMutex.ReleaseMutex(); } catch { } } _starting = false; }
private void StreamWav() { var res = ReasonToFinishPlaying.StoppedByUser; HttpWebRequest request = null; try { using (HttpWebResponse resp = ConnectionFactory.GetResponse(_source, false, out request)) { //1/4 of a second, 16 byte buffer var data = new byte[((RecordingFormat.SampleRate / 4) * 2) * RecordingFormat.Channels]; using (var stream = resp.GetResponseStream()) { if (stream == null) { throw new Exception("Stream is null"); } while (!_stopEvent.WaitOne(10, false) && !MainForm.ShuttingDown) { var da = DataAvailable; if (da != null) { int recbytesize = stream.Read(data, 0, data.Length); if (recbytesize == 0) { throw new Exception("lost stream"); } if (_sampleChannel == null) { continue; } _waveProvider.AddSamples(data, 0, recbytesize); var sampleBuffer = new float[recbytesize]; int read = _sampleChannel.Read(sampleBuffer, 0, recbytesize); da(this, new DataAvailableEventArgs((byte[])data.Clone(), read)); if (Listening) { WaveOutProvider?.AddSamples(data, 0, read); } } else { break; } } } } } catch (Exception ex) { res = ReasonToFinishPlaying.DeviceLost; MainForm.LogExceptionToFile(ex, "WavStream"); } finally { AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(res)); } }
private void WorkerThread() { bool file = false; try { if (File.Exists(_source)) { file = true; } } catch { // ignored } if (_mFactory == null) { var args = new List <string> { "-I", "dumy", "--ignore-config", "--no-osd", "--disable-screensaver", "--plugin-path=./plugins" }; if (file) { args.Add("--file-caching=3000"); } try { var l2 = args.ToList(); l2.AddRange(_arguments); l2 = l2.Distinct().ToList(); _mFactory = new MediaPlayerFactory(l2.ToArray()); } catch (Exception ex) { MainForm.LogExceptionToFile(ex, "VLC Stream"); MainForm.LogMessageToFile("VLC arguments are: " + string.Join(",", args.ToArray()), "VLC Stream"); MainForm.LogMessageToFile("Using default VLC configuration.", "VLC Stream"); _mFactory = new MediaPlayerFactory(args.ToArray()); } GC.KeepAlive(_mFactory); } _mMedia = file ? _mFactory.CreateMedia <IMediaFromFile>(_source) : _mFactory.CreateMedia <IMedia>(_source); _mMedia.Events.DurationChanged += EventsDurationChanged; _mMedia.Events.StateChanged += EventsStateChanged; if (_mPlayer != null) { try { _mPlayer?.Dispose(); } catch { // ignored } _mPlayer = null; } _mPlayer = _mFactory.CreatePlayer <IVideoPlayer>(); _mPlayer.Events.TimeChanged += EventsTimeChanged; var fc = new Func <SoundFormat, SoundFormat>(SoundFormatCallback); _mPlayer.CustomAudioRenderer.SetFormatCallback(fc); var ac = new AudioCallbacks { SoundCallback = SoundCallback }; _mPlayer.CustomAudioRenderer.SetCallbacks(ac); _mPlayer.CustomAudioRenderer.SetExceptionHandler(Handler); _mPlayer.CustomRenderer.SetCallback(FrameCallback); _mPlayer.CustomRenderer.SetExceptionHandler(Handler); GC.KeepAlive(_mPlayer); _needsSetup = true; _stopping = false; _mPlayer.CustomRenderer.SetFormat(new BitmapFormat(FormatWidth, FormatHeight, ChromaType.RV24)); _mPlayer.Open(_mMedia); _mMedia.Parse(true); _mPlayer.Delay = 0; _framesReceived = 0; Duration = Time = 0; LastFrame = DateTime.MinValue; //check if file source (isseekable in _mPlayer is not reliable) Seekable = false; try { var p = Path.GetFullPath(_mMedia.Input); Seekable = !string.IsNullOrEmpty(p); } catch (Exception) { Seekable = false; } _mPlayer.WindowHandle = IntPtr.Zero; _videoQueue = new ConcurrentQueue <Bitmap>(); _audioQueue = new ConcurrentQueue <byte[]>(); _eventing = new Thread(EventManager) { Name = "vlc eventing", IsBackground = true }; _eventing.Start(); _mPlayer.Play(); _stopEvent.WaitOne(); if (_eventing != null && !_eventing.Join(0)) { _eventing.Join(); } if (!Seekable && !_stopRequested) { PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.DeviceLost)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.DeviceLost)); } else { PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(ReasonToFinishPlaying.StoppedByUser)); } DisposePlayer(); _stopEvent?.Close(); _stopEvent = null; }
private void DoStart() { var vss = Source; if (!IsAudio) { vss = Tokenise(vss); } AVDictionary *options = null; if (_inputFormat == null) { var prefix = vss.ToLower().Substring(0, vss.IndexOf(":", StringComparison.Ordinal)); switch (prefix) { case "https": case "http": case "mmsh": case "mms": ffmpeg.av_dict_set_int(&options, "timeout", _timeout, 0); ffmpeg.av_dict_set_int(&options, "stimeout", _timeout * 1000, 0); if (_cookies != "") { ffmpeg.av_dict_set(&options, "cookies", _cookies, 0); } if (_headers != "") { ffmpeg.av_dict_set(&options, "headers", _headers, 0); } if (_userAgent != "") { ffmpeg.av_dict_set(&options, "user-agent", _userAgent, 0); } break; default: ffmpeg.av_dict_set_int(&options, "timeout", _timeout, 0); break; case "rtsp": case "rtmp": ffmpeg.av_dict_set_int(&options, "stimeout", _timeout * 1000, 0); if (_userAgent != "") { ffmpeg.av_dict_set(&options, "user-agent", _userAgent, 0); } break; } ffmpeg.av_dict_set(&options, "rtsp_transport", _modeRTSP, 0); } ffmpeg.av_dict_set_int(&options, "rtbufsize", 10000000, 0); var lo = _options.Split(Environment.NewLine.ToCharArray()); foreach (var nv in lo) { if (!string.IsNullOrEmpty(nv)) { var i = nv.IndexOf('='); if (i > -1) { var n = nv.Substring(0, i).Trim(); var v = nv.Substring(i + 1).Trim(); if (!string.IsNullOrEmpty(n) && !string.IsNullOrEmpty(v)) { int j; if (int.TryParse(v, out j)) { ffmpeg.av_dict_set_int(&options, n, j, 0); } else { ffmpeg.av_dict_set(&options, n, v, 0); } } } } } _abort = false; try { Program.MutexHelper.Wait(); var pFormatContext = ffmpeg.avformat_alloc_context(); _lastPacket = DateTime.UtcNow; _interruptCallback = InterruptCb; _interruptCallbackAddress = Marshal.GetFunctionPointerForDelegate(_interruptCallback); _aviocb = new AVIOInterruptCB_callback_func { Pointer = _interruptCallbackAddress }; pFormatContext->interrupt_callback.callback = _aviocb; pFormatContext->interrupt_callback.opaque = null; pFormatContext->max_analyze_duration = 0; Throw("OPEN_INPUT", ffmpeg.avformat_open_input(&pFormatContext, vss, _inputFormat, &options)); _formatContext = pFormatContext; SetupFormat(); } catch (Exception ex) { ErrorHandler?.Invoke(ex.Message); _res = ReasonToFinishPlaying.VideoSourceError; PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); } finally { try { Program.MutexHelper.Release(); } catch { } } _starting = false; }