ApiEntryPoint.cs 19 KB

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