MulticastStream.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Model.Logging;
  10. namespace Emby.Server.Implementations.LiveTv.TunerHosts
  11. {
  12. public class MulticastStream
  13. {
  14. private readonly ConcurrentDictionary<Guid,QueueStream> _outputStreams = new ConcurrentDictionary<Guid, QueueStream>();
  15. private const int BufferSize = 81920;
  16. private CancellationToken _cancellationToken;
  17. private readonly ILogger _logger;
  18. public MulticastStream(ILogger logger)
  19. {
  20. _logger = logger;
  21. }
  22. public async Task CopyUntilCancelled(Stream source, Action onStarted, CancellationToken cancellationToken)
  23. {
  24. _cancellationToken = cancellationToken;
  25. byte[] buffer = new byte[BufferSize];
  26. while (!cancellationToken.IsCancellationRequested)
  27. {
  28. var bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
  29. if (bytesRead > 0)
  30. {
  31. byte[] copy = new byte[bytesRead];
  32. Buffer.BlockCopy(buffer, 0, copy, 0, bytesRead);
  33. var allStreams = _outputStreams.ToList();
  34. foreach (var stream in allStreams)
  35. {
  36. stream.Value.Queue(copy);
  37. }
  38. if (onStarted != null)
  39. {
  40. var onStartedCopy = onStarted;
  41. onStarted = null;
  42. Task.Run(onStartedCopy);
  43. }
  44. }
  45. else
  46. {
  47. await Task.Delay(100).ConfigureAwait(false);
  48. }
  49. }
  50. }
  51. public Task CopyToAsync(Stream stream)
  52. {
  53. var result = new QueueStream(stream, _logger)
  54. {
  55. OnFinished = OnFinished
  56. };
  57. _outputStreams.TryAdd(result.Id, result);
  58. result.Start(_cancellationToken);
  59. return result.TaskCompletion.Task;
  60. }
  61. public void RemoveOutputStream(QueueStream stream)
  62. {
  63. QueueStream removed;
  64. _outputStreams.TryRemove(stream.Id, out removed);
  65. }
  66. private void OnFinished(QueueStream queueStream)
  67. {
  68. RemoveOutputStream(queueStream);
  69. }
  70. }
  71. }