2
0

ApiEntryPoint.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Controller.Plugins;
  3. using MediaBrowser.Controller.Resolvers;
  4. using MediaBrowser.Model.Logging;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Api
  14. {
  15. /// <summary>
  16. /// Class ServerEntryPoint
  17. /// </summary>
  18. public class ApiEntryPoint : IServerEntryPoint
  19. {
  20. /// <summary>
  21. /// The instance
  22. /// </summary>
  23. public static ApiEntryPoint Instance;
  24. /// <summary>
  25. /// Gets or sets the logger.
  26. /// </summary>
  27. /// <value>The logger.</value>
  28. private ILogger Logger { get; set; }
  29. /// <summary>
  30. /// The application paths
  31. /// </summary>
  32. private readonly IServerApplicationPaths _appPaths;
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="ApiEntryPoint" /> class.
  35. /// </summary>
  36. /// <param name="logger">The logger.</param>
  37. /// <param name="appPaths">The application paths.</param>
  38. public ApiEntryPoint(ILogger logger, IServerApplicationPaths appPaths)
  39. {
  40. Logger = logger;
  41. _appPaths = appPaths;
  42. Instance = this;
  43. }
  44. /// <summary>
  45. /// Runs this instance.
  46. /// </summary>
  47. public void Run()
  48. {
  49. try
  50. {
  51. DeleteEncodedMediaCache();
  52. }
  53. catch (DirectoryNotFoundException)
  54. {
  55. // Don't clutter the log
  56. }
  57. catch (IOException ex)
  58. {
  59. Logger.ErrorException("Error deleting encoded media cache", ex);
  60. }
  61. }
  62. /// <summary>
  63. /// Deletes the encoded media cache.
  64. /// </summary>
  65. private void DeleteEncodedMediaCache()
  66. {
  67. foreach (var file in Directory.EnumerateFiles(_appPaths.TranscodingTempPath)
  68. .Where(i => EntityResolutionHelper.VideoFileExtensions.Contains(Path.GetExtension(i)))
  69. .ToList())
  70. {
  71. File.Delete(file);
  72. }
  73. }
  74. /// <summary>
  75. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  76. /// </summary>
  77. public void Dispose()
  78. {
  79. Dispose(true);
  80. GC.SuppressFinalize(this);
  81. }
  82. /// <summary>
  83. /// Releases unmanaged and - optionally - managed resources.
  84. /// </summary>
  85. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  86. protected virtual void Dispose(bool dispose)
  87. {
  88. var jobCount = _activeTranscodingJobs.Count;
  89. Parallel.ForEach(_activeTranscodingJobs.ToList(), KillTranscodingJob);
  90. // Try to allow for some time to kill the ffmpeg processes and delete the partial stream files
  91. if (jobCount > 0)
  92. {
  93. Thread.Sleep(1000);
  94. }
  95. }
  96. /// <summary>
  97. /// The active transcoding jobs
  98. /// </summary>
  99. private readonly List<TranscodingJob> _activeTranscodingJobs = new List<TranscodingJob>();
  100. /// <summary>
  101. /// Called when [transcode beginning].
  102. /// </summary>
  103. /// <param name="path">The path.</param>
  104. /// <param name="type">The type.</param>
  105. /// <param name="process">The process.</param>
  106. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  107. /// <param name="startTimeTicks">The start time ticks.</param>
  108. /// <param name="sourcePath">The source path.</param>
  109. /// <param name="deviceId">The device id.</param>
  110. public void OnTranscodeBeginning(string path, TranscodingJobType type, Process process, bool isVideo, long? startTimeTicks, string sourcePath, string deviceId)
  111. {
  112. lock (_activeTranscodingJobs)
  113. {
  114. _activeTranscodingJobs.Add(new TranscodingJob
  115. {
  116. Type = type,
  117. Path = path,
  118. Process = process,
  119. ActiveRequestCount = 1,
  120. IsVideo = isVideo,
  121. StartTimeTicks = startTimeTicks,
  122. SourcePath = sourcePath,
  123. DeviceId = deviceId
  124. });
  125. }
  126. }
  127. /// <summary>
  128. /// <summary>
  129. /// The progressive
  130. /// </summary>
  131. /// Called when [transcode failed to start].
  132. /// </summary>
  133. /// <param name="path">The path.</param>
  134. /// <param name="type">The type.</param>
  135. public void OnTranscodeFailedToStart(string path, TranscodingJobType type)
  136. {
  137. lock (_activeTranscodingJobs)
  138. {
  139. var job = _activeTranscodingJobs.First(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  140. _activeTranscodingJobs.Remove(job);
  141. }
  142. }
  143. /// <summary>
  144. /// Determines whether [has active transcoding job] [the specified path].
  145. /// </summary>
  146. /// <param name="path">The path.</param>
  147. /// <param name="type">The type.</param>
  148. /// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
  149. public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
  150. {
  151. lock (_activeTranscodingJobs)
  152. {
  153. return _activeTranscodingJobs.Any(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  154. }
  155. }
  156. /// <summary>
  157. /// Called when [transcode begin request].
  158. /// </summary>
  159. /// <param name="path">The path.</param>
  160. /// <param name="type">The type.</param>
  161. public void OnTranscodeBeginRequest(string path, TranscodingJobType type)
  162. {
  163. lock (_activeTranscodingJobs)
  164. {
  165. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  166. if (job == null)
  167. {
  168. return;
  169. }
  170. job.ActiveRequestCount++;
  171. if (job.KillTimer != null)
  172. {
  173. job.KillTimer.Dispose();
  174. job.KillTimer = null;
  175. }
  176. }
  177. }
  178. /// <summary>
  179. /// Called when [transcode end request].
  180. /// </summary>
  181. /// <param name="path">The path.</param>
  182. /// <param name="type">The type.</param>
  183. public void OnTranscodeEndRequest(string path, TranscodingJobType type)
  184. {
  185. lock (_activeTranscodingJobs)
  186. {
  187. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  188. if (job == null)
  189. {
  190. return;
  191. }
  192. job.ActiveRequestCount--;
  193. if (job.ActiveRequestCount == 0)
  194. {
  195. // The HLS kill timer is long - 1/2 hr. clients should use the manual kill command when stopping.
  196. var timerDuration = type == TranscodingJobType.Progressive ? 1000 : 1800000;
  197. if (job.KillTimer == null)
  198. {
  199. job.KillTimer = new Timer(OnTranscodeKillTimerStopped, job, timerDuration, Timeout.Infinite);
  200. }
  201. else
  202. {
  203. job.KillTimer.Change(timerDuration, Timeout.Infinite);
  204. }
  205. }
  206. }
  207. }
  208. /// <summary>
  209. /// Called when [transcode kill timer stopped].
  210. /// </summary>
  211. /// <param name="state">The state.</param>
  212. private void OnTranscodeKillTimerStopped(object state)
  213. {
  214. var job = (TranscodingJob)state;
  215. KillTranscodingJob(job);
  216. }
  217. /// <summary>
  218. /// Kills the single transcoding job.
  219. /// </summary>
  220. /// <param name="deviceId">The device id.</param>
  221. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  222. /// <exception cref="System.ArgumentNullException">sourcePath</exception>
  223. internal void KillTranscodingJobs(string deviceId, bool isVideo)
  224. {
  225. if (string.IsNullOrEmpty(deviceId))
  226. {
  227. throw new ArgumentNullException("deviceId");
  228. }
  229. var jobs = new List<TranscodingJob>();
  230. lock (_activeTranscodingJobs)
  231. {
  232. // This is really only needed for HLS.
  233. // Progressive streams can stop on their own reliably
  234. jobs.AddRange(_activeTranscodingJobs.Where(i => isVideo == i.IsVideo && string.Equals(deviceId, i.DeviceId, StringComparison.OrdinalIgnoreCase)));
  235. }
  236. foreach (var job in jobs)
  237. {
  238. KillTranscodingJob(job);
  239. }
  240. }
  241. /// <summary>
  242. /// Kills the transcoding job.
  243. /// </summary>
  244. /// <param name="job">The job.</param>
  245. private void KillTranscodingJob(TranscodingJob job)
  246. {
  247. lock (_activeTranscodingJobs)
  248. {
  249. _activeTranscodingJobs.Remove(job);
  250. if (job.KillTimer != null)
  251. {
  252. job.KillTimer.Dispose();
  253. job.KillTimer = null;
  254. }
  255. }
  256. var process = job.Process;
  257. var hasExited = true;
  258. try
  259. {
  260. hasExited = process.HasExited;
  261. }
  262. catch (Exception ex)
  263. {
  264. Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
  265. }
  266. if (!hasExited)
  267. {
  268. try
  269. {
  270. Logger.Info("Killing ffmpeg process for {0}", job.Path);
  271. process.Kill();
  272. // Need to wait because killing is asynchronous
  273. process.WaitForExit(5000);
  274. }
  275. catch (Win32Exception ex)
  276. {
  277. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  278. }
  279. catch (InvalidOperationException ex)
  280. {
  281. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  282. }
  283. catch (NotSupportedException ex)
  284. {
  285. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  286. }
  287. }
  288. // Determine if it exited successfully
  289. var hasExitedSuccessfully = false;
  290. try
  291. {
  292. hasExitedSuccessfully = process.ExitCode == 0;
  293. }
  294. catch (InvalidOperationException)
  295. {
  296. }
  297. catch (NotSupportedException)
  298. {
  299. }
  300. // Dispose the process
  301. process.Dispose();
  302. // If it didn't complete successfully cleanup the partial files
  303. // Also don't cache output from resume points
  304. // Also don't cache video
  305. if (!hasExitedSuccessfully || job.StartTimeTicks.HasValue || job.IsVideo)
  306. {
  307. DeletePartialStreamFiles(job.Path, job.Type, 0, 1500);
  308. }
  309. }
  310. private async void DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
  311. {
  312. if (retryCount >= 5)
  313. {
  314. return;
  315. }
  316. Logger.Info("Deleting partial stream file(s) {0}", path);
  317. await Task.Delay(delayMs).ConfigureAwait(false);
  318. try
  319. {
  320. if (jobType == TranscodingJobType.Progressive)
  321. {
  322. DeleteProgressivePartialStreamFiles(path);
  323. }
  324. else
  325. {
  326. DeleteHlsPartialStreamFiles(path);
  327. }
  328. }
  329. catch (IOException ex)
  330. {
  331. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  332. DeletePartialStreamFiles(path, jobType, retryCount + 1, 500);
  333. }
  334. catch (Exception ex)
  335. {
  336. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  337. }
  338. }
  339. /// <summary>
  340. /// Deletes the progressive partial stream files.
  341. /// </summary>
  342. /// <param name="outputFilePath">The output file path.</param>
  343. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  344. {
  345. File.Delete(outputFilePath);
  346. }
  347. /// <summary>
  348. /// Deletes the HLS partial stream files.
  349. /// </summary>
  350. /// <param name="outputFilePath">The output file path.</param>
  351. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  352. {
  353. var directory = Path.GetDirectoryName(outputFilePath);
  354. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  355. var filesToDelete = Directory.EnumerateFiles(directory)
  356. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  357. .ToList();
  358. foreach (var file in filesToDelete)
  359. {
  360. try
  361. {
  362. Logger.Info("Deleting HLS file {0}", file);
  363. File.Delete(file);
  364. }
  365. catch (IOException ex)
  366. {
  367. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  368. }
  369. }
  370. }
  371. }
  372. /// <summary>
  373. /// Class TranscodingJob
  374. /// </summary>
  375. public class TranscodingJob
  376. {
  377. /// <summary>
  378. /// Gets or sets the path.
  379. /// </summary>
  380. /// <value>The path.</value>
  381. public string Path { get; set; }
  382. /// <summary>
  383. /// Gets or sets the type.
  384. /// </summary>
  385. /// <value>The type.</value>
  386. public TranscodingJobType Type { get; set; }
  387. /// <summary>
  388. /// Gets or sets the process.
  389. /// </summary>
  390. /// <value>The process.</value>
  391. public Process Process { get; set; }
  392. /// <summary>
  393. /// Gets or sets the active request count.
  394. /// </summary>
  395. /// <value>The active request count.</value>
  396. public int ActiveRequestCount { get; set; }
  397. /// <summary>
  398. /// Gets or sets the kill timer.
  399. /// </summary>
  400. /// <value>The kill timer.</value>
  401. public Timer KillTimer { get; set; }
  402. public bool IsVideo { get; set; }
  403. public long? StartTimeTicks { get; set; }
  404. public string SourcePath { get; set; }
  405. public string DeviceId { get; set; }
  406. }
  407. /// <summary>
  408. /// Enum TranscodingJobType
  409. /// </summary>
  410. public enum TranscodingJobType
  411. {
  412. /// <summary>
  413. /// The progressive
  414. /// </summary>
  415. Progressive,
  416. /// <summary>
  417. /// The HLS
  418. /// </summary>
  419. Hls
  420. }
  421. }