LiveStream.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MediaBrowser.Model.Dto;
  7. using MediaBrowser.Model.IO;
  8. using MediaBrowser.Model.System;
  9. namespace MediaBrowser.Controller.LiveTv
  10. {
  11. public class LiveStream
  12. {
  13. public MediaSourceInfo OriginalMediaSource { get; set; }
  14. public MediaSourceInfo OpenedMediaSource { get; set; }
  15. public int ConsumerCount
  16. {
  17. get { return SharedStreamIds.Count; }
  18. }
  19. public ITunerHost TunerHost { get; set; }
  20. public string OriginalStreamId { get; set; }
  21. public bool EnableStreamSharing { get; set; }
  22. public string UniqueId = Guid.NewGuid().ToString("N");
  23. public List<string> SharedStreamIds = new List<string>();
  24. protected readonly IEnvironmentInfo Environment;
  25. protected readonly IFileSystem FileSystem;
  26. const int StreamCopyToBufferSize = 81920;
  27. public LiveStream(MediaSourceInfo mediaSource, IEnvironmentInfo environment, IFileSystem fileSystem)
  28. {
  29. OriginalMediaSource = mediaSource;
  30. Environment = environment;
  31. FileSystem = fileSystem;
  32. OpenedMediaSource = mediaSource;
  33. EnableStreamSharing = true;
  34. }
  35. public Task Open(CancellationToken cancellationToken)
  36. {
  37. return OpenInternal(cancellationToken);
  38. }
  39. protected virtual Task OpenInternal(CancellationToken cancellationToken)
  40. {
  41. return Task.FromResult(true);
  42. }
  43. public virtual Task Close()
  44. {
  45. return Task.FromResult(true);
  46. }
  47. protected Stream GetInputStream(string path, long startPosition, bool allowAsyncFileRead)
  48. {
  49. var fileOpenOptions = startPosition > 0
  50. ? FileOpenOptions.RandomAccess
  51. : FileOpenOptions.SequentialScan;
  52. if (allowAsyncFileRead)
  53. {
  54. fileOpenOptions |= FileOpenOptions.Asynchronous;
  55. }
  56. return FileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, fileOpenOptions);
  57. }
  58. protected async Task DeleteTempFile(string path, int retryCount = 0)
  59. {
  60. try
  61. {
  62. FileSystem.DeleteFile(path);
  63. return;
  64. }
  65. catch
  66. {
  67. }
  68. if (retryCount > 20)
  69. {
  70. return;
  71. }
  72. await Task.Delay(500).ConfigureAwait(false);
  73. await DeleteTempFile(path, retryCount + 1).ConfigureAwait(false);
  74. }
  75. }
  76. }