MulticastStream.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. private readonly ConcurrentQueue<byte[]> _sharedBuffer = new ConcurrentQueue<byte[]>();
  19. public MulticastStream(ILogger logger)
  20. {
  21. _logger = logger;
  22. }
  23. public async Task CopyUntilCancelled(Stream source, Action onStarted, CancellationToken cancellationToken)
  24. {
  25. _cancellationToken = cancellationToken;
  26. byte[] buffer = new byte[BufferSize];
  27. while (!cancellationToken.IsCancellationRequested)
  28. {
  29. var bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
  30. if (bytesRead > 0)
  31. {
  32. byte[] copy = new byte[bytesRead];
  33. Buffer.BlockCopy(buffer, 0, copy, 0, bytesRead);
  34. _sharedBuffer.Enqueue(copy);
  35. while (_sharedBuffer.Count > 3000)
  36. {
  37. byte[] bytes;
  38. _sharedBuffer.TryDequeue(out bytes);
  39. }
  40. var allStreams = _outputStreams.ToList();
  41. foreach (var stream in allStreams)
  42. {
  43. stream.Value.Queue(copy);
  44. }
  45. if (onStarted != null)
  46. {
  47. var onStartedCopy = onStarted;
  48. onStarted = null;
  49. Task.Run(onStartedCopy);
  50. }
  51. }
  52. else
  53. {
  54. await Task.Delay(100).ConfigureAwait(false);
  55. }
  56. }
  57. }
  58. public Task CopyToAsync(Stream stream)
  59. {
  60. var result = new QueueStream(stream, _logger)
  61. {
  62. OnFinished = OnFinished
  63. };
  64. var list = new List<byte>();
  65. foreach (var bytes in _sharedBuffer)
  66. {
  67. list.AddRange(bytes);
  68. }
  69. _logger.Info("QueueStream started with {0} initial bytes", list.Count);
  70. result.Queue(list.ToArray());
  71. _outputStreams.TryAdd(result.Id, result);
  72. result.Start(_cancellationToken);
  73. return result.TaskCompletion.Task;
  74. }
  75. public void RemoveOutputStream(QueueStream stream)
  76. {
  77. QueueStream removed;
  78. _outputStreams.TryRemove(stream.Id, out removed);
  79. }
  80. private void OnFinished(QueueStream queueStream)
  81. {
  82. RemoveOutputStream(queueStream);
  83. }
  84. }
  85. }