ApiEntryPoint.cs 18 KB

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