2
0

ApiEntryPoint.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Api.Playback;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Controller.Configuration;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.MediaEncoding;
  12. using MediaBrowser.Controller.Net;
  13. using MediaBrowser.Controller.Plugins;
  14. using MediaBrowser.Controller.Session;
  15. using MediaBrowser.Model.Configuration;
  16. using MediaBrowser.Model.Diagnostics;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.Session;
  20. using MediaBrowser.Model.Threading;
  21. using Microsoft.Extensions.Logging;
  22. namespace MediaBrowser.Api
  23. {
  24. /// <summary>
  25. /// Class ServerEntryPoint
  26. /// </summary>
  27. public class ApiEntryPoint : IServerEntryPoint
  28. {
  29. /// <summary>
  30. /// The instance
  31. /// </summary>
  32. public static ApiEntryPoint Instance;
  33. /// <summary>
  34. /// Gets or sets the logger.
  35. /// </summary>
  36. /// <value>The logger.</value>
  37. internal ILogger Logger { get; private set; }
  38. internal IHttpResultFactory ResultFactory { get; private set; }
  39. /// <summary>
  40. /// The application paths
  41. /// </summary>
  42. private readonly IServerConfigurationManager _config;
  43. private readonly ISessionManager _sessionManager;
  44. private readonly IFileSystem _fileSystem;
  45. private readonly IMediaSourceManager _mediaSourceManager;
  46. public readonly ITimerFactory TimerFactory;
  47. public readonly IProcessFactory ProcessFactory;
  48. /// <summary>
  49. /// The active transcoding jobs
  50. /// </summary>
  51. private readonly List<TranscodingJob> _activeTranscodingJobs = new List<TranscodingJob>();
  52. private readonly Dictionary<string, SemaphoreSlim> _transcodingLocks =
  53. new Dictionary<string, SemaphoreSlim>();
  54. /// <summary>
  55. /// Initializes a new instance of the <see cref="ApiEntryPoint" /> class.
  56. /// </summary>
  57. /// <param name="logger">The logger.</param>
  58. /// <param name="sessionManager">The session manager.</param>
  59. /// <param name="config">The configuration.</param>
  60. /// <param name="fileSystem">The file system.</param>
  61. /// <param name="mediaSourceManager">The media source manager.</param>
  62. public ApiEntryPoint(ILogger logger, ISessionManager sessionManager, IServerConfigurationManager config, IFileSystem fileSystem, IMediaSourceManager mediaSourceManager, ITimerFactory timerFactory, IProcessFactory processFactory, IHttpResultFactory resultFactory)
  63. {
  64. Logger = logger;
  65. _sessionManager = sessionManager;
  66. _config = config;
  67. _fileSystem = fileSystem;
  68. _mediaSourceManager = mediaSourceManager;
  69. TimerFactory = timerFactory;
  70. ProcessFactory = processFactory;
  71. ResultFactory = resultFactory;
  72. Instance = this;
  73. _sessionManager.PlaybackProgress += _sessionManager_PlaybackProgress;
  74. _sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
  75. }
  76. public static string[] Split(string value, char separator, bool removeEmpty)
  77. {
  78. if (string.IsNullOrWhiteSpace(value))
  79. {
  80. return Array.Empty<string>();
  81. }
  82. if (removeEmpty)
  83. {
  84. return value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries);
  85. }
  86. return value.Split(separator);
  87. }
  88. public SemaphoreSlim GetTranscodingLock(string outputPath)
  89. {
  90. lock (_transcodingLocks)
  91. {
  92. if (!_transcodingLocks.TryGetValue(outputPath, out SemaphoreSlim result))
  93. {
  94. result = new SemaphoreSlim(1, 1);
  95. _transcodingLocks[outputPath] = result;
  96. }
  97. return result;
  98. }
  99. }
  100. private void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
  101. {
  102. if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
  103. {
  104. PingTranscodingJob(e.PlaySessionId, e.IsPaused);
  105. }
  106. }
  107. void _sessionManager_PlaybackProgress(object sender, PlaybackProgressEventArgs e)
  108. {
  109. if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
  110. {
  111. PingTranscodingJob(e.PlaySessionId, e.IsPaused);
  112. }
  113. }
  114. /// <summary>
  115. /// Runs this instance.
  116. /// </summary>
  117. public void Run()
  118. {
  119. try
  120. {
  121. DeleteEncodedMediaCache();
  122. }
  123. catch (FileNotFoundException)
  124. {
  125. // Don't clutter the log
  126. }
  127. catch (IOException)
  128. {
  129. // Don't clutter the log
  130. }
  131. catch (Exception ex)
  132. {
  133. Logger.LogError(ex, "Error deleting encoded media cache");
  134. }
  135. }
  136. public EncodingOptions GetEncodingOptions()
  137. {
  138. return ConfigurationManagerExtensions.GetConfiguration<EncodingOptions>(_config, "encoding");
  139. }
  140. /// <summary>
  141. /// Deletes the encoded media cache.
  142. /// </summary>
  143. private void DeleteEncodedMediaCache()
  144. {
  145. var path = _config.ApplicationPaths.TranscodingTempPath;
  146. foreach (var file in _fileSystem.GetFilePaths(path, true)
  147. .ToList())
  148. {
  149. _fileSystem.DeleteFile(file);
  150. }
  151. }
  152. /// <summary>
  153. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  154. /// </summary>
  155. public void Dispose()
  156. {
  157. Dispose(true);
  158. GC.SuppressFinalize(this);
  159. }
  160. /// <summary>
  161. /// Releases unmanaged and - optionally - managed resources.
  162. /// </summary>
  163. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  164. protected virtual void Dispose(bool dispose)
  165. {
  166. var list = _activeTranscodingJobs.ToList();
  167. var jobCount = list.Count;
  168. Parallel.ForEach(list, j => KillTranscodingJob(j, false, path => true));
  169. // Try to allow for some time to kill the ffmpeg processes and delete the partial stream files
  170. if (jobCount > 0)
  171. {
  172. var task = Task.Delay(1000);
  173. Task.WaitAll(task);
  174. }
  175. }
  176. /// <summary>
  177. /// Called when [transcode beginning].
  178. /// </summary>
  179. /// <param name="path">The path.</param>
  180. /// <param name="playSessionId">The play session identifier.</param>
  181. /// <param name="liveStreamId">The live stream identifier.</param>
  182. /// <param name="transcodingJobId">The transcoding job identifier.</param>
  183. /// <param name="type">The type.</param>
  184. /// <param name="process">The process.</param>
  185. /// <param name="deviceId">The device id.</param>
  186. /// <param name="state">The state.</param>
  187. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  188. /// <returns>TranscodingJob.</returns>
  189. public TranscodingJob OnTranscodeBeginning(string path,
  190. string playSessionId,
  191. string liveStreamId,
  192. string transcodingJobId,
  193. TranscodingJobType type,
  194. IProcess process,
  195. string deviceId,
  196. StreamState state,
  197. CancellationTokenSource cancellationTokenSource)
  198. {
  199. lock (_activeTranscodingJobs)
  200. {
  201. var job = new TranscodingJob(Logger, TimerFactory)
  202. {
  203. Type = type,
  204. Path = path,
  205. Process = process,
  206. ActiveRequestCount = 1,
  207. DeviceId = deviceId,
  208. CancellationTokenSource = cancellationTokenSource,
  209. Id = transcodingJobId,
  210. PlaySessionId = playSessionId,
  211. LiveStreamId = liveStreamId,
  212. MediaSource = state.MediaSource
  213. };
  214. _activeTranscodingJobs.Add(job);
  215. ReportTranscodingProgress(job, state, null, null, null, null, null);
  216. return job;
  217. }
  218. }
  219. public void ReportTranscodingProgress(TranscodingJob job, StreamState state, TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded, int? bitRate)
  220. {
  221. var ticks = transcodingPosition.HasValue ? transcodingPosition.Value.Ticks : (long?)null;
  222. if (job != null)
  223. {
  224. job.Framerate = framerate;
  225. job.CompletionPercentage = percentComplete;
  226. job.TranscodingPositionTicks = ticks;
  227. job.BytesTranscoded = bytesTranscoded;
  228. job.BitRate = bitRate;
  229. }
  230. var deviceId = state.Request.DeviceId;
  231. if (!string.IsNullOrWhiteSpace(deviceId))
  232. {
  233. var audioCodec = state.ActualOutputAudioCodec;
  234. var videoCodec = state.ActualOutputVideoCodec;
  235. _sessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
  236. {
  237. Bitrate = bitRate ?? state.TotalOutputBitrate,
  238. AudioCodec = audioCodec,
  239. VideoCodec = videoCodec,
  240. Container = state.OutputContainer,
  241. Framerate = framerate,
  242. CompletionPercentage = percentComplete,
  243. Width = state.OutputWidth,
  244. Height = state.OutputHeight,
  245. AudioChannels = state.OutputAudioChannels,
  246. IsAudioDirect = string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase),
  247. IsVideoDirect = string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase),
  248. TranscodeReasons = state.TranscodeReasons
  249. });
  250. }
  251. }
  252. /// <summary>
  253. /// <summary>
  254. /// The progressive
  255. /// </summary>
  256. /// Called when [transcode failed to start].
  257. /// </summary>
  258. /// <param name="path">The path.</param>
  259. /// <param name="type">The type.</param>
  260. /// <param name="state">The state.</param>
  261. public void OnTranscodeFailedToStart(string path, TranscodingJobType type, StreamState state)
  262. {
  263. lock (_activeTranscodingJobs)
  264. {
  265. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
  266. if (job != null)
  267. {
  268. _activeTranscodingJobs.Remove(job);
  269. }
  270. }
  271. lock (_transcodingLocks)
  272. {
  273. _transcodingLocks.Remove(path);
  274. }
  275. if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
  276. {
  277. _sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
  278. }
  279. }
  280. /// <summary>
  281. /// Determines whether [has active transcoding job] [the specified path].
  282. /// </summary>
  283. /// <param name="path">The path.</param>
  284. /// <param name="type">The type.</param>
  285. /// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
  286. public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
  287. {
  288. return GetTranscodingJob(path, type) != null;
  289. }
  290. public TranscodingJob GetTranscodingJob(string path, TranscodingJobType type)
  291. {
  292. lock (_activeTranscodingJobs)
  293. {
  294. return _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
  295. }
  296. }
  297. public TranscodingJob GetTranscodingJob(string playSessionId)
  298. {
  299. lock (_activeTranscodingJobs)
  300. {
  301. return _activeTranscodingJobs.FirstOrDefault(j => string.Equals(j.PlaySessionId, playSessionId, StringComparison.OrdinalIgnoreCase));
  302. }
  303. }
  304. /// <summary>
  305. /// Called when [transcode begin request].
  306. /// </summary>
  307. /// <param name="path">The path.</param>
  308. /// <param name="type">The type.</param>
  309. public TranscodingJob OnTranscodeBeginRequest(string path, TranscodingJobType type)
  310. {
  311. lock (_activeTranscodingJobs)
  312. {
  313. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
  314. if (job == null)
  315. {
  316. return null;
  317. }
  318. OnTranscodeBeginRequest(job);
  319. return job;
  320. }
  321. }
  322. public void OnTranscodeBeginRequest(TranscodingJob job)
  323. {
  324. job.ActiveRequestCount++;
  325. if (string.IsNullOrWhiteSpace(job.PlaySessionId) || job.Type == TranscodingJobType.Progressive)
  326. {
  327. job.StopKillTimer();
  328. }
  329. }
  330. public void OnTranscodeEndRequest(TranscodingJob job)
  331. {
  332. job.ActiveRequestCount--;
  333. //Logger.LogDebug("OnTranscodeEndRequest job.ActiveRequestCount={0}", job.ActiveRequestCount);
  334. if (job.ActiveRequestCount <= 0)
  335. {
  336. PingTimer(job, false);
  337. }
  338. }
  339. internal void PingTranscodingJob(string playSessionId, bool? isUserPaused)
  340. {
  341. if (string.IsNullOrEmpty(playSessionId))
  342. {
  343. throw new ArgumentNullException(nameof(playSessionId));
  344. }
  345. //Logger.LogDebug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused);
  346. List<TranscodingJob> jobs;
  347. lock (_activeTranscodingJobs)
  348. {
  349. // This is really only needed for HLS.
  350. // Progressive streams can stop on their own reliably
  351. jobs = _activeTranscodingJobs.Where(j => string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)).ToList();
  352. }
  353. foreach (var job in jobs)
  354. {
  355. if (isUserPaused.HasValue)
  356. {
  357. //Logger.LogDebug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id);
  358. job.IsUserPaused = isUserPaused.Value;
  359. }
  360. PingTimer(job, true);
  361. }
  362. }
  363. private void PingTimer(TranscodingJob job, bool isProgressCheckIn)
  364. {
  365. if (job.HasExited)
  366. {
  367. job.StopKillTimer();
  368. return;
  369. }
  370. var timerDuration = 10000;
  371. if (job.Type != TranscodingJobType.Progressive)
  372. {
  373. timerDuration = 60000;
  374. }
  375. job.PingTimeout = timerDuration;
  376. job.LastPingDate = DateTime.UtcNow;
  377. // Don't start the timer for playback checkins with progressive streaming
  378. if (job.Type != TranscodingJobType.Progressive || !isProgressCheckIn)
  379. {
  380. job.StartKillTimer(OnTranscodeKillTimerStopped);
  381. }
  382. else
  383. {
  384. job.ChangeKillTimerIfStarted();
  385. }
  386. }
  387. /// <summary>
  388. /// Called when [transcode kill timer stopped].
  389. /// </summary>
  390. /// <param name="state">The state.</param>
  391. private void OnTranscodeKillTimerStopped(object state)
  392. {
  393. var job = (TranscodingJob)state;
  394. if (!job.HasExited && job.Type != TranscodingJobType.Progressive)
  395. {
  396. var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds;
  397. if (timeSinceLastPing < job.PingTimeout)
  398. {
  399. job.StartKillTimer(OnTranscodeKillTimerStopped, job.PingTimeout);
  400. return;
  401. }
  402. }
  403. Logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
  404. KillTranscodingJob(job, true, path => true);
  405. }
  406. /// <summary>
  407. /// Kills the single transcoding job.
  408. /// </summary>
  409. /// <param name="deviceId">The device id.</param>
  410. /// <param name="playSessionId">The play session identifier.</param>
  411. /// <param name="deleteFiles">The delete files.</param>
  412. /// <returns>Task.</returns>
  413. internal void KillTranscodingJobs(string deviceId, string playSessionId, Func<string, bool> deleteFiles)
  414. {
  415. KillTranscodingJobs(j =>
  416. {
  417. if (!string.IsNullOrWhiteSpace(playSessionId))
  418. {
  419. return string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase);
  420. }
  421. return string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase);
  422. }, deleteFiles);
  423. }
  424. /// <summary>
  425. /// Kills the transcoding jobs.
  426. /// </summary>
  427. /// <param name="killJob">The kill job.</param>
  428. /// <param name="deleteFiles">The delete files.</param>
  429. /// <returns>Task.</returns>
  430. private void KillTranscodingJobs(Func<TranscodingJob, bool> killJob, Func<string, bool> deleteFiles)
  431. {
  432. var jobs = new List<TranscodingJob>();
  433. lock (_activeTranscodingJobs)
  434. {
  435. // This is really only needed for HLS.
  436. // Progressive streams can stop on their own reliably
  437. jobs.AddRange(_activeTranscodingJobs.Where(killJob));
  438. }
  439. if (jobs.Count == 0)
  440. {
  441. return;
  442. }
  443. foreach (var job in jobs)
  444. {
  445. KillTranscodingJob(job, false, deleteFiles);
  446. }
  447. }
  448. /// <summary>
  449. /// Kills the transcoding job.
  450. /// </summary>
  451. /// <param name="job">The job.</param>
  452. /// <param name="closeLiveStream">if set to <c>true</c> [close live stream].</param>
  453. /// <param name="delete">The delete.</param>
  454. private async void KillTranscodingJob(TranscodingJob job, bool closeLiveStream, Func<string, bool> delete)
  455. {
  456. job.DisposeKillTimer();
  457. Logger.LogDebug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
  458. lock (_activeTranscodingJobs)
  459. {
  460. _activeTranscodingJobs.Remove(job);
  461. if (!job.CancellationTokenSource.IsCancellationRequested)
  462. {
  463. job.CancellationTokenSource.Cancel();
  464. }
  465. }
  466. lock (_transcodingLocks)
  467. {
  468. _transcodingLocks.Remove(job.Path);
  469. }
  470. lock (job.ProcessLock)
  471. {
  472. if (job.TranscodingThrottler != null)
  473. {
  474. job.TranscodingThrottler.Stop();
  475. }
  476. var process = job.Process;
  477. var hasExited = job.HasExited;
  478. if (!hasExited)
  479. {
  480. try
  481. {
  482. Logger.LogInformation("Stopping ffmpeg process with q command for {path}", job.Path);
  483. //process.Kill();
  484. process.StandardInput.WriteLine("q");
  485. // Need to wait because killing is asynchronous
  486. if (!process.WaitForExit(5000))
  487. {
  488. Logger.LogInformation("Killing ffmpeg process for {path}", job.Path);
  489. process.Kill();
  490. }
  491. }
  492. catch (Exception ex)
  493. {
  494. Logger.LogError(ex, "Error killing transcoding job for {path}", job.Path);
  495. }
  496. }
  497. }
  498. if (delete(job.Path))
  499. {
  500. DeletePartialStreamFiles(job.Path, job.Type, 0, 1500);
  501. }
  502. if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
  503. {
  504. try
  505. {
  506. await _mediaSourceManager.CloseLiveStream(job.LiveStreamId).ConfigureAwait(false);
  507. }
  508. catch (Exception ex)
  509. {
  510. Logger.LogError(ex, "Error closing live stream for {path}", job.Path);
  511. }
  512. }
  513. }
  514. private async void DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
  515. {
  516. if (retryCount >= 10)
  517. {
  518. return;
  519. }
  520. Logger.LogInformation("Deleting partial stream file(s) {0}", path);
  521. await Task.Delay(delayMs).ConfigureAwait(false);
  522. try
  523. {
  524. if (jobType == TranscodingJobType.Progressive)
  525. {
  526. DeleteProgressivePartialStreamFiles(path);
  527. }
  528. else
  529. {
  530. DeleteHlsPartialStreamFiles(path);
  531. }
  532. }
  533. catch (FileNotFoundException)
  534. {
  535. }
  536. catch (IOException ex)
  537. {
  538. Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path);
  539. DeletePartialStreamFiles(path, jobType, retryCount + 1, 500);
  540. }
  541. catch (Exception ex)
  542. {
  543. Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path);
  544. }
  545. }
  546. /// <summary>
  547. /// Deletes the progressive partial stream files.
  548. /// </summary>
  549. /// <param name="outputFilePath">The output file path.</param>
  550. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  551. {
  552. _fileSystem.DeleteFile(outputFilePath);
  553. }
  554. /// <summary>
  555. /// Deletes the HLS partial stream files.
  556. /// </summary>
  557. /// <param name="outputFilePath">The output file path.</param>
  558. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  559. {
  560. var directory = _fileSystem.GetDirectoryName(outputFilePath);
  561. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  562. var filesToDelete = _fileSystem.GetFilePaths(directory)
  563. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  564. .ToList();
  565. Exception e = null;
  566. foreach (var file in filesToDelete)
  567. {
  568. try
  569. {
  570. //Logger.LogDebug("Deleting HLS file {0}", file);
  571. _fileSystem.DeleteFile(file);
  572. }
  573. catch (FileNotFoundException)
  574. {
  575. }
  576. catch (IOException ex)
  577. {
  578. e = ex;
  579. Logger.LogError(ex, "Error deleting HLS file {path}", file);
  580. }
  581. }
  582. if (e != null)
  583. {
  584. throw e;
  585. }
  586. }
  587. }
  588. /// <summary>
  589. /// Class TranscodingJob
  590. /// </summary>
  591. public class TranscodingJob
  592. {
  593. /// <summary>
  594. /// Gets or sets the play session identifier.
  595. /// </summary>
  596. /// <value>The play session identifier.</value>
  597. public string PlaySessionId { get; set; }
  598. /// <summary>
  599. /// Gets or sets the live stream identifier.
  600. /// </summary>
  601. /// <value>The live stream identifier.</value>
  602. public string LiveStreamId { get; set; }
  603. public bool IsLiveOutput { get; set; }
  604. /// <summary>
  605. /// Gets or sets the path.
  606. /// </summary>
  607. /// <value>The path.</value>
  608. public MediaSourceInfo MediaSource { get; set; }
  609. public string Path { get; set; }
  610. /// <summary>
  611. /// Gets or sets the type.
  612. /// </summary>
  613. /// <value>The type.</value>
  614. public TranscodingJobType Type { get; set; }
  615. /// <summary>
  616. /// Gets or sets the process.
  617. /// </summary>
  618. /// <value>The process.</value>
  619. public IProcess Process { get; set; }
  620. public ILogger Logger { get; private set; }
  621. /// <summary>
  622. /// Gets or sets the active request count.
  623. /// </summary>
  624. /// <value>The active request count.</value>
  625. public int ActiveRequestCount { get; set; }
  626. /// <summary>
  627. /// Gets or sets the kill timer.
  628. /// </summary>
  629. /// <value>The kill timer.</value>
  630. private ITimer KillTimer { get; set; }
  631. private readonly ITimerFactory _timerFactory;
  632. public string DeviceId { get; set; }
  633. public CancellationTokenSource CancellationTokenSource { get; set; }
  634. public object ProcessLock = new object();
  635. public bool HasExited { get; set; }
  636. public bool IsUserPaused { get; set; }
  637. public string Id { get; set; }
  638. public float? Framerate { get; set; }
  639. public double? CompletionPercentage { get; set; }
  640. public long? BytesDownloaded { get; set; }
  641. public long? BytesTranscoded { get; set; }
  642. public int? BitRate { get; set; }
  643. public long? TranscodingPositionTicks { get; set; }
  644. public long? DownloadPositionTicks { get; set; }
  645. public TranscodingThrottler TranscodingThrottler { get; set; }
  646. private readonly object _timerLock = new object();
  647. public DateTime LastPingDate { get; set; }
  648. public int PingTimeout { get; set; }
  649. public TranscodingJob(ILogger logger, ITimerFactory timerFactory)
  650. {
  651. Logger = logger;
  652. _timerFactory = timerFactory;
  653. }
  654. public void StopKillTimer()
  655. {
  656. lock (_timerLock)
  657. {
  658. if (KillTimer != null)
  659. {
  660. KillTimer.Change(Timeout.Infinite, Timeout.Infinite);
  661. }
  662. }
  663. }
  664. public void DisposeKillTimer()
  665. {
  666. lock (_timerLock)
  667. {
  668. if (KillTimer != null)
  669. {
  670. KillTimer.Dispose();
  671. KillTimer = null;
  672. }
  673. }
  674. }
  675. public void StartKillTimer(Action<object> callback)
  676. {
  677. StartKillTimer(callback, PingTimeout);
  678. }
  679. public void StartKillTimer(Action<object> callback, int intervalMs)
  680. {
  681. if (HasExited)
  682. {
  683. return;
  684. }
  685. lock (_timerLock)
  686. {
  687. if (KillTimer == null)
  688. {
  689. //Logger.LogDebug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  690. KillTimer = _timerFactory.Create(callback, this, intervalMs, Timeout.Infinite);
  691. }
  692. else
  693. {
  694. //Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  695. KillTimer.Change(intervalMs, Timeout.Infinite);
  696. }
  697. }
  698. }
  699. public void ChangeKillTimerIfStarted()
  700. {
  701. if (HasExited)
  702. {
  703. return;
  704. }
  705. lock (_timerLock)
  706. {
  707. if (KillTimer != null)
  708. {
  709. var intervalMs = PingTimeout;
  710. //Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  711. KillTimer.Change(intervalMs, Timeout.Infinite);
  712. }
  713. }
  714. }
  715. }
  716. }