ApiEntryPoint.cs 26 KB

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