ApiEntryPoint.cs 19 KB

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