ApiEntryPoint.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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, "*", SearchOption.AllDirectories)
  68. .ToList())
  69. {
  70. File.Delete(file);
  71. }
  72. }
  73. /// <summary>
  74. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  75. /// </summary>
  76. public void Dispose()
  77. {
  78. Dispose(true);
  79. GC.SuppressFinalize(this);
  80. }
  81. /// <summary>
  82. /// Releases unmanaged and - optionally - managed resources.
  83. /// </summary>
  84. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  85. protected virtual void Dispose(bool dispose)
  86. {
  87. var jobCount = _activeTranscodingJobs.Count;
  88. Parallel.ForEach(_activeTranscodingJobs.ToList(), KillTranscodingJob);
  89. // Try to allow for some time to kill the ffmpeg processes and delete the partial stream files
  90. if (jobCount > 0)
  91. {
  92. Thread.Sleep(1000);
  93. }
  94. }
  95. /// <summary>
  96. /// The active transcoding jobs
  97. /// </summary>
  98. private readonly List<TranscodingJob> _activeTranscodingJobs = new List<TranscodingJob>();
  99. /// <summary>
  100. /// Called when [transcode beginning].
  101. /// </summary>
  102. /// <param name="path">The path.</param>
  103. /// <param name="type">The type.</param>
  104. /// <param name="process">The process.</param>
  105. /// <param name="startTimeTicks">The start time ticks.</param>
  106. /// <param name="sourcePath">The source path.</param>
  107. /// <param name="deviceId">The device id.</param>
  108. public void OnTranscodeBeginning(string path, TranscodingJobType type, Process process, long? startTimeTicks, string sourcePath, string deviceId)
  109. {
  110. lock (_activeTranscodingJobs)
  111. {
  112. _activeTranscodingJobs.Add(new TranscodingJob
  113. {
  114. Type = type,
  115. Path = path,
  116. Process = process,
  117. ActiveRequestCount = 1,
  118. StartTimeTicks = startTimeTicks,
  119. SourcePath = sourcePath,
  120. DeviceId = deviceId
  121. });
  122. }
  123. }
  124. /// <summary>
  125. /// <summary>
  126. /// The progressive
  127. /// </summary>
  128. /// Called when [transcode failed to start].
  129. /// </summary>
  130. /// <param name="path">The path.</param>
  131. /// <param name="type">The type.</param>
  132. public void OnTranscodeFailedToStart(string path, TranscodingJobType type)
  133. {
  134. lock (_activeTranscodingJobs)
  135. {
  136. var job = _activeTranscodingJobs.First(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  137. _activeTranscodingJobs.Remove(job);
  138. }
  139. }
  140. /// <summary>
  141. /// Determines whether [has active transcoding job] [the specified path].
  142. /// </summary>
  143. /// <param name="path">The path.</param>
  144. /// <param name="type">The type.</param>
  145. /// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
  146. public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
  147. {
  148. lock (_activeTranscodingJobs)
  149. {
  150. return _activeTranscodingJobs.Any(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  151. }
  152. }
  153. /// <summary>
  154. /// Called when [transcode begin request].
  155. /// </summary>
  156. /// <param name="path">The path.</param>
  157. /// <param name="type">The type.</param>
  158. public void OnTranscodeBeginRequest(string path, TranscodingJobType type)
  159. {
  160. lock (_activeTranscodingJobs)
  161. {
  162. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  163. if (job == null)
  164. {
  165. return;
  166. }
  167. job.ActiveRequestCount++;
  168. if (job.KillTimer != null)
  169. {
  170. job.KillTimer.Dispose();
  171. job.KillTimer = null;
  172. }
  173. }
  174. }
  175. /// <summary>
  176. /// Called when [transcode end request].
  177. /// </summary>
  178. /// <param name="path">The path.</param>
  179. /// <param name="type">The type.</param>
  180. public void OnTranscodeEndRequest(string path, TranscodingJobType type)
  181. {
  182. lock (_activeTranscodingJobs)
  183. {
  184. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  185. if (job == null)
  186. {
  187. return;
  188. }
  189. job.ActiveRequestCount--;
  190. if (job.ActiveRequestCount == 0)
  191. {
  192. // The HLS kill timer is long - 1/2 hr. clients should use the manual kill command when stopping.
  193. var timerDuration = type == TranscodingJobType.Progressive ? 1000 : 1800000;
  194. if (job.KillTimer == null)
  195. {
  196. job.KillTimer = new Timer(OnTranscodeKillTimerStopped, job, timerDuration, Timeout.Infinite);
  197. }
  198. else
  199. {
  200. job.KillTimer.Change(timerDuration, Timeout.Infinite);
  201. }
  202. }
  203. }
  204. }
  205. /// <summary>
  206. /// Called when [transcode kill timer stopped].
  207. /// </summary>
  208. /// <param name="state">The state.</param>
  209. private void OnTranscodeKillTimerStopped(object state)
  210. {
  211. var job = (TranscodingJob)state;
  212. KillTranscodingJob(job);
  213. }
  214. /// <summary>
  215. /// Kills the single transcoding job.
  216. /// </summary>
  217. /// <param name="deviceId">The device id.</param>
  218. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  219. /// <exception cref="System.ArgumentNullException">sourcePath</exception>
  220. internal void KillTranscodingJobs(string deviceId, bool isVideo)
  221. {
  222. if (string.IsNullOrEmpty(deviceId))
  223. {
  224. throw new ArgumentNullException("deviceId");
  225. }
  226. var jobs = new List<TranscodingJob>();
  227. lock (_activeTranscodingJobs)
  228. {
  229. // This is really only needed for HLS.
  230. // Progressive streams can stop on their own reliably
  231. jobs.AddRange(_activeTranscodingJobs.Where(i => string.Equals(deviceId, i.DeviceId, StringComparison.OrdinalIgnoreCase)));
  232. }
  233. foreach (var job in jobs)
  234. {
  235. KillTranscodingJob(job);
  236. }
  237. }
  238. /// <summary>
  239. /// Kills the transcoding job.
  240. /// </summary>
  241. /// <param name="job">The job.</param>
  242. private void KillTranscodingJob(TranscodingJob job)
  243. {
  244. lock (_activeTranscodingJobs)
  245. {
  246. _activeTranscodingJobs.Remove(job);
  247. if (job.KillTimer != null)
  248. {
  249. job.KillTimer.Dispose();
  250. job.KillTimer = null;
  251. }
  252. }
  253. var process = job.Process;
  254. var hasExited = true;
  255. try
  256. {
  257. hasExited = process.HasExited;
  258. }
  259. catch (Exception ex)
  260. {
  261. Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
  262. }
  263. if (!hasExited)
  264. {
  265. try
  266. {
  267. Logger.Info("Killing ffmpeg process for {0}", job.Path);
  268. process.Kill();
  269. // Need to wait because killing is asynchronous
  270. process.WaitForExit(5000);
  271. }
  272. catch (Win32Exception ex)
  273. {
  274. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  275. }
  276. catch (InvalidOperationException ex)
  277. {
  278. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  279. }
  280. catch (NotSupportedException ex)
  281. {
  282. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  283. }
  284. }
  285. // Dispose the process
  286. process.Dispose();
  287. DeletePartialStreamFiles(job.Path, job.Type, 0, 1500);
  288. }
  289. private async void DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
  290. {
  291. if (retryCount >= 10)
  292. {
  293. return;
  294. }
  295. Logger.Info("Deleting partial stream file(s) {0}", path);
  296. await Task.Delay(delayMs).ConfigureAwait(false);
  297. try
  298. {
  299. if (jobType == TranscodingJobType.Progressive)
  300. {
  301. DeleteProgressivePartialStreamFiles(path);
  302. }
  303. else
  304. {
  305. DeleteHlsPartialStreamFiles(path);
  306. }
  307. }
  308. catch (IOException ex)
  309. {
  310. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  311. DeletePartialStreamFiles(path, jobType, retryCount + 1, 500);
  312. }
  313. catch (Exception ex)
  314. {
  315. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  316. }
  317. }
  318. /// <summary>
  319. /// Deletes the progressive partial stream files.
  320. /// </summary>
  321. /// <param name="outputFilePath">The output file path.</param>
  322. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  323. {
  324. File.Delete(outputFilePath);
  325. }
  326. /// <summary>
  327. /// Deletes the HLS partial stream files.
  328. /// </summary>
  329. /// <param name="outputFilePath">The output file path.</param>
  330. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  331. {
  332. var directory = Path.GetDirectoryName(outputFilePath);
  333. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  334. var filesToDelete = Directory.EnumerateFiles(directory)
  335. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  336. .ToList();
  337. foreach (var file in filesToDelete)
  338. {
  339. try
  340. {
  341. Logger.Info("Deleting HLS file {0}", file);
  342. File.Delete(file);
  343. }
  344. catch (IOException ex)
  345. {
  346. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  347. }
  348. }
  349. }
  350. }
  351. /// <summary>
  352. /// Class TranscodingJob
  353. /// </summary>
  354. public class TranscodingJob
  355. {
  356. /// <summary>
  357. /// Gets or sets the path.
  358. /// </summary>
  359. /// <value>The path.</value>
  360. public string Path { get; set; }
  361. /// <summary>
  362. /// Gets or sets the type.
  363. /// </summary>
  364. /// <value>The type.</value>
  365. public TranscodingJobType Type { get; set; }
  366. /// <summary>
  367. /// Gets or sets the process.
  368. /// </summary>
  369. /// <value>The process.</value>
  370. public Process Process { get; set; }
  371. /// <summary>
  372. /// Gets or sets the active request count.
  373. /// </summary>
  374. /// <value>The active request count.</value>
  375. public int ActiveRequestCount { get; set; }
  376. /// <summary>
  377. /// Gets or sets the kill timer.
  378. /// </summary>
  379. /// <value>The kill timer.</value>
  380. public Timer KillTimer { get; set; }
  381. public long? StartTimeTicks { get; set; }
  382. public string SourcePath { get; set; }
  383. public string DeviceId { get; set; }
  384. }
  385. /// <summary>
  386. /// Enum TranscodingJobType
  387. /// </summary>
  388. public enum TranscodingJobType
  389. {
  390. /// <summary>
  391. /// The progressive
  392. /// </summary>
  393. Progressive,
  394. /// <summary>
  395. /// The HLS
  396. /// </summary>
  397. Hls
  398. }
  399. }