BaseStreamingService.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.Implementations.HttpServer;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Model.Drawing;
  8. using MediaBrowser.Model.Dto;
  9. using MediaBrowser.Model.Entities;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.ComponentModel;
  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.Playback
  19. {
  20. /// <summary>
  21. /// Class BaseStreamingService
  22. /// </summary>
  23. public abstract class BaseStreamingService : BaseRestService
  24. {
  25. /// <summary>
  26. /// Gets or sets the application paths.
  27. /// </summary>
  28. /// <value>The application paths.</value>
  29. protected IServerApplicationPaths ApplicationPaths { get; set; }
  30. /// <summary>
  31. /// Gets the server kernel.
  32. /// </summary>
  33. /// <value>The server kernel.</value>
  34. protected Kernel ServerKernel
  35. {
  36. get { return Kernel as Kernel; }
  37. }
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  40. /// </summary>
  41. /// <param name="appPaths">The app paths.</param>
  42. protected BaseStreamingService(IServerApplicationPaths appPaths)
  43. {
  44. ApplicationPaths = appPaths;
  45. }
  46. /// <summary>
  47. /// Gets the command line arguments.
  48. /// </summary>
  49. /// <param name="outputPath">The output path.</param>
  50. /// <param name="state">The state.</param>
  51. /// <returns>System.String.</returns>
  52. protected abstract string GetCommandLineArguments(string outputPath, StreamState state);
  53. /// <summary>
  54. /// Gets the type of the transcoding job.
  55. /// </summary>
  56. /// <value>The type of the transcoding job.</value>
  57. protected abstract TranscodingJobType TranscodingJobType { get; }
  58. /// <summary>
  59. /// Gets the output file extension.
  60. /// </summary>
  61. /// <param name="state">The state.</param>
  62. /// <returns>System.String.</returns>
  63. protected virtual string GetOutputFileExtension(StreamState state)
  64. {
  65. return Path.GetExtension(state.Url);
  66. }
  67. /// <summary>
  68. /// Gets the output file path.
  69. /// </summary>
  70. /// <param name="state">The state.</param>
  71. /// <returns>System.String.</returns>
  72. protected string GetOutputFilePath(StreamState state)
  73. {
  74. var folder = ApplicationPaths.FFMpegStreamCachePath;
  75. return Path.Combine(folder, GetCommandLineArguments("dummy\\dummy", state).GetMD5() + GetOutputFileExtension(state).ToLower());
  76. }
  77. /// <summary>
  78. /// The fast seek offset seconds
  79. /// </summary>
  80. private const int FastSeekOffsetSeconds = 1;
  81. /// <summary>
  82. /// Gets the fast seek command line parameter.
  83. /// </summary>
  84. /// <param name="request">The request.</param>
  85. /// <returns>System.String.</returns>
  86. /// <value>The fast seek command line parameter.</value>
  87. protected string GetFastSeekCommandLineParameter(StreamRequest request)
  88. {
  89. var time = request.StartTimeTicks;
  90. if (time.HasValue)
  91. {
  92. var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds;
  93. if (seconds > 0)
  94. {
  95. return string.Format("-ss {0}", seconds);
  96. }
  97. }
  98. return string.Empty;
  99. }
  100. /// <summary>
  101. /// Gets the slow seek command line parameter.
  102. /// </summary>
  103. /// <param name="request">The request.</param>
  104. /// <returns>System.String.</returns>
  105. /// <value>The slow seek command line parameter.</value>
  106. protected string GetSlowSeekCommandLineParameter(StreamRequest request)
  107. {
  108. var time = request.StartTimeTicks;
  109. if (time.HasValue)
  110. {
  111. if (TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds > 0)
  112. {
  113. return string.Format(" -ss {0}", FastSeekOffsetSeconds);
  114. }
  115. }
  116. return string.Empty;
  117. }
  118. /// <summary>
  119. /// Gets the map args.
  120. /// </summary>
  121. /// <param name="state">The state.</param>
  122. /// <returns>System.String.</returns>
  123. protected string GetMapArgs(StreamState state)
  124. {
  125. var args = string.Empty;
  126. if (state.VideoStream != null)
  127. {
  128. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  129. }
  130. else
  131. {
  132. args += "-map -0:v";
  133. }
  134. if (state.AudioStream != null)
  135. {
  136. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  137. }
  138. else
  139. {
  140. args += " -map -0:a";
  141. }
  142. if (state.SubtitleStream == null)
  143. {
  144. args += " -map -0:s";
  145. }
  146. return args;
  147. }
  148. /// <summary>
  149. /// Determines which stream will be used for playback
  150. /// </summary>
  151. /// <param name="allStream">All stream.</param>
  152. /// <param name="desiredIndex">Index of the desired.</param>
  153. /// <param name="type">The type.</param>
  154. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  155. /// <returns>MediaStream.</returns>
  156. private MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  157. {
  158. var streams = allStream.Where(s => s.Type == type).ToList();
  159. if (desiredIndex.HasValue)
  160. {
  161. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  162. if (stream != null)
  163. {
  164. return stream;
  165. }
  166. }
  167. // Just return the first one
  168. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  169. }
  170. /// <summary>
  171. /// If we're going to put a fixed size on the command line, this will calculate it
  172. /// </summary>
  173. /// <param name="state">The state.</param>
  174. /// <param name="outputVideoCodec">The output video codec.</param>
  175. /// <returns>System.String.</returns>
  176. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec)
  177. {
  178. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  179. var assSubtitleParam = string.Empty;
  180. var request = state.Request;
  181. if (state.SubtitleStream != null)
  182. {
  183. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 || state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1)
  184. {
  185. assSubtitleParam = GetTextSubtitleParam((Video)state.Item, state.SubtitleStream, request.StartTimeTicks);
  186. }
  187. }
  188. // If fixed dimensions were supplied
  189. if (request.Width.HasValue && request.Height.HasValue)
  190. {
  191. return string.Format(" -vf \"scale={0}:{1}{2}\"", request.Width.Value, request.Height.Value, assSubtitleParam);
  192. }
  193. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  194. // If a fixed width was requested
  195. if (request.Width.HasValue)
  196. {
  197. return isH264Output ?
  198. string.Format(" -vf \"scale={0}:trunc(ow/a/2)*2{1}\"", request.Width.Value, assSubtitleParam) :
  199. string.Format(" -vf \"scale={0}:-1{1}\"", request.Width.Value, assSubtitleParam);
  200. }
  201. // If a max width was requested
  202. if (request.MaxWidth.HasValue && !request.MaxHeight.HasValue)
  203. {
  204. return isH264Output ?
  205. string.Format(" -vf \"scale=min(iw\\,{0}):trunc(ow/a/2)*2{1}\"", request.MaxWidth.Value, assSubtitleParam) :
  206. string.Format(" -vf \"scale=min(iw\\,{0}):-1{1}\"", request.MaxWidth.Value, assSubtitleParam);
  207. }
  208. // Need to perform calculations manually
  209. // Try to account for bad media info
  210. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  211. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  212. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  213. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  214. if (isH264Output)
  215. {
  216. return string.Format(" -vf \"scale=trunc({0}/2)*2:trunc({1}/2)*2{2}\"", outputSize.Width, outputSize.Height, assSubtitleParam);
  217. }
  218. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  219. return string.Format(" -vf \"scale={0}:-1{1}\"", Convert.ToInt32(outputSize.Width), assSubtitleParam);
  220. }
  221. /// <summary>
  222. /// Gets the text subtitle param.
  223. /// </summary>
  224. /// <param name="video">The video.</param>
  225. /// <param name="subtitleStream">The subtitle stream.</param>
  226. /// <param name="startTimeTicks">The start time ticks.</param>
  227. /// <returns>System.String.</returns>
  228. protected string GetTextSubtitleParam(Video video, MediaStream subtitleStream, long? startTimeTicks)
  229. {
  230. var path = subtitleStream.IsExternal ? GetConvertedAssPath(video, subtitleStream) : GetExtractedAssPath(video, subtitleStream);
  231. if (string.IsNullOrEmpty(path))
  232. {
  233. return string.Empty;
  234. }
  235. var param = string.Format(",ass={0}", path);
  236. if (startTimeTicks.HasValue)
  237. {
  238. var seconds = Convert.ToInt32(TimeSpan.FromTicks(startTimeTicks.Value).TotalSeconds);
  239. param += string.Format(",setpts=PTS-{0}/TB", seconds);
  240. }
  241. return param;
  242. }
  243. /// <summary>
  244. /// Gets the extracted ass path.
  245. /// </summary>
  246. /// <param name="video">The video.</param>
  247. /// <param name="subtitleStream">The subtitle stream.</param>
  248. /// <returns>System.String.</returns>
  249. private string GetExtractedAssPath(Video video, MediaStream subtitleStream)
  250. {
  251. var path = ServerKernel.FFMpegManager.GetSubtitleCachePath(video, subtitleStream.Index, ".ass");
  252. if (!File.Exists(path))
  253. {
  254. var success = ServerKernel.FFMpegManager.ExtractTextSubtitle(video, subtitleStream.Index, path, CancellationToken.None).Result;
  255. if (!success)
  256. {
  257. return null;
  258. }
  259. }
  260. return path;
  261. }
  262. /// <summary>
  263. /// Gets the converted ass path.
  264. /// </summary>
  265. /// <param name="video">The video.</param>
  266. /// <param name="subtitleStream">The subtitle stream.</param>
  267. /// <returns>System.String.</returns>
  268. private string GetConvertedAssPath(Video video, MediaStream subtitleStream)
  269. {
  270. var path = ServerKernel.FFMpegManager.GetSubtitleCachePath(video, subtitleStream.Index, ".ass");
  271. if (!File.Exists(path))
  272. {
  273. var success = ServerKernel.FFMpegManager.ConvertTextSubtitle(subtitleStream, path, CancellationToken.None).Result;
  274. if (!success)
  275. {
  276. return null;
  277. }
  278. }
  279. return path;
  280. }
  281. /// <summary>
  282. /// Gets the internal graphical subtitle param.
  283. /// </summary>
  284. /// <param name="state">The state.</param>
  285. /// <param name="outputVideoCodec">The output video codec.</param>
  286. /// <returns>System.String.</returns>
  287. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  288. {
  289. var outputSizeParam = string.Empty;
  290. var request = state.Request;
  291. // Add resolution params, if specified
  292. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  293. {
  294. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec).TrimEnd('"');
  295. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  296. }
  297. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p,lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:0] [sub] overlay{1}\"", state.SubtitleStream.Index, outputSizeParam);
  298. }
  299. /// <summary>
  300. /// Gets the number of audio channels to specify on the command line
  301. /// </summary>
  302. /// <param name="request">The request.</param>
  303. /// <param name="audioStream">The audio stream.</param>
  304. /// <returns>System.Nullable{System.Int32}.</returns>
  305. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  306. {
  307. if (audioStream.Channels > 2 && request.AudioCodec.HasValue)
  308. {
  309. if (request.AudioCodec.Value == AudioCodecs.Aac)
  310. {
  311. // libvo_aacenc currently only supports two channel output
  312. return 2;
  313. }
  314. if (request.AudioCodec.Value == AudioCodecs.Wma)
  315. {
  316. // wmav2 currently only supports two channel output
  317. return 2;
  318. }
  319. }
  320. return request.AudioChannels;
  321. }
  322. /// <summary>
  323. /// Determines whether the specified stream is H264.
  324. /// </summary>
  325. /// <param name="stream">The stream.</param>
  326. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  327. protected bool IsH264(MediaStream stream)
  328. {
  329. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  330. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  331. }
  332. /// <summary>
  333. /// Gets the name of the output audio codec
  334. /// </summary>
  335. /// <param name="request">The request.</param>
  336. /// <returns>System.String.</returns>
  337. protected string GetAudioCodec(StreamRequest request)
  338. {
  339. var codec = request.AudioCodec;
  340. if (codec.HasValue)
  341. {
  342. if (codec == AudioCodecs.Aac)
  343. {
  344. return "libvo_aacenc";
  345. }
  346. if (codec == AudioCodecs.Mp3)
  347. {
  348. return "libmp3lame";
  349. }
  350. if (codec == AudioCodecs.Vorbis)
  351. {
  352. return "libvorbis";
  353. }
  354. if (codec == AudioCodecs.Wma)
  355. {
  356. return "wmav2";
  357. }
  358. }
  359. return "copy";
  360. }
  361. /// <summary>
  362. /// Gets the name of the output video codec
  363. /// </summary>
  364. /// <param name="request">The request.</param>
  365. /// <returns>System.String.</returns>
  366. protected string GetVideoCodec(StreamRequest request)
  367. {
  368. var codec = request.VideoCodec;
  369. if (codec.HasValue)
  370. {
  371. if (codec == VideoCodecs.H264)
  372. {
  373. return "libx264";
  374. }
  375. if (codec == VideoCodecs.Vpx)
  376. {
  377. return "libvpx";
  378. }
  379. if (codec == VideoCodecs.Wmv)
  380. {
  381. return "wmv2";
  382. }
  383. if (codec == VideoCodecs.Theora)
  384. {
  385. return "libtheora";
  386. }
  387. }
  388. return "copy";
  389. }
  390. /// <summary>
  391. /// Gets the input argument.
  392. /// </summary>
  393. /// <param name="item">The item.</param>
  394. /// <param name="isoMount">The iso mount.</param>
  395. /// <returns>System.String.</returns>
  396. protected string GetInputArgument(BaseItem item, IIsoMount isoMount)
  397. {
  398. return isoMount == null ?
  399. ServerKernel.FFMpegManager.GetInputArgument(item) :
  400. ServerKernel.FFMpegManager.GetInputArgument(item as Video, isoMount);
  401. }
  402. /// <summary>
  403. /// Starts the FFMPEG.
  404. /// </summary>
  405. /// <param name="state">The state.</param>
  406. /// <param name="outputPath">The output path.</param>
  407. /// <returns>Task.</returns>
  408. protected async Task StartFFMpeg(StreamState state, string outputPath)
  409. {
  410. var video = state.Item as Video;
  411. //if (video != null && video.VideoType == VideoType.Iso &&
  412. // video.IsoType.HasValue && Kernel.IsoManager.CanMount(video.Path))
  413. //{
  414. // IsoMount = await Kernel.IsoManager.Mount(video.Path, CancellationToken.None).ConfigureAwait(false);
  415. //}
  416. var process = new Process
  417. {
  418. StartInfo = new ProcessStartInfo
  419. {
  420. CreateNoWindow = true,
  421. UseShellExecute = false,
  422. // Must consume both stdout and stderr or deadlocks may occur
  423. RedirectStandardOutput = true,
  424. RedirectStandardError = true,
  425. FileName = ServerKernel.FFMpegManager.FFMpegPath,
  426. WorkingDirectory = Path.GetDirectoryName(ServerKernel.FFMpegManager.FFMpegPath),
  427. Arguments = GetCommandLineArguments(outputPath, state),
  428. WindowStyle = ProcessWindowStyle.Hidden,
  429. ErrorDialog = false
  430. },
  431. EnableRaisingEvents = true
  432. };
  433. Plugin.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process);
  434. //Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  435. var logFilePath = Path.Combine(Kernel.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  436. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  437. state.LogFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  438. process.Exited += (sender, args) => OnFFMpegProcessExited(process, state);
  439. try
  440. {
  441. process.Start();
  442. }
  443. catch (Win32Exception ex)
  444. {
  445. Logger.ErrorException("Error starting ffmpeg", ex);
  446. Plugin.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  447. state.LogFileStream.Dispose();
  448. throw;
  449. }
  450. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  451. process.BeginOutputReadLine();
  452. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  453. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  454. // Wait for the file to exist before proceeeding
  455. while (!File.Exists(outputPath))
  456. {
  457. await Task.Delay(100).ConfigureAwait(false);
  458. }
  459. }
  460. /// <summary>
  461. /// Processes the exited.
  462. /// </summary>
  463. /// <param name="process">The process.</param>
  464. /// <param name="state">The state.</param>
  465. protected void OnFFMpegProcessExited(Process process, StreamState state)
  466. {
  467. if (state.IsoMount != null)
  468. {
  469. state.IsoMount.Dispose();
  470. state.IsoMount = null;
  471. }
  472. var outputFilePath = GetOutputFilePath(state);
  473. state.LogFileStream.Dispose();
  474. int? exitCode = null;
  475. try
  476. {
  477. exitCode = process.ExitCode;
  478. Logger.Info("FFMpeg exited with code {0} for {1}", exitCode.Value, outputFilePath);
  479. }
  480. catch
  481. {
  482. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  483. }
  484. process.Dispose();
  485. Plugin.Instance.OnTranscodingFinished(outputFilePath, TranscodingJobType);
  486. if (!exitCode.HasValue || exitCode.Value != 0)
  487. {
  488. Logger.Info("Deleting partial stream file(s) {0}", outputFilePath);
  489. try
  490. {
  491. DeletePartialStreamFiles(outputFilePath);
  492. }
  493. catch (IOException ex)
  494. {
  495. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, outputFilePath);
  496. }
  497. }
  498. else
  499. {
  500. Logger.Info("FFMpeg completed and exited normally for {0}", outputFilePath);
  501. }
  502. }
  503. /// <summary>
  504. /// Deletes the partial stream files.
  505. /// </summary>
  506. /// <param name="outputFilePath">The output file path.</param>
  507. protected abstract void DeletePartialStreamFiles(string outputFilePath);
  508. /// <summary>
  509. /// Gets the state.
  510. /// </summary>
  511. /// <param name="request">The request.</param>
  512. /// <returns>StreamState.</returns>
  513. protected StreamState GetState(StreamRequest request)
  514. {
  515. var item = DtoBuilder.GetItemByClientId(request.Id);
  516. var media = (IHasMediaStreams)item;
  517. return new StreamState
  518. {
  519. Item = item,
  520. Request = request,
  521. AudioStream = GetMediaStream(media.MediaStreams, request.AudioStreamIndex, MediaStreamType.Audio, true),
  522. VideoStream = GetMediaStream(media.MediaStreams, request.VideoStreamIndex, MediaStreamType.Video, true),
  523. SubtitleStream = GetMediaStream(media.MediaStreams, request.SubtitleStreamIndex, MediaStreamType.Subtitle, false),
  524. Url = Request.PathInfo
  525. };
  526. }
  527. }
  528. }