ApiEntryPoint.cs 28 KB

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