ApiEntryPoint.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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 list = _activeTranscodingJobs.ToList();
  116. var jobCount = list.Count;
  117. Parallel.ForEach(list, 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.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
  215. if (job != null)
  216. {
  217. _activeTranscodingJobs.Remove(job);
  218. }
  219. }
  220. if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
  221. {
  222. _sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
  223. }
  224. }
  225. /// <summary>
  226. /// Determines whether [has active transcoding job] [the specified path].
  227. /// </summary>
  228. /// <param name="path">The path.</param>
  229. /// <param name="type">The type.</param>
  230. /// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
  231. public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
  232. {
  233. return GetTranscodingJob(path, type) != null;
  234. }
  235. public TranscodingJob GetTranscodingJob(string path, TranscodingJobType type)
  236. {
  237. lock (_activeTranscodingJobs)
  238. {
  239. return _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
  240. }
  241. }
  242. /// <summary>
  243. /// Called when [transcode begin request].
  244. /// </summary>
  245. /// <param name="path">The path.</param>
  246. /// <param name="type">The type.</param>
  247. public TranscodingJob OnTranscodeBeginRequest(string path, TranscodingJobType type)
  248. {
  249. lock (_activeTranscodingJobs)
  250. {
  251. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
  252. if (job == null)
  253. {
  254. return null;
  255. }
  256. OnTranscodeBeginRequest(job);
  257. return job;
  258. }
  259. }
  260. public void OnTranscodeBeginRequest(TranscodingJob job)
  261. {
  262. job.ActiveRequestCount++;
  263. if (string.IsNullOrWhiteSpace(job.PlaySessionId) || job.Type == TranscodingJobType.Progressive)
  264. {
  265. job.StopKillTimer();
  266. }
  267. }
  268. public void OnTranscodeEndRequest(TranscodingJob job)
  269. {
  270. job.ActiveRequestCount--;
  271. //Logger.Debug("OnTranscodeEndRequest job.ActiveRequestCount={0}", job.ActiveRequestCount);
  272. if (job.ActiveRequestCount <= 0)
  273. {
  274. PingTimer(job, false);
  275. }
  276. }
  277. internal void PingTranscodingJob(string playSessionId, bool? isUserPaused)
  278. {
  279. if (string.IsNullOrEmpty(playSessionId))
  280. {
  281. throw new ArgumentNullException("playSessionId");
  282. }
  283. //Logger.Debug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused);
  284. List<TranscodingJob> jobs;
  285. lock (_activeTranscodingJobs)
  286. {
  287. // This is really only needed for HLS.
  288. // Progressive streams can stop on their own reliably
  289. jobs = _activeTranscodingJobs.Where(j => string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)).ToList();
  290. }
  291. foreach (var job in jobs)
  292. {
  293. if (isUserPaused.HasValue)
  294. {
  295. //Logger.Debug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id);
  296. job.IsUserPaused = isUserPaused.Value;
  297. }
  298. PingTimer(job, true);
  299. }
  300. }
  301. private async void PingTimer(TranscodingJob job, bool isProgressCheckIn)
  302. {
  303. if (job.HasExited)
  304. {
  305. job.StopKillTimer();
  306. return;
  307. }
  308. var timerDuration = 10000;
  309. if (job.Type != TranscodingJobType.Progressive)
  310. {
  311. timerDuration = 60000;
  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("Stopping ffmpeg process with q command for {0}", job.Path);
  428. //process.Kill();
  429. process.StandardInput.WriteLine("q");
  430. // Need to wait because killing is asynchronous
  431. if (!process.WaitForExit(5000))
  432. {
  433. Logger.Info("Killing ffmpeg process for {0}", job.Path);
  434. process.Kill();
  435. }
  436. }
  437. catch (Exception ex)
  438. {
  439. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  440. }
  441. }
  442. }
  443. if (delete(job.Path))
  444. {
  445. DeletePartialStreamFiles(job.Path, job.Type, 0, 1500);
  446. }
  447. if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
  448. {
  449. try
  450. {
  451. await _mediaSourceManager.CloseLiveStream(job.LiveStreamId, CancellationToken.None).ConfigureAwait(false);
  452. }
  453. catch (Exception ex)
  454. {
  455. Logger.ErrorException("Error closing live stream for {0}", ex, job.Path);
  456. }
  457. }
  458. }
  459. private async void DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
  460. {
  461. if (retryCount >= 10)
  462. {
  463. return;
  464. }
  465. Logger.Info("Deleting partial stream file(s) {0}", path);
  466. await Task.Delay(delayMs).ConfigureAwait(false);
  467. try
  468. {
  469. if (jobType == TranscodingJobType.Progressive)
  470. {
  471. DeleteProgressivePartialStreamFiles(path);
  472. }
  473. else
  474. {
  475. DeleteHlsPartialStreamFiles(path);
  476. }
  477. }
  478. catch (DirectoryNotFoundException)
  479. {
  480. }
  481. catch (FileNotFoundException)
  482. {
  483. }
  484. catch (IOException)
  485. {
  486. //Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  487. DeletePartialStreamFiles(path, jobType, retryCount + 1, 500);
  488. }
  489. catch
  490. {
  491. //Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  492. }
  493. }
  494. /// <summary>
  495. /// Deletes the progressive partial stream files.
  496. /// </summary>
  497. /// <param name="outputFilePath">The output file path.</param>
  498. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  499. {
  500. _fileSystem.DeleteFile(outputFilePath);
  501. }
  502. /// <summary>
  503. /// Deletes the HLS partial stream files.
  504. /// </summary>
  505. /// <param name="outputFilePath">The output file path.</param>
  506. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  507. {
  508. var directory = Path.GetDirectoryName(outputFilePath);
  509. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  510. var filesToDelete = _fileSystem.GetFilePaths(directory)
  511. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  512. .ToList();
  513. Exception e = null;
  514. foreach (var file in filesToDelete)
  515. {
  516. try
  517. {
  518. //Logger.Debug("Deleting HLS file {0}", file);
  519. _fileSystem.DeleteFile(file);
  520. }
  521. catch (DirectoryNotFoundException)
  522. {
  523. }
  524. catch (FileNotFoundException)
  525. {
  526. }
  527. catch (IOException ex)
  528. {
  529. e = ex;
  530. //Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  531. }
  532. }
  533. if (e != null)
  534. {
  535. throw e;
  536. }
  537. }
  538. }
  539. /// <summary>
  540. /// Class TranscodingJob
  541. /// </summary>
  542. public class TranscodingJob
  543. {
  544. /// <summary>
  545. /// Gets or sets the play session identifier.
  546. /// </summary>
  547. /// <value>The play session identifier.</value>
  548. public string PlaySessionId { get; set; }
  549. /// <summary>
  550. /// Gets or sets the live stream identifier.
  551. /// </summary>
  552. /// <value>The live stream identifier.</value>
  553. public string LiveStreamId { get; set; }
  554. public bool IsLiveOutput { get; set; }
  555. /// <summary>
  556. /// Gets or sets the path.
  557. /// </summary>
  558. /// <value>The path.</value>
  559. public string Path { get; set; }
  560. /// <summary>
  561. /// Gets or sets the type.
  562. /// </summary>
  563. /// <value>The type.</value>
  564. public TranscodingJobType Type { get; set; }
  565. /// <summary>
  566. /// Gets or sets the process.
  567. /// </summary>
  568. /// <value>The process.</value>
  569. public Process Process { get; set; }
  570. public ILogger Logger { get; private set; }
  571. /// <summary>
  572. /// Gets or sets the active request count.
  573. /// </summary>
  574. /// <value>The active request count.</value>
  575. public int ActiveRequestCount { get; set; }
  576. /// <summary>
  577. /// Gets or sets the kill timer.
  578. /// </summary>
  579. /// <value>The kill timer.</value>
  580. private Timer KillTimer { get; set; }
  581. public string DeviceId { get; set; }
  582. public CancellationTokenSource CancellationTokenSource { get; set; }
  583. public object ProcessLock = new object();
  584. public bool HasExited { get; set; }
  585. public bool IsUserPaused { get; set; }
  586. public string Id { get; set; }
  587. public float? Framerate { get; set; }
  588. public double? CompletionPercentage { get; set; }
  589. public long? BytesDownloaded { get; set; }
  590. public long? BytesTranscoded { get; set; }
  591. public long? TranscodingPositionTicks { get; set; }
  592. public long? DownloadPositionTicks { get; set; }
  593. public TranscodingThrottler TranscodingThrottler { get; set; }
  594. private readonly object _timerLock = new object();
  595. public DateTime LastPingDate { get; set; }
  596. public int PingTimeout { get; set; }
  597. public TranscodingJob(ILogger logger)
  598. {
  599. Logger = logger;
  600. }
  601. public void StopKillTimer()
  602. {
  603. lock (_timerLock)
  604. {
  605. if (KillTimer != null)
  606. {
  607. KillTimer.Change(Timeout.Infinite, Timeout.Infinite);
  608. }
  609. }
  610. }
  611. public void DisposeKillTimer()
  612. {
  613. lock (_timerLock)
  614. {
  615. if (KillTimer != null)
  616. {
  617. KillTimer.Dispose();
  618. KillTimer = null;
  619. }
  620. }
  621. }
  622. public void StartKillTimer(TimerCallback callback)
  623. {
  624. StartKillTimer(callback, PingTimeout);
  625. }
  626. public void StartKillTimer(TimerCallback callback, int intervalMs)
  627. {
  628. if (HasExited)
  629. {
  630. return;
  631. }
  632. lock (_timerLock)
  633. {
  634. if (KillTimer == null)
  635. {
  636. Logger.Debug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  637. KillTimer = new Timer(callback, this, intervalMs, Timeout.Infinite);
  638. }
  639. else
  640. {
  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. public void ChangeKillTimerIfStarted()
  647. {
  648. if (HasExited)
  649. {
  650. return;
  651. }
  652. lock (_timerLock)
  653. {
  654. if (KillTimer != null)
  655. {
  656. var intervalMs = PingTimeout;
  657. Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  658. KillTimer.Change(intervalMs, Timeout.Infinite);
  659. }
  660. }
  661. }
  662. }
  663. /// <summary>
  664. /// Enum TranscodingJobType
  665. /// </summary>
  666. public enum TranscodingJobType
  667. {
  668. /// <summary>
  669. /// The progressive
  670. /// </summary>
  671. Progressive,
  672. /// <summary>
  673. /// The HLS
  674. /// </summary>
  675. Hls,
  676. /// <summary>
  677. /// The dash
  678. /// </summary>
  679. Dash
  680. }
  681. }