ApiEntryPoint.cs 26 KB

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