ApiEntryPoint.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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 = 60000;
  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("Stopping ffmpeg process with q command for {0}", job.Path);
  424. //process.Kill();
  425. process.StandardInput.WriteLine("q");
  426. // Need to wait because killing is asynchronous
  427. if (!process.WaitForExit(5000))
  428. {
  429. Logger.Info("Killing ffmpeg process for {0}", job.Path);
  430. process.Kill();
  431. }
  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 = _fileSystem.GetFilePaths(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.Debug("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 bool IsUserPaused { get; set; }
  582. public string Id { get; set; }
  583. public float? Framerate { get; set; }
  584. public double? CompletionPercentage { get; set; }
  585. public long? BytesDownloaded { get; set; }
  586. public long? BytesTranscoded { get; set; }
  587. public long? TranscodingPositionTicks { get; set; }
  588. public long? DownloadPositionTicks { get; set; }
  589. public TranscodingThrottler TranscodingThrottler { get; set; }
  590. private readonly object _timerLock = new object();
  591. public DateTime LastPingDate { get; set; }
  592. public int PingTimeout { get; set; }
  593. public TranscodingJob(ILogger logger)
  594. {
  595. Logger = logger;
  596. }
  597. public void StopKillTimer()
  598. {
  599. lock (_timerLock)
  600. {
  601. if (KillTimer != null)
  602. {
  603. KillTimer.Change(Timeout.Infinite, Timeout.Infinite);
  604. }
  605. }
  606. }
  607. public void DisposeKillTimer()
  608. {
  609. lock (_timerLock)
  610. {
  611. if (KillTimer != null)
  612. {
  613. KillTimer.Dispose();
  614. KillTimer = null;
  615. }
  616. }
  617. }
  618. public void StartKillTimer(TimerCallback callback)
  619. {
  620. StartKillTimer(callback, PingTimeout);
  621. }
  622. public void StartKillTimer(TimerCallback callback, int intervalMs)
  623. {
  624. if (HasExited)
  625. {
  626. return;
  627. }
  628. lock (_timerLock)
  629. {
  630. if (KillTimer == null)
  631. {
  632. Logger.Debug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  633. KillTimer = new Timer(callback, this, intervalMs, Timeout.Infinite);
  634. }
  635. else
  636. {
  637. Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  638. KillTimer.Change(intervalMs, Timeout.Infinite);
  639. }
  640. }
  641. }
  642. public void ChangeKillTimerIfStarted()
  643. {
  644. if (HasExited)
  645. {
  646. return;
  647. }
  648. lock (_timerLock)
  649. {
  650. if (KillTimer != null)
  651. {
  652. var intervalMs = PingTimeout;
  653. Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  654. KillTimer.Change(intervalMs, Timeout.Infinite);
  655. }
  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. }