ApiEntryPoint.cs 26 KB

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