ApiEntryPoint.cs 12 KB

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