ApiEntryPoint.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. using MediaBrowser.Api.Playback;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Plugins;
  5. using MediaBrowser.Controller.Session;
  6. using MediaBrowser.Model.Configuration;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.Session;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Diagnostics;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Api
  17. {
  18. /// <summary>
  19. /// Class ServerEntryPoint
  20. /// </summary>
  21. public class ApiEntryPoint : IServerEntryPoint
  22. {
  23. /// <summary>
  24. /// The instance
  25. /// </summary>
  26. public static ApiEntryPoint Instance;
  27. /// <summary>
  28. /// Gets or sets the logger.
  29. /// </summary>
  30. /// <value>The logger.</value>
  31. private ILogger Logger { get; set; }
  32. /// <summary>
  33. /// The application paths
  34. /// </summary>
  35. private readonly IServerConfigurationManager _config;
  36. private readonly ISessionManager _sessionManager;
  37. public readonly SemaphoreSlim TranscodingStartLock = new SemaphoreSlim(1, 1);
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="ApiEntryPoint" /> class.
  40. /// </summary>
  41. /// <param name="logger">The logger.</param>
  42. /// <param name="sessionManager">The session manager.</param>
  43. /// <param name="config">The configuration.</param>
  44. public ApiEntryPoint(ILogger logger, ISessionManager sessionManager, IServerConfigurationManager config)
  45. {
  46. Logger = logger;
  47. _sessionManager = sessionManager;
  48. _config = config;
  49. Instance = this;
  50. }
  51. /// <summary>
  52. /// Runs this instance.
  53. /// </summary>
  54. public void Run()
  55. {
  56. try
  57. {
  58. DeleteEncodedMediaCache();
  59. }
  60. catch (DirectoryNotFoundException)
  61. {
  62. // Don't clutter the log
  63. }
  64. catch (IOException ex)
  65. {
  66. Logger.ErrorException("Error deleting encoded media cache", ex);
  67. }
  68. }
  69. public EncodingOptions GetEncodingOptions()
  70. {
  71. return _config.GetConfiguration<EncodingOptions>("encoding");
  72. }
  73. /// <summary>
  74. /// Deletes the encoded media cache.
  75. /// </summary>
  76. private void DeleteEncodedMediaCache()
  77. {
  78. foreach (var file in Directory.EnumerateFiles(_config.ApplicationPaths.TranscodingTempPath, "*", SearchOption.AllDirectories)
  79. .ToList())
  80. {
  81. File.Delete(file);
  82. }
  83. }
  84. /// <summary>
  85. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  86. /// </summary>
  87. public void Dispose()
  88. {
  89. Dispose(true);
  90. GC.SuppressFinalize(this);
  91. }
  92. /// <summary>
  93. /// Releases unmanaged and - optionally - managed resources.
  94. /// </summary>
  95. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  96. protected virtual void Dispose(bool dispose)
  97. {
  98. var jobCount = _activeTranscodingJobs.Count;
  99. Parallel.ForEach(_activeTranscodingJobs.ToList(), j => KillTranscodingJob(j, path => true));
  100. // Try to allow for some time to kill the ffmpeg processes and delete the partial stream files
  101. if (jobCount > 0)
  102. {
  103. Thread.Sleep(1000);
  104. }
  105. }
  106. /// <summary>
  107. /// The active transcoding jobs
  108. /// </summary>
  109. private readonly List<TranscodingJob> _activeTranscodingJobs = new List<TranscodingJob>();
  110. /// <summary>
  111. /// Called when [transcode beginning].
  112. /// </summary>
  113. /// <param name="path">The path.</param>
  114. /// <param name="transcodingJobId">The transcoding job identifier.</param>
  115. /// <param name="type">The type.</param>
  116. /// <param name="process">The process.</param>
  117. /// <param name="deviceId">The device id.</param>
  118. /// <param name="state">The state.</param>
  119. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  120. /// <returns>TranscodingJob.</returns>
  121. public TranscodingJob OnTranscodeBeginning(string path,
  122. string transcodingJobId,
  123. TranscodingJobType type,
  124. Process process,
  125. string deviceId,
  126. StreamState state,
  127. CancellationTokenSource cancellationTokenSource)
  128. {
  129. lock (_activeTranscodingJobs)
  130. {
  131. var job = new TranscodingJob
  132. {
  133. Type = type,
  134. Path = path,
  135. Process = process,
  136. ActiveRequestCount = 1,
  137. DeviceId = deviceId,
  138. CancellationTokenSource = cancellationTokenSource,
  139. Id = transcodingJobId
  140. };
  141. _activeTranscodingJobs.Add(job);
  142. ReportTranscodingProgress(job, state, null, null, null, null);
  143. return job;
  144. }
  145. }
  146. public void ReportTranscodingProgress(TranscodingJob job, StreamState state, TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded)
  147. {
  148. var ticks = transcodingPosition.HasValue ? transcodingPosition.Value.Ticks : (long?)null;
  149. if (job != null)
  150. {
  151. job.Framerate = framerate;
  152. job.CompletionPercentage = percentComplete;
  153. job.TranscodingPositionTicks = ticks;
  154. job.BytesTranscoded = bytesTranscoded;
  155. }
  156. var deviceId = state.Request.DeviceId;
  157. if (!string.IsNullOrWhiteSpace(deviceId))
  158. {
  159. var audioCodec = state.ActualOutputVideoCodec;
  160. var videoCodec = state.ActualOutputVideoCodec;
  161. _sessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
  162. {
  163. Bitrate = state.TotalOutputBitrate,
  164. AudioCodec = audioCodec,
  165. VideoCodec = videoCodec,
  166. Container = state.OutputContainer,
  167. Framerate = framerate,
  168. CompletionPercentage = percentComplete,
  169. Width = state.OutputWidth,
  170. Height = state.OutputHeight,
  171. AudioChannels = state.OutputAudioChannels,
  172. IsAudioDirect = string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase),
  173. IsVideoDirect = string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase)
  174. });
  175. }
  176. }
  177. /// <summary>
  178. /// <summary>
  179. /// The progressive
  180. /// </summary>
  181. /// Called when [transcode failed to start].
  182. /// </summary>
  183. /// <param name="path">The path.</param>
  184. /// <param name="type">The type.</param>
  185. /// <param name="state">The state.</param>
  186. public void OnTranscodeFailedToStart(string path, TranscodingJobType type, StreamState state)
  187. {
  188. lock (_activeTranscodingJobs)
  189. {
  190. var job = _activeTranscodingJobs.First(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  191. _activeTranscodingJobs.Remove(job);
  192. }
  193. if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
  194. {
  195. _sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
  196. }
  197. }
  198. /// <summary>
  199. /// Determines whether [has active transcoding job] [the specified path].
  200. /// </summary>
  201. /// <param name="path">The path.</param>
  202. /// <param name="type">The type.</param>
  203. /// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
  204. public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
  205. {
  206. return GetTranscodingJob(path, type) != null;
  207. }
  208. public TranscodingJob GetTranscodingJob(string path, TranscodingJobType type)
  209. {
  210. lock (_activeTranscodingJobs)
  211. {
  212. return _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  213. }
  214. }
  215. public TranscodingJob GetTranscodingJob(string id)
  216. {
  217. lock (_activeTranscodingJobs)
  218. {
  219. return _activeTranscodingJobs.FirstOrDefault(j => j.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
  220. }
  221. }
  222. /// <summary>
  223. /// Called when [transcode begin request].
  224. /// </summary>
  225. /// <param name="path">The path.</param>
  226. /// <param name="type">The type.</param>
  227. public TranscodingJob OnTranscodeBeginRequest(string path, TranscodingJobType type)
  228. {
  229. lock (_activeTranscodingJobs)
  230. {
  231. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  232. if (job == null)
  233. {
  234. return null;
  235. }
  236. job.ActiveRequestCount++;
  237. job.DisposeKillTimer();
  238. return job;
  239. }
  240. }
  241. public void OnTranscodeEndRequest(TranscodingJob job)
  242. {
  243. job.ActiveRequestCount--;
  244. if (job.ActiveRequestCount == 0)
  245. {
  246. if (job.Type == TranscodingJobType.Progressive)
  247. {
  248. const int timerDuration = 1000;
  249. if (job.KillTimer == null)
  250. {
  251. job.KillTimer = new Timer(OnTranscodeKillTimerStopped, job, timerDuration, Timeout.Infinite);
  252. }
  253. else
  254. {
  255. job.KillTimer.Change(timerDuration, Timeout.Infinite);
  256. }
  257. }
  258. }
  259. }
  260. /// <summary>
  261. /// Called when [transcode kill timer stopped].
  262. /// </summary>
  263. /// <param name="state">The state.</param>
  264. private void OnTranscodeKillTimerStopped(object state)
  265. {
  266. var job = (TranscodingJob)state;
  267. KillTranscodingJob(job, path => true);
  268. }
  269. /// <summary>
  270. /// Kills the single transcoding job.
  271. /// </summary>
  272. /// <param name="deviceId">The device id.</param>
  273. /// <param name="deleteFiles">The delete files.</param>
  274. /// <returns>Task.</returns>
  275. /// <exception cref="ArgumentNullException">deviceId</exception>
  276. internal void KillTranscodingJobs(string deviceId, Func<string, bool> deleteFiles)
  277. {
  278. if (string.IsNullOrEmpty(deviceId))
  279. {
  280. throw new ArgumentNullException("deviceId");
  281. }
  282. KillTranscodingJobs(j => string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase), deleteFiles);
  283. }
  284. /// <summary>
  285. /// Kills the transcoding jobs.
  286. /// </summary>
  287. /// <param name="killJob">The kill job.</param>
  288. /// <param name="deleteFiles">The delete files.</param>
  289. /// <returns>Task.</returns>
  290. internal void KillTranscodingJobs(Func<TranscodingJob, bool> killJob, Func<string, bool> deleteFiles)
  291. {
  292. var jobs = new List<TranscodingJob>();
  293. lock (_activeTranscodingJobs)
  294. {
  295. // This is really only needed for HLS.
  296. // Progressive streams can stop on their own reliably
  297. jobs.AddRange(_activeTranscodingJobs.Where(killJob));
  298. }
  299. if (jobs.Count == 0)
  300. {
  301. return;
  302. }
  303. foreach (var job in jobs)
  304. {
  305. KillTranscodingJob(job, deleteFiles);
  306. }
  307. }
  308. /// <summary>
  309. /// Kills the transcoding job.
  310. /// </summary>
  311. /// <param name="job">The job.</param>
  312. /// <param name="delete">The delete.</param>
  313. private void KillTranscodingJob(TranscodingJob job, Func<string, bool> delete)
  314. {
  315. lock (_activeTranscodingJobs)
  316. {
  317. _activeTranscodingJobs.Remove(job);
  318. if (!job.CancellationTokenSource.IsCancellationRequested)
  319. {
  320. job.CancellationTokenSource.Cancel();
  321. }
  322. job.DisposeKillTimer();
  323. }
  324. lock (job.ProcessLock)
  325. {
  326. var process = job.Process;
  327. var hasExited = true;
  328. try
  329. {
  330. hasExited = process.HasExited;
  331. }
  332. catch (Exception ex)
  333. {
  334. Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
  335. }
  336. if (!hasExited)
  337. {
  338. try
  339. {
  340. Logger.Info("Killing ffmpeg process for {0}", job.Path);
  341. //process.Kill();
  342. process.StandardInput.WriteLine("q");
  343. // Need to wait because killing is asynchronous
  344. process.WaitForExit(5000);
  345. }
  346. catch (Exception ex)
  347. {
  348. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  349. }
  350. }
  351. }
  352. if (delete(job.Path))
  353. {
  354. DeletePartialStreamFiles(job.Path, job.Type, 0, 1500);
  355. }
  356. }
  357. private async void DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
  358. {
  359. if (retryCount >= 10)
  360. {
  361. return;
  362. }
  363. Logger.Info("Deleting partial stream file(s) {0}", path);
  364. await Task.Delay(delayMs).ConfigureAwait(false);
  365. try
  366. {
  367. if (jobType == TranscodingJobType.Progressive)
  368. {
  369. DeleteProgressivePartialStreamFiles(path);
  370. }
  371. else
  372. {
  373. DeleteHlsPartialStreamFiles(path);
  374. }
  375. }
  376. catch (DirectoryNotFoundException)
  377. {
  378. }
  379. catch (FileNotFoundException)
  380. {
  381. }
  382. catch (IOException ex)
  383. {
  384. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  385. DeletePartialStreamFiles(path, jobType, retryCount + 1, 500);
  386. }
  387. catch (Exception ex)
  388. {
  389. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  390. }
  391. }
  392. /// <summary>
  393. /// Deletes the progressive partial stream files.
  394. /// </summary>
  395. /// <param name="outputFilePath">The output file path.</param>
  396. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  397. {
  398. File.Delete(outputFilePath);
  399. }
  400. /// <summary>
  401. /// Deletes the HLS partial stream files.
  402. /// </summary>
  403. /// <param name="outputFilePath">The output file path.</param>
  404. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  405. {
  406. var directory = Path.GetDirectoryName(outputFilePath);
  407. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  408. var filesToDelete = Directory.EnumerateFiles(directory)
  409. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  410. .ToList();
  411. Exception e = null;
  412. foreach (var file in filesToDelete)
  413. {
  414. try
  415. {
  416. Logger.Info("Deleting HLS file {0}", file);
  417. File.Delete(file);
  418. }
  419. catch (DirectoryNotFoundException)
  420. {
  421. }
  422. catch (FileNotFoundException)
  423. {
  424. }
  425. catch (IOException ex)
  426. {
  427. e = ex;
  428. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  429. }
  430. }
  431. if (e != null)
  432. {
  433. throw e;
  434. }
  435. }
  436. }
  437. /// <summary>
  438. /// Class TranscodingJob
  439. /// </summary>
  440. public class TranscodingJob
  441. {
  442. /// <summary>
  443. /// Gets or sets the path.
  444. /// </summary>
  445. /// <value>The path.</value>
  446. public string Path { get; set; }
  447. /// <summary>
  448. /// Gets or sets the type.
  449. /// </summary>
  450. /// <value>The type.</value>
  451. public TranscodingJobType Type { get; set; }
  452. /// <summary>
  453. /// Gets or sets the process.
  454. /// </summary>
  455. /// <value>The process.</value>
  456. public Process Process { get; set; }
  457. /// <summary>
  458. /// Gets or sets the active request count.
  459. /// </summary>
  460. /// <value>The active request count.</value>
  461. public int ActiveRequestCount { get; set; }
  462. /// <summary>
  463. /// Gets or sets the kill timer.
  464. /// </summary>
  465. /// <value>The kill timer.</value>
  466. public Timer KillTimer { get; set; }
  467. public string DeviceId { get; set; }
  468. public CancellationTokenSource CancellationTokenSource { get; set; }
  469. public object ProcessLock = new object();
  470. public bool HasExited { get; set; }
  471. public string Id { get; set; }
  472. public float? Framerate { get; set; }
  473. public double? CompletionPercentage { get; set; }
  474. public long? BytesDownloaded { get; set; }
  475. public long? BytesTranscoded { get; set; }
  476. public long? TranscodingPositionTicks { get; set; }
  477. public long? DownloadPositionTicks { get; set; }
  478. public void DisposeKillTimer()
  479. {
  480. if (KillTimer != null)
  481. {
  482. KillTimer.Dispose();
  483. KillTimer = null;
  484. }
  485. }
  486. }
  487. /// <summary>
  488. /// Enum TranscodingJobType
  489. /// </summary>
  490. public enum TranscodingJobType
  491. {
  492. /// <summary>
  493. /// The progressive
  494. /// </summary>
  495. Progressive,
  496. /// <summary>
  497. /// The HLS
  498. /// </summary>
  499. Hls,
  500. /// <summary>
  501. /// The dash
  502. /// </summary>
  503. Dash
  504. }
  505. }