DirectRecorder.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using CommonIO;
  6. using MediaBrowser.Common.IO;
  7. using MediaBrowser.Common.Net;
  8. using MediaBrowser.Model.Dto;
  9. using MediaBrowser.Model.Logging;
  10. namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
  11. {
  12. public class DirectRecorder : IRecorder
  13. {
  14. private readonly ILogger _logger;
  15. private readonly IHttpClient _httpClient;
  16. private readonly IFileSystem _fileSystem;
  17. public DirectRecorder(ILogger logger, IHttpClient httpClient, IFileSystem fileSystem)
  18. {
  19. _logger = logger;
  20. _httpClient = httpClient;
  21. _fileSystem = fileSystem;
  22. }
  23. public async Task Record(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  24. {
  25. var httpRequestOptions = new HttpRequestOptions()
  26. {
  27. Url = mediaSource.Path
  28. };
  29. httpRequestOptions.BufferContent = false;
  30. using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false))
  31. {
  32. _logger.Info("Opened recording stream from tuner provider");
  33. using (var output = _fileSystem.GetFileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.Read))
  34. {
  35. onStarted();
  36. _logger.Info("Copying recording stream to file {0}", targetFile);
  37. if (mediaSource.RunTimeTicks.HasValue)
  38. {
  39. // The media source already has a fixed duration
  40. // But add another stop 1 minute later just in case the recording gets stuck for any reason
  41. var durationToken = new CancellationTokenSource(duration.Add(TimeSpan.FromMinutes(1)));
  42. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  43. }
  44. else
  45. {
  46. // The media source if infinite so we need to handle stopping ourselves
  47. var durationToken = new CancellationTokenSource(duration);
  48. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  49. }
  50. await response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  51. }
  52. }
  53. _logger.Info("Recording completed to file {0}", targetFile);
  54. }
  55. }
  56. }