ApiEntryPoint.cs 27 KB

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