ApiEntryPoint.cs 28 KB

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