MulticastStream.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. using MediaBrowser.Model.Net;
  11. namespace Emby.Server.Implementations.LiveTv.TunerHosts
  12. {
  13. public class MulticastStream
  14. {
  15. private readonly ConcurrentDictionary<Guid, QueueStream> _outputStreams = new ConcurrentDictionary<Guid, QueueStream>();
  16. private const int BufferSize = 81920;
  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. byte[] buffer = new byte[BufferSize];
  25. if (source == null)
  26. {
  27. throw new ArgumentNullException("source");
  28. }
  29. while (true)
  30. {
  31. cancellationToken.ThrowIfCancellationRequested();
  32. var bytesRead = source.Read(buffer, 0, buffer.Length);
  33. if (bytesRead > 0)
  34. {
  35. var allStreams = _outputStreams.ToList();
  36. //if (allStreams.Count == 1)
  37. //{
  38. // allStreams[0].Value.Write(buffer, 0, bytesRead);
  39. //}
  40. //else
  41. {
  42. byte[] copy = new byte[bytesRead];
  43. Buffer.BlockCopy(buffer, 0, copy, 0, bytesRead);
  44. foreach (var stream in allStreams)
  45. {
  46. stream.Value.Queue(copy, 0, copy.Length);
  47. }
  48. }
  49. if (onStarted != null)
  50. {
  51. var onStartedCopy = onStarted;
  52. onStarted = null;
  53. Task.Run(onStartedCopy);
  54. }
  55. }
  56. else
  57. {
  58. await Task.Delay(100).ConfigureAwait(false);
  59. }
  60. }
  61. }
  62. public Task CopyToAsync(Stream stream, CancellationToken cancellationToken)
  63. {
  64. var result = new QueueStream(stream, _logger)
  65. {
  66. OnFinished = OnFinished
  67. };
  68. _outputStreams.TryAdd(result.Id, result);
  69. result.Start(cancellationToken);
  70. return result.TaskCompletion.Task;
  71. }
  72. public void RemoveOutputStream(QueueStream stream)
  73. {
  74. QueueStream removed;
  75. _outputStreams.TryRemove(stream.Id, out removed);
  76. }
  77. private void OnFinished(QueueStream queueStream)
  78. {
  79. RemoveOutputStream(queueStream);
  80. }
  81. }
  82. }