ApiEntryPoint.cs 28 KB

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