MulticastStream.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 (!cancellationToken.IsCancellationRequested)
  30. {
  31. var bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
  32. if (bytesRead > 0)
  33. {
  34. var allStreams = _outputStreams.ToList();
  35. //if (allStreams.Count == 1)
  36. //{
  37. // await allStreams[0].Value.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
  38. //}
  39. //else
  40. {
  41. byte[] copy = new byte[bytesRead];
  42. Buffer.BlockCopy(buffer, 0, copy, 0, bytesRead);
  43. foreach (var stream in allStreams)
  44. {
  45. stream.Value.Queue(copy, 0, copy.Length);
  46. }
  47. }
  48. if (onStarted != null)
  49. {
  50. var onStartedCopy = onStarted;
  51. onStarted = null;
  52. Task.Run(onStartedCopy);
  53. }
  54. }
  55. else
  56. {
  57. await Task.Delay(100).ConfigureAwait(false);
  58. }
  59. }
  60. }
  61. public Task CopyToAsync(Stream stream, CancellationToken cancellationToken)
  62. {
  63. var result = new QueueStream(stream, _logger)
  64. {
  65. OnFinished = OnFinished
  66. };
  67. _outputStreams.TryAdd(result.Id, result);
  68. result.Start(cancellationToken);
  69. return result.TaskCompletion.Task;
  70. }
  71. public void RemoveOutputStream(QueueStream stream)
  72. {
  73. QueueStream removed;
  74. _outputStreams.TryRemove(stream.Id, out removed);
  75. }
  76. private void OnFinished(QueueStream queueStream)
  77. {
  78. RemoveOutputStream(queueStream);
  79. }
  80. }
  81. }