ApiEntryPoint.cs 28 KB

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