ApiEntryPoint.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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, KillTranscodingJob);
  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. /// <param name="sourcePath">The source path.</param>
  77. public void OnTranscodeBeginning(string path, TranscodingJobType type, Process process, bool isVideo, long? startTimeTicks, string sourcePath)
  78. {
  79. lock (_activeTranscodingJobs)
  80. {
  81. _activeTranscodingJobs.Add(new TranscodingJob
  82. {
  83. Type = type,
  84. Path = path,
  85. Process = process,
  86. ActiveRequestCount = 1,
  87. IsVideo = isVideo,
  88. StartTimeTicks = startTimeTicks,
  89. SourcePath = sourcePath
  90. });
  91. }
  92. }
  93. /// <summary>
  94. /// <summary>
  95. /// The progressive
  96. /// </summary>
  97. /// Called when [transcode failed to start].
  98. /// </summary>
  99. /// <param name="path">The path.</param>
  100. /// <param name="type">The type.</param>
  101. public void OnTranscodeFailedToStart(string path, TranscodingJobType type)
  102. {
  103. lock (_activeTranscodingJobs)
  104. {
  105. var job = _activeTranscodingJobs.First(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  106. _activeTranscodingJobs.Remove(job);
  107. }
  108. }
  109. /// <summary>
  110. /// Determines whether [has active transcoding job] [the specified path].
  111. /// </summary>
  112. /// <param name="path">The path.</param>
  113. /// <param name="type">The type.</param>
  114. /// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
  115. public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
  116. {
  117. lock (_activeTranscodingJobs)
  118. {
  119. return _activeTranscodingJobs.Any(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  120. }
  121. }
  122. /// <summary>
  123. /// Called when [transcode begin request].
  124. /// </summary>
  125. /// <param name="path">The path.</param>
  126. /// <param name="type">The type.</param>
  127. public void OnTranscodeBeginRequest(string path, TranscodingJobType type)
  128. {
  129. lock (_activeTranscodingJobs)
  130. {
  131. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  132. if (job == null)
  133. {
  134. return;
  135. }
  136. job.ActiveRequestCount++;
  137. if (job.KillTimer != null)
  138. {
  139. job.KillTimer.Dispose();
  140. job.KillTimer = null;
  141. }
  142. }
  143. }
  144. /// <summary>
  145. /// Called when [transcode end request].
  146. /// </summary>
  147. /// <param name="path">The path.</param>
  148. /// <param name="type">The type.</param>
  149. public void OnTranscodeEndRequest(string path, TranscodingJobType type)
  150. {
  151. lock (_activeTranscodingJobs)
  152. {
  153. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  154. if (job == null)
  155. {
  156. return;
  157. }
  158. job.ActiveRequestCount--;
  159. if (job.ActiveRequestCount == 0)
  160. {
  161. var timerDuration = type == TranscodingJobType.Progressive ? 1000 : 180000;
  162. if (job.KillTimer == null)
  163. {
  164. job.KillTimer = new Timer(OnTranscodeKillTimerStopped, job, timerDuration, Timeout.Infinite);
  165. }
  166. else
  167. {
  168. job.KillTimer.Change(timerDuration, Timeout.Infinite);
  169. }
  170. }
  171. }
  172. }
  173. /// <summary>
  174. /// Called when [transcode kill timer stopped].
  175. /// </summary>
  176. /// <param name="state">The state.</param>
  177. private void OnTranscodeKillTimerStopped(object state)
  178. {
  179. var job = (TranscodingJob)state;
  180. KillTranscodingJob(job);
  181. }
  182. /// <summary>
  183. /// Kills the single transcoding job.
  184. /// </summary>
  185. /// <param name="sourcePath">The source path.</param>
  186. internal void KillSingleTranscodingJob(string sourcePath)
  187. {
  188. if (string.IsNullOrEmpty(sourcePath))
  189. {
  190. throw new ArgumentNullException("sourcePath");
  191. }
  192. var jobs = new List<TranscodingJob>();
  193. lock (_activeTranscodingJobs)
  194. {
  195. // This is really only needed for HLS.
  196. // Progressive streams can stop on their own reliably
  197. jobs.AddRange(_activeTranscodingJobs.Where(i => string.Equals(sourcePath, i.SourcePath) && i.Type == TranscodingJobType.Hls));
  198. }
  199. // This method of killing is a bit of a shortcut, but it saves clients from having to send a request just for that
  200. // But we can only kill if there's one active job. If there are more we won't know which one to stop
  201. if (jobs.Count == 1)
  202. {
  203. KillTranscodingJob(jobs.First());
  204. }
  205. }
  206. /// <summary>
  207. /// Kills the transcoding job.
  208. /// </summary>
  209. /// <param name="job">The job.</param>
  210. private async void KillTranscodingJob(TranscodingJob job)
  211. {
  212. lock (_activeTranscodingJobs)
  213. {
  214. _activeTranscodingJobs.Remove(job);
  215. if (job.KillTimer != null)
  216. {
  217. job.KillTimer.Dispose();
  218. job.KillTimer = null;
  219. }
  220. }
  221. var process = job.Process;
  222. var hasExited = true;
  223. try
  224. {
  225. hasExited = process.HasExited;
  226. }
  227. catch (Exception ex)
  228. {
  229. Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
  230. }
  231. if (!hasExited)
  232. {
  233. try
  234. {
  235. Logger.Info("Killing ffmpeg process for {0}", job.Path);
  236. process.Kill();
  237. // Need to wait because killing is asynchronous
  238. process.WaitForExit(5000);
  239. }
  240. catch (Win32Exception ex)
  241. {
  242. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  243. }
  244. catch (InvalidOperationException ex)
  245. {
  246. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  247. }
  248. catch (NotSupportedException ex)
  249. {
  250. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  251. }
  252. }
  253. // Determine if it exited successfully
  254. var hasExitedSuccessfully = false;
  255. try
  256. {
  257. hasExitedSuccessfully = process.ExitCode == 0;
  258. }
  259. catch (InvalidOperationException)
  260. {
  261. }
  262. catch (NotSupportedException)
  263. {
  264. }
  265. // Dispose the process
  266. process.Dispose();
  267. // If it didn't complete successfully cleanup the partial files
  268. // Also don't cache output from resume points
  269. // Also don't cache video
  270. if (!hasExitedSuccessfully || job.StartTimeTicks.HasValue || job.IsVideo)
  271. {
  272. Logger.Info("Deleting partial stream file(s) {0}", job.Path);
  273. await Task.Delay(1000).ConfigureAwait(false);
  274. try
  275. {
  276. if (job.Type == TranscodingJobType.Progressive)
  277. {
  278. DeleteProgressivePartialStreamFiles(job.Path);
  279. }
  280. else
  281. {
  282. DeleteHlsPartialStreamFiles(job.Path);
  283. }
  284. }
  285. catch (IOException ex)
  286. {
  287. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, job.Path);
  288. }
  289. }
  290. }
  291. /// <summary>
  292. /// Deletes the progressive partial stream files.
  293. /// </summary>
  294. /// <param name="outputFilePath">The output file path.</param>
  295. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  296. {
  297. File.Delete(outputFilePath);
  298. }
  299. /// <summary>
  300. /// Deletes the HLS partial stream files.
  301. /// </summary>
  302. /// <param name="outputFilePath">The output file path.</param>
  303. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  304. {
  305. var directory = Path.GetDirectoryName(outputFilePath);
  306. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  307. var filesToDelete = Directory.EnumerateFiles(directory)
  308. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  309. .ToList();
  310. foreach (var file in filesToDelete)
  311. {
  312. try
  313. {
  314. Logger.Info("Deleting HLS file {0}", file);
  315. File.Delete(file);
  316. }
  317. catch (IOException ex)
  318. {
  319. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  320. }
  321. }
  322. }
  323. }
  324. /// <summary>
  325. /// Class TranscodingJob
  326. /// </summary>
  327. public class TranscodingJob
  328. {
  329. /// <summary>
  330. /// Gets or sets the path.
  331. /// </summary>
  332. /// <value>The path.</value>
  333. public string Path { get; set; }
  334. /// <summary>
  335. /// Gets or sets the type.
  336. /// </summary>
  337. /// <value>The type.</value>
  338. public TranscodingJobType Type { get; set; }
  339. /// <summary>
  340. /// Gets or sets the process.
  341. /// </summary>
  342. /// <value>The process.</value>
  343. public Process Process { get; set; }
  344. /// <summary>
  345. /// Gets or sets the active request count.
  346. /// </summary>
  347. /// <value>The active request count.</value>
  348. public int ActiveRequestCount { get; set; }
  349. /// <summary>
  350. /// Gets or sets the kill timer.
  351. /// </summary>
  352. /// <value>The kill timer.</value>
  353. public Timer KillTimer { get; set; }
  354. public bool IsVideo { get; set; }
  355. public long? StartTimeTicks { get; set; }
  356. public string SourcePath { get; set; }
  357. }
  358. /// <summary>
  359. /// Enum TranscodingJobType
  360. /// </summary>
  361. public enum TranscodingJobType
  362. {
  363. /// <summary>
  364. /// The progressive
  365. /// </summary>
  366. Progressive,
  367. /// <summary>
  368. /// The HLS
  369. /// </summary>
  370. Hls
  371. }
  372. }