ApiEntryPoint.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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 MediaBrowser.Model.Session;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Api
  15. {
  16. /// <summary>
  17. /// Class ServerEntryPoint
  18. /// </summary>
  19. public class ApiEntryPoint : IServerEntryPoint
  20. {
  21. /// <summary>
  22. /// The instance
  23. /// </summary>
  24. public static ApiEntryPoint Instance;
  25. /// <summary>
  26. /// Gets or sets the logger.
  27. /// </summary>
  28. /// <value>The logger.</value>
  29. private ILogger Logger { get; set; }
  30. /// <summary>
  31. /// The application paths
  32. /// </summary>
  33. private readonly IServerApplicationPaths _appPaths;
  34. private readonly ISessionManager _sessionManager;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="ApiEntryPoint" /> class.
  37. /// </summary>
  38. /// <param name="logger">The logger.</param>
  39. /// <param name="appPaths">The application paths.</param>
  40. /// <param name="sessionManager">The session manager.</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(), j => KillTranscodingJob(j, FileDeleteMode.All));
  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="deviceId">The device id.</param>
  110. /// <param name="state">The state.</param>
  111. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  112. public void OnTranscodeBeginning(string path,
  113. TranscodingJobType type,
  114. Process process,
  115. string deviceId,
  116. StreamState state,
  117. CancellationTokenSource cancellationTokenSource)
  118. {
  119. lock (_activeTranscodingJobs)
  120. {
  121. _activeTranscodingJobs.Add(new TranscodingJob
  122. {
  123. Type = type,
  124. Path = path,
  125. Process = process,
  126. ActiveRequestCount = 1,
  127. DeviceId = deviceId,
  128. CancellationTokenSource = cancellationTokenSource
  129. });
  130. ReportTranscodingProgress(state, null, null);
  131. }
  132. }
  133. public void ReportTranscodingProgress(StreamState state, float? framerate, double? percentComplete)
  134. {
  135. var deviceId = state.Request.DeviceId;
  136. if (!string.IsNullOrWhiteSpace(deviceId))
  137. {
  138. var audioCodec = state.Request.AudioCodec;
  139. var videoCodec = state.VideoRequest == null ? null : state.VideoRequest.VideoCodec;
  140. if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase) ||
  141. string.IsNullOrEmpty(audioCodec))
  142. {
  143. audioCodec = state.OutputAudioCodec;
  144. }
  145. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) ||
  146. string.IsNullOrEmpty(videoCodec))
  147. {
  148. videoCodec = state.OutputVideoCodec;
  149. }
  150. _sessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
  151. {
  152. Bitrate = state.TotalOutputBitrate,
  153. AudioCodec = audioCodec,
  154. VideoCodec = videoCodec,
  155. Container = state.OutputContainer,
  156. Framerate = framerate,
  157. CompletionPercentage = percentComplete,
  158. Width = state.OutputWidth,
  159. Height = state.OutputHeight,
  160. AudioChannels = state.OutputAudioChannels
  161. });
  162. }
  163. }
  164. /// <summary>
  165. /// <summary>
  166. /// The progressive
  167. /// </summary>
  168. /// Called when [transcode failed to start].
  169. /// </summary>
  170. /// <param name="path">The path.</param>
  171. /// <param name="type">The type.</param>
  172. /// <param name="state">The state.</param>
  173. public void OnTranscodeFailedToStart(string path, TranscodingJobType type, StreamState state)
  174. {
  175. lock (_activeTranscodingJobs)
  176. {
  177. var job = _activeTranscodingJobs.First(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  178. _activeTranscodingJobs.Remove(job);
  179. }
  180. if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
  181. {
  182. _sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
  183. }
  184. }
  185. /// <summary>
  186. /// Determines whether [has active transcoding job] [the specified path].
  187. /// </summary>
  188. /// <param name="path">The path.</param>
  189. /// <param name="type">The type.</param>
  190. /// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
  191. public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
  192. {
  193. return GetTranscodingJob(path, type) != null;
  194. }
  195. public TranscodingJob GetTranscodingJob(string path, TranscodingJobType type)
  196. {
  197. lock (_activeTranscodingJobs)
  198. {
  199. return _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  200. }
  201. }
  202. /// <summary>
  203. /// Called when [transcode begin request].
  204. /// </summary>
  205. /// <param name="path">The path.</param>
  206. /// <param name="type">The type.</param>
  207. public void OnTranscodeBeginRequest(string path, TranscodingJobType type)
  208. {
  209. lock (_activeTranscodingJobs)
  210. {
  211. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  212. if (job == null)
  213. {
  214. return;
  215. }
  216. job.ActiveRequestCount++;
  217. if (job.KillTimer != null)
  218. {
  219. job.KillTimer.Dispose();
  220. job.KillTimer = null;
  221. }
  222. }
  223. }
  224. /// <summary>
  225. /// Called when [transcode end request].
  226. /// </summary>
  227. /// <param name="path">The path.</param>
  228. /// <param name="type">The type.</param>
  229. public void OnTranscodeEndRequest(string path, TranscodingJobType type)
  230. {
  231. lock (_activeTranscodingJobs)
  232. {
  233. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  234. if (job == null)
  235. {
  236. return;
  237. }
  238. job.ActiveRequestCount--;
  239. if (job.ActiveRequestCount == 0)
  240. {
  241. // The HLS kill timer is long - 1/2 hr. clients should use the manual kill command when stopping.
  242. var timerDuration = type == TranscodingJobType.Progressive ? 1000 : 1800000;
  243. if (job.KillTimer == null)
  244. {
  245. job.KillTimer = new Timer(OnTranscodeKillTimerStopped, job, timerDuration, Timeout.Infinite);
  246. }
  247. else
  248. {
  249. job.KillTimer.Change(timerDuration, Timeout.Infinite);
  250. }
  251. }
  252. }
  253. }
  254. /// <summary>
  255. /// Called when [transcode kill timer stopped].
  256. /// </summary>
  257. /// <param name="state">The state.</param>
  258. private void OnTranscodeKillTimerStopped(object state)
  259. {
  260. var job = (TranscodingJob)state;
  261. KillTranscodingJob(job, FileDeleteMode.All);
  262. }
  263. /// <summary>
  264. /// Kills the single transcoding job.
  265. /// </summary>
  266. /// <param name="deviceId">The device id.</param>
  267. /// <param name="deleteMode">The delete mode.</param>
  268. /// <exception cref="System.ArgumentNullException">sourcePath</exception>
  269. internal void KillTranscodingJobs(string deviceId, FileDeleteMode deleteMode)
  270. {
  271. if (string.IsNullOrEmpty(deviceId))
  272. {
  273. throw new ArgumentNullException("deviceId");
  274. }
  275. var jobs = new List<TranscodingJob>();
  276. lock (_activeTranscodingJobs)
  277. {
  278. // This is really only needed for HLS.
  279. // Progressive streams can stop on their own reliably
  280. jobs.AddRange(_activeTranscodingJobs.Where(i => string.Equals(deviceId, i.DeviceId, StringComparison.OrdinalIgnoreCase)));
  281. }
  282. foreach (var job in jobs)
  283. {
  284. KillTranscodingJob(job, deleteMode);
  285. }
  286. }
  287. /// <summary>
  288. /// Kills the transcoding jobs.
  289. /// </summary>
  290. /// <param name="deviceId">The device identifier.</param>
  291. /// <param name="outputPath">The output path.</param>
  292. /// <param name="deleteMode">The delete mode.</param>
  293. /// <exception cref="System.ArgumentNullException">deviceId</exception>
  294. internal void KillTranscodingJobs(string deviceId, string outputPath, FileDeleteMode deleteMode)
  295. {
  296. if (string.IsNullOrEmpty(deviceId))
  297. {
  298. throw new ArgumentNullException("deviceId");
  299. }
  300. var jobs = new List<TranscodingJob>();
  301. lock (_activeTranscodingJobs)
  302. {
  303. // This is really only needed for HLS.
  304. // Progressive streams can stop on their own reliably
  305. jobs.AddRange(_activeTranscodingJobs.Where(i => string.Equals(deviceId, i.DeviceId, StringComparison.OrdinalIgnoreCase) && string.Equals(outputPath, i.Path, StringComparison.OrdinalIgnoreCase)));
  306. }
  307. foreach (var job in jobs)
  308. {
  309. KillTranscodingJob(job, deleteMode);
  310. }
  311. }
  312. /// <summary>
  313. /// Kills the transcoding job.
  314. /// </summary>
  315. /// <param name="job">The job.</param>
  316. /// <param name="deleteMode">The delete mode.</param>
  317. private void KillTranscodingJob(TranscodingJob job, FileDeleteMode deleteMode)
  318. {
  319. lock (_activeTranscodingJobs)
  320. {
  321. _activeTranscodingJobs.Remove(job);
  322. if (!job.CancellationTokenSource.IsCancellationRequested)
  323. {
  324. job.CancellationTokenSource.Cancel();
  325. }
  326. if (job.KillTimer != null)
  327. {
  328. job.KillTimer.Dispose();
  329. job.KillTimer = null;
  330. }
  331. }
  332. lock (job.ProcessLock)
  333. {
  334. var process = job.Process;
  335. var hasExited = true;
  336. try
  337. {
  338. hasExited = process.HasExited;
  339. }
  340. catch (Exception ex)
  341. {
  342. Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
  343. }
  344. if (!hasExited)
  345. {
  346. try
  347. {
  348. Logger.Info("Killing ffmpeg process for {0}", job.Path);
  349. //process.Kill();
  350. process.StandardInput.WriteLine("q");
  351. // Need to wait because killing is asynchronous
  352. process.WaitForExit(5000);
  353. }
  354. catch (Exception ex)
  355. {
  356. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  357. }
  358. }
  359. }
  360. if (deleteMode == FileDeleteMode.All)
  361. {
  362. DeletePartialStreamFiles(job.Path, job.Type, 0, 1500);
  363. }
  364. }
  365. private async void DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
  366. {
  367. if (retryCount >= 10)
  368. {
  369. return;
  370. }
  371. Logger.Info("Deleting partial stream file(s) {0}", path);
  372. await Task.Delay(delayMs).ConfigureAwait(false);
  373. try
  374. {
  375. if (jobType == TranscodingJobType.Progressive)
  376. {
  377. DeleteProgressivePartialStreamFiles(path);
  378. }
  379. else
  380. {
  381. DeleteHlsPartialStreamFiles(path);
  382. }
  383. }
  384. catch (IOException ex)
  385. {
  386. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  387. DeletePartialStreamFiles(path, jobType, retryCount + 1, 500);
  388. }
  389. catch (Exception ex)
  390. {
  391. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  392. }
  393. }
  394. /// <summary>
  395. /// Deletes the progressive partial stream files.
  396. /// </summary>
  397. /// <param name="outputFilePath">The output file path.</param>
  398. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  399. {
  400. File.Delete(outputFilePath);
  401. }
  402. /// <summary>
  403. /// Deletes the HLS partial stream files.
  404. /// </summary>
  405. /// <param name="outputFilePath">The output file path.</param>
  406. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  407. {
  408. var directory = Path.GetDirectoryName(outputFilePath);
  409. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  410. var filesToDelete = Directory.EnumerateFiles(directory)
  411. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  412. .ToList();
  413. Exception e = null;
  414. foreach (var file in filesToDelete)
  415. {
  416. try
  417. {
  418. Logger.Info("Deleting HLS file {0}", file);
  419. File.Delete(file);
  420. }
  421. catch (IOException ex)
  422. {
  423. e = ex;
  424. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  425. }
  426. }
  427. if (e != null)
  428. {
  429. throw e;
  430. }
  431. }
  432. }
  433. /// <summary>
  434. /// Class TranscodingJob
  435. /// </summary>
  436. public class TranscodingJob
  437. {
  438. /// <summary>
  439. /// Gets or sets the path.
  440. /// </summary>
  441. /// <value>The path.</value>
  442. public string Path { get; set; }
  443. /// <summary>
  444. /// Gets or sets the type.
  445. /// </summary>
  446. /// <value>The type.</value>
  447. public TranscodingJobType Type { get; set; }
  448. /// <summary>
  449. /// Gets or sets the process.
  450. /// </summary>
  451. /// <value>The process.</value>
  452. public Process Process { get; set; }
  453. /// <summary>
  454. /// Gets or sets the active request count.
  455. /// </summary>
  456. /// <value>The active request count.</value>
  457. public int ActiveRequestCount { get; set; }
  458. /// <summary>
  459. /// Gets or sets the kill timer.
  460. /// </summary>
  461. /// <value>The kill timer.</value>
  462. public Timer KillTimer { get; set; }
  463. public string DeviceId { get; set; }
  464. public CancellationTokenSource CancellationTokenSource { get; set; }
  465. public object ProcessLock = new object();
  466. public bool HasExited { get; set; }
  467. }
  468. /// <summary>
  469. /// Enum TranscodingJobType
  470. /// </summary>
  471. public enum TranscodingJobType
  472. {
  473. /// <summary>
  474. /// The progressive
  475. /// </summary>
  476. Progressive,
  477. /// <summary>
  478. /// The HLS
  479. /// </summary>
  480. Hls
  481. }
  482. public enum FileDeleteMode
  483. {
  484. None,
  485. All
  486. }
  487. }