ApiEntryPoint.cs 28 KB

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