ApiEntryPoint.cs 26 KB

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