ApiEntryPoint.cs 17 KB

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