ApiEntryPoint.cs 28 KB

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