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. 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. }
  307. }
  308. job.PingTimeout = timerDuration;
  309. job.LastPingDate = DateTime.UtcNow;
  310. // Don't start the timer for playback checkins with progressive streaming
  311. if (job.Type != TranscodingJobType.Progressive || !isProgressCheckIn)
  312. {
  313. job.StartKillTimer(OnTranscodeKillTimerStopped);
  314. }
  315. else
  316. {
  317. job.ChangeKillTimerIfStarted();
  318. }
  319. if (!string.IsNullOrWhiteSpace(job.LiveStreamId))
  320. {
  321. try
  322. {
  323. await _mediaSourceManager.PingLiveStream(job.LiveStreamId, CancellationToken.None).ConfigureAwait(false);
  324. }
  325. catch (Exception ex)
  326. {
  327. Logger.ErrorException("Error closing live stream", ex);
  328. }
  329. }
  330. }
  331. /// <summary>
  332. /// Called when [transcode kill timer stopped].
  333. /// </summary>
  334. /// <param name="state">The state.</param>
  335. private void OnTranscodeKillTimerStopped(object state)
  336. {
  337. var job = (TranscodingJob)state;
  338. if (!job.HasExited && job.Type != TranscodingJobType.Progressive)
  339. {
  340. var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds;
  341. if (timeSinceLastPing < job.PingTimeout)
  342. {
  343. job.StartKillTimer(OnTranscodeKillTimerStopped, job.PingTimeout);
  344. return;
  345. }
  346. }
  347. Logger.Debug("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
  348. KillTranscodingJob(job, true, path => true);
  349. }
  350. /// <summary>
  351. /// Kills the single transcoding job.
  352. /// </summary>
  353. /// <param name="deviceId">The device id.</param>
  354. /// <param name="playSessionId">The play session identifier.</param>
  355. /// <param name="deleteFiles">The delete files.</param>
  356. /// <returns>Task.</returns>
  357. internal void KillTranscodingJobs(string deviceId, string playSessionId, Func<string, bool> deleteFiles)
  358. {
  359. KillTranscodingJobs(j =>
  360. {
  361. if (!string.IsNullOrWhiteSpace(playSessionId))
  362. {
  363. return string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase);
  364. }
  365. return string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase);
  366. }, deleteFiles);
  367. }
  368. /// <summary>
  369. /// Kills the transcoding jobs.
  370. /// </summary>
  371. /// <param name="killJob">The kill job.</param>
  372. /// <param name="deleteFiles">The delete files.</param>
  373. /// <returns>Task.</returns>
  374. private void KillTranscodingJobs(Func<TranscodingJob, bool> killJob, Func<string, bool> deleteFiles)
  375. {
  376. var jobs = new List<TranscodingJob>();
  377. lock (_activeTranscodingJobs)
  378. {
  379. // This is really only needed for HLS.
  380. // Progressive streams can stop on their own reliably
  381. jobs.AddRange(_activeTranscodingJobs.Where(killJob));
  382. }
  383. if (jobs.Count == 0)
  384. {
  385. return;
  386. }
  387. foreach (var job in jobs)
  388. {
  389. KillTranscodingJob(job, false, deleteFiles);
  390. }
  391. }
  392. /// <summary>
  393. /// Kills the transcoding job.
  394. /// </summary>
  395. /// <param name="job">The job.</param>
  396. /// <param name="closeLiveStream">if set to <c>true</c> [close live stream].</param>
  397. /// <param name="delete">The delete.</param>
  398. private async void KillTranscodingJob(TranscodingJob job, bool closeLiveStream, Func<string, bool> delete)
  399. {
  400. job.DisposeKillTimer();
  401. Logger.Debug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
  402. lock (_activeTranscodingJobs)
  403. {
  404. _activeTranscodingJobs.Remove(job);
  405. if (!job.CancellationTokenSource.IsCancellationRequested)
  406. {
  407. job.CancellationTokenSource.Cancel();
  408. }
  409. }
  410. lock (job.ProcessLock)
  411. {
  412. if (job.TranscodingThrottler != null)
  413. {
  414. job.TranscodingThrottler.Stop();
  415. }
  416. var process = job.Process;
  417. var hasExited = job.HasExited;
  418. if (!hasExited)
  419. {
  420. try
  421. {
  422. Logger.Info("Killing ffmpeg process for {0}", job.Path);
  423. //process.Kill();
  424. process.StandardInput.WriteLine("q");
  425. // Need to wait because killing is asynchronous
  426. process.WaitForExit(5000);
  427. }
  428. catch (Exception ex)
  429. {
  430. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  431. }
  432. }
  433. }
  434. if (delete(job.Path))
  435. {
  436. DeletePartialStreamFiles(job.Path, job.Type, 0, 1500);
  437. }
  438. if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
  439. {
  440. try
  441. {
  442. await _mediaSourceManager.CloseLiveStream(job.LiveStreamId, CancellationToken.None).ConfigureAwait(false);
  443. }
  444. catch (Exception ex)
  445. {
  446. Logger.ErrorException("Error closing live stream for {0}", ex, job.Path);
  447. }
  448. }
  449. }
  450. private async void DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
  451. {
  452. if (retryCount >= 10)
  453. {
  454. return;
  455. }
  456. Logger.Info("Deleting partial stream file(s) {0}", path);
  457. await Task.Delay(delayMs).ConfigureAwait(false);
  458. try
  459. {
  460. if (jobType == TranscodingJobType.Progressive)
  461. {
  462. DeleteProgressivePartialStreamFiles(path);
  463. }
  464. else
  465. {
  466. DeleteHlsPartialStreamFiles(path);
  467. }
  468. }
  469. catch (DirectoryNotFoundException)
  470. {
  471. }
  472. catch (FileNotFoundException)
  473. {
  474. }
  475. catch (IOException ex)
  476. {
  477. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  478. DeletePartialStreamFiles(path, jobType, retryCount + 1, 500);
  479. }
  480. catch (Exception ex)
  481. {
  482. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  483. }
  484. }
  485. /// <summary>
  486. /// Deletes the progressive partial stream files.
  487. /// </summary>
  488. /// <param name="outputFilePath">The output file path.</param>
  489. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  490. {
  491. _fileSystem.DeleteFile(outputFilePath);
  492. }
  493. /// <summary>
  494. /// Deletes the HLS partial stream files.
  495. /// </summary>
  496. /// <param name="outputFilePath">The output file path.</param>
  497. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  498. {
  499. var directory = Path.GetDirectoryName(outputFilePath);
  500. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  501. var filesToDelete = Directory.EnumerateFiles(directory)
  502. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  503. .ToList();
  504. Exception e = null;
  505. foreach (var file in filesToDelete)
  506. {
  507. try
  508. {
  509. Logger.Info("Deleting HLS file {0}", file);
  510. _fileSystem.DeleteFile(file);
  511. }
  512. catch (DirectoryNotFoundException)
  513. {
  514. }
  515. catch (FileNotFoundException)
  516. {
  517. }
  518. catch (IOException ex)
  519. {
  520. e = ex;
  521. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  522. }
  523. }
  524. if (e != null)
  525. {
  526. throw e;
  527. }
  528. }
  529. }
  530. /// <summary>
  531. /// Class TranscodingJob
  532. /// </summary>
  533. public class TranscodingJob
  534. {
  535. /// <summary>
  536. /// Gets or sets the play session identifier.
  537. /// </summary>
  538. /// <value>The play session identifier.</value>
  539. public string PlaySessionId { get; set; }
  540. /// <summary>
  541. /// Gets or sets the live stream identifier.
  542. /// </summary>
  543. /// <value>The live stream identifier.</value>
  544. public string LiveStreamId { get; set; }
  545. public bool IsLiveOutput { get; set; }
  546. /// <summary>
  547. /// Gets or sets the path.
  548. /// </summary>
  549. /// <value>The path.</value>
  550. public string Path { get; set; }
  551. /// <summary>
  552. /// Gets or sets the type.
  553. /// </summary>
  554. /// <value>The type.</value>
  555. public TranscodingJobType Type { get; set; }
  556. /// <summary>
  557. /// Gets or sets the process.
  558. /// </summary>
  559. /// <value>The process.</value>
  560. public Process Process { get; set; }
  561. public ILogger Logger { get; private set; }
  562. /// <summary>
  563. /// Gets or sets the active request count.
  564. /// </summary>
  565. /// <value>The active request count.</value>
  566. public int ActiveRequestCount { get; set; }
  567. /// <summary>
  568. /// Gets or sets the kill timer.
  569. /// </summary>
  570. /// <value>The kill timer.</value>
  571. private Timer KillTimer { get; set; }
  572. public string DeviceId { get; set; }
  573. public CancellationTokenSource CancellationTokenSource { get; set; }
  574. public object ProcessLock = new object();
  575. public bool HasExited { get; set; }
  576. public string Id { get; set; }
  577. public float? Framerate { get; set; }
  578. public double? CompletionPercentage { get; set; }
  579. public long? BytesDownloaded { get; set; }
  580. public long? BytesTranscoded { get; set; }
  581. public long? TranscodingPositionTicks { get; set; }
  582. public long? DownloadPositionTicks { get; set; }
  583. public TranscodingThrottler TranscodingThrottler { get; set; }
  584. private readonly object _timerLock = new object();
  585. public DateTime LastPingDate { get; set; }
  586. public int PingTimeout { get; set; }
  587. public TranscodingJob(ILogger logger)
  588. {
  589. Logger = logger;
  590. }
  591. public void StopKillTimer()
  592. {
  593. lock (_timerLock)
  594. {
  595. if (KillTimer != null)
  596. {
  597. KillTimer.Change(Timeout.Infinite, Timeout.Infinite);
  598. }
  599. }
  600. }
  601. public void DisposeKillTimer()
  602. {
  603. lock (_timerLock)
  604. {
  605. if (KillTimer != null)
  606. {
  607. KillTimer.Dispose();
  608. KillTimer = null;
  609. }
  610. }
  611. }
  612. public void StartKillTimer(TimerCallback callback)
  613. {
  614. StartKillTimer(callback, PingTimeout);
  615. }
  616. public void StartKillTimer(TimerCallback callback, int intervalMs)
  617. {
  618. CheckHasExited();
  619. lock (_timerLock)
  620. {
  621. if (KillTimer == null)
  622. {
  623. Logger.Debug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  624. KillTimer = new Timer(callback, this, intervalMs, Timeout.Infinite);
  625. }
  626. else
  627. {
  628. Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  629. KillTimer.Change(intervalMs, Timeout.Infinite);
  630. }
  631. }
  632. }
  633. public void ChangeKillTimerIfStarted()
  634. {
  635. CheckHasExited();
  636. lock (_timerLock)
  637. {
  638. if (KillTimer != null)
  639. {
  640. var intervalMs = PingTimeout;
  641. Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  642. KillTimer.Change(intervalMs, Timeout.Infinite);
  643. }
  644. }
  645. }
  646. private void CheckHasExited()
  647. {
  648. if (HasExited)
  649. {
  650. throw new ObjectDisposedException("Job");
  651. }
  652. }
  653. }
  654. /// <summary>
  655. /// Enum TranscodingJobType
  656. /// </summary>
  657. public enum TranscodingJobType
  658. {
  659. /// <summary>
  660. /// The progressive
  661. /// </summary>
  662. Progressive,
  663. /// <summary>
  664. /// The HLS
  665. /// </summary>
  666. Hls,
  667. /// <summary>
  668. /// The dash
  669. /// </summary>
  670. Dash
  671. }
  672. }