ApiEntryPoint.cs 28 KB

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