Stream GetBufferingStream(string streamUrl) { var memoryStream = new DualStream(); Task.Run(() => { int byteCounter = 0; try { var webClient = new WebClient(); var networkStream = webClient.OpenRead(streamUrl); if (networkStream == null) { return; } byte[] buffer = new byte[0x1000]; while (true) { int read = networkStream.Read(buffer, 0, buffer.Length); if (read <= 0) { break; } byteCounter += read; totalSourceBytes += read; memoryStream.Write(buffer, 0, read); } } catch (Exception ex) { Console.WriteLine("Exception while reading network stream: " + ex); } NetworkDone = true; Console.WriteLine("net: done. ({0} read)", byteCounter); }); return(memoryStream); }
public void Start() { Task.Run(async() => { // Wait for some data to arrive while (true) { if (streamRequest.NetworkDone) { break; } if (bufferingStream.Length > 1024 * 3) { break; } await Task.Delay(100); } Stream input, pcmOutput; var ffmpegProcess = GetTranscoderStreams(out input, out pcmOutput); PCMOutput = new DualStream(); // Keep pumping network stuff into the transcoder transcoderTask = Task.Run(() => TranscoderFunc(bufferingStream, input, tokenSource.Token), tokenSource.Token); // Keep pumping transcoder output into the PCMOutput stream outputTask = Task.Run(() => OutputFunc(pcmOutput, PCMOutput, tokenSource.Token), tokenSource.Token); // Wait until network stuff is all done while (!streamRequest.NetworkDone) { await Task.Delay(200); } // Then wait until we sent everything to the transcoder while (BytesSentToTranscoder < streamRequest.TotalSourceBytes) { await Task.Delay(200); } // Then wait some more until it did everything and kill it await Task.Delay(5000); try { tokenSource.Cancel(); bufferingStream.Close(); Console.WriteLine("Killing transcoder..."); ffmpegProcess.Kill(); } catch { } }); }
static async Task OutputFunc(Stream sourceStream, DualStream targetBuffer, CancellationToken cancellationToken) { try { byte[] buffer = new byte[1024]; while (!cancellationToken.IsCancellationRequested) { // When there is new stuff available on the network we want to get it instantly int read = await sourceStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken); if (read > 0) { targetBuffer.Write(buffer, 0, read); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.WriteLine("OutputFunc stopped"); }
Stream GetBufferingStream(string streamUrl) { var memoryStream = new DualStream(); Task.Run(() => { int byteCounter = 0; try { var webClient = new WebClient(); var networkStream = webClient.OpenRead(streamUrl); if (networkStream == null) return; byte[] buffer = new byte[0x1000]; while (true) { int read = networkStream.Read(buffer, 0, buffer.Length); if (read <= 0) break; byteCounter += read; totalSourceBytes += read; memoryStream.Write(buffer, 0, read); } } catch (Exception ex) { Console.WriteLine("Exception while reading network stream: " + ex); } NetworkDone = true; Console.WriteLine("net: done. ({0} read)", byteCounter); }); return memoryStream; }