MulticastStream.cs 2.7 KB

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