2
0

ApiEntryPoint.cs 26 KB

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