ApiEntryPoint.cs 26 KB

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