ApiEntryPoint.cs 14 KB

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