BaseStreamingService.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Dto;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.LiveTv;
  8. using MediaBrowser.Controller.MediaInfo;
  9. using MediaBrowser.Controller.Persistence;
  10. using MediaBrowser.Model.Configuration;
  11. using MediaBrowser.Model.Drawing;
  12. using MediaBrowser.Model.Dto;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.IO;
  15. using MediaBrowser.Model.LiveTv;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Diagnostics;
  19. using System.Globalization;
  20. using System.IO;
  21. using System.Linq;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. namespace MediaBrowser.Api.Playback
  25. {
  26. /// <summary>
  27. /// Class BaseStreamingService
  28. /// </summary>
  29. public abstract class BaseStreamingService : BaseApiService
  30. {
  31. /// <summary>
  32. /// Gets or sets the application paths.
  33. /// </summary>
  34. /// <value>The application paths.</value>
  35. protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
  36. /// <summary>
  37. /// Gets or sets the user manager.
  38. /// </summary>
  39. /// <value>The user manager.</value>
  40. protected IUserManager UserManager { get; private set; }
  41. /// <summary>
  42. /// Gets or sets the library manager.
  43. /// </summary>
  44. /// <value>The library manager.</value>
  45. protected ILibraryManager LibraryManager { get; private set; }
  46. /// <summary>
  47. /// Gets or sets the iso manager.
  48. /// </summary>
  49. /// <value>The iso manager.</value>
  50. protected IIsoManager IsoManager { get; private set; }
  51. /// <summary>
  52. /// Gets or sets the media encoder.
  53. /// </summary>
  54. /// <value>The media encoder.</value>
  55. protected IMediaEncoder MediaEncoder { get; private set; }
  56. protected IDtoService DtoService { get; private set; }
  57. protected IFileSystem FileSystem { get; private set; }
  58. protected IItemRepository ItemRepository { get; private set; }
  59. protected ILiveTvManager LiveTvManager { get; private set; }
  60. /// <summary>
  61. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  62. /// </summary>
  63. /// <param name="serverConfig">The server configuration.</param>
  64. /// <param name="userManager">The user manager.</param>
  65. /// <param name="libraryManager">The library manager.</param>
  66. /// <param name="isoManager">The iso manager.</param>
  67. /// <param name="mediaEncoder">The media encoder.</param>
  68. /// <param name="dtoService">The dto service.</param>
  69. /// <param name="fileSystem">The file system.</param>
  70. /// <param name="itemRepository">The item repository.</param>
  71. protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository, ILiveTvManager liveTvManager)
  72. {
  73. LiveTvManager = liveTvManager;
  74. ItemRepository = itemRepository;
  75. FileSystem = fileSystem;
  76. DtoService = dtoService;
  77. ServerConfigurationManager = serverConfig;
  78. UserManager = userManager;
  79. LibraryManager = libraryManager;
  80. IsoManager = isoManager;
  81. MediaEncoder = mediaEncoder;
  82. }
  83. /// <summary>
  84. /// Gets the command line arguments.
  85. /// </summary>
  86. /// <param name="outputPath">The output path.</param>
  87. /// <param name="state">The state.</param>
  88. /// <param name="performSubtitleConversions">if set to <c>true</c> [perform subtitle conversions].</param>
  89. /// <returns>System.String.</returns>
  90. protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool performSubtitleConversions);
  91. /// <summary>
  92. /// Gets the type of the transcoding job.
  93. /// </summary>
  94. /// <value>The type of the transcoding job.</value>
  95. protected abstract TranscodingJobType TranscodingJobType { get; }
  96. /// <summary>
  97. /// Gets the output file extension.
  98. /// </summary>
  99. /// <param name="state">The state.</param>
  100. /// <returns>System.String.</returns>
  101. protected virtual string GetOutputFileExtension(StreamState state)
  102. {
  103. return Path.GetExtension(state.RequestedUrl);
  104. }
  105. /// <summary>
  106. /// Gets the output file path.
  107. /// </summary>
  108. /// <param name="state">The state.</param>
  109. /// <returns>System.String.</returns>
  110. protected virtual string GetOutputFilePath(StreamState state)
  111. {
  112. var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
  113. var outputFileExtension = GetOutputFileExtension(state);
  114. return Path.Combine(folder, GetCommandLineArguments("dummy\\dummy", state, false).GetMD5() + (outputFileExtension ?? string.Empty).ToLower());
  115. }
  116. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  117. /// <summary>
  118. /// The fast seek offset seconds
  119. /// </summary>
  120. private const int FastSeekOffsetSeconds = 1;
  121. /// <summary>
  122. /// Gets the fast seek command line parameter.
  123. /// </summary>
  124. /// <param name="request">The request.</param>
  125. /// <returns>System.String.</returns>
  126. /// <value>The fast seek command line parameter.</value>
  127. protected string GetFastSeekCommandLineParameter(StreamRequest request)
  128. {
  129. var time = request.StartTimeTicks;
  130. if (time.HasValue)
  131. {
  132. var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds;
  133. if (seconds > 0)
  134. {
  135. return string.Format("-ss {0}", seconds.ToString(UsCulture));
  136. }
  137. }
  138. return string.Empty;
  139. }
  140. /// <summary>
  141. /// Gets the slow seek command line parameter.
  142. /// </summary>
  143. /// <param name="request">The request.</param>
  144. /// <returns>System.String.</returns>
  145. /// <value>The slow seek command line parameter.</value>
  146. protected string GetSlowSeekCommandLineParameter(StreamRequest request)
  147. {
  148. var time = request.StartTimeTicks;
  149. if (time.HasValue)
  150. {
  151. if (TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds > 0)
  152. {
  153. return string.Format(" -ss {0}", FastSeekOffsetSeconds.ToString(UsCulture));
  154. }
  155. }
  156. return string.Empty;
  157. }
  158. /// <summary>
  159. /// Gets the map args.
  160. /// </summary>
  161. /// <param name="state">The state.</param>
  162. /// <returns>System.String.</returns>
  163. protected virtual string GetMapArgs(StreamState state)
  164. {
  165. var args = string.Empty;
  166. if (state.IsRemote || !state.HasMediaStreams)
  167. {
  168. return string.Empty;
  169. }
  170. if (state.VideoStream != null)
  171. {
  172. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  173. }
  174. else
  175. {
  176. args += "-map -0:v";
  177. }
  178. if (state.AudioStream != null)
  179. {
  180. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  181. }
  182. else
  183. {
  184. args += " -map -0:a";
  185. }
  186. if (state.SubtitleStream == null)
  187. {
  188. args += " -map -0:s";
  189. }
  190. return args;
  191. }
  192. /// <summary>
  193. /// Determines which stream will be used for playback
  194. /// </summary>
  195. /// <param name="allStream">All stream.</param>
  196. /// <param name="desiredIndex">Index of the desired.</param>
  197. /// <param name="type">The type.</param>
  198. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  199. /// <returns>MediaStream.</returns>
  200. private MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  201. {
  202. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  203. if (desiredIndex.HasValue)
  204. {
  205. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  206. if (stream != null)
  207. {
  208. return stream;
  209. }
  210. }
  211. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  212. {
  213. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  214. streams.FirstOrDefault();
  215. }
  216. // Just return the first one
  217. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  218. }
  219. protected EncodingQuality GetQualitySetting()
  220. {
  221. var quality = ServerConfigurationManager.Configuration.MediaEncodingQuality;
  222. if (quality == EncodingQuality.Auto)
  223. {
  224. var cpuCount = Environment.ProcessorCount;
  225. if (cpuCount >= 4)
  226. {
  227. return EncodingQuality.HighQuality;
  228. }
  229. return EncodingQuality.HighSpeed;
  230. }
  231. return quality;
  232. }
  233. /// <summary>
  234. /// Gets the number of threads.
  235. /// </summary>
  236. /// <returns>System.Int32.</returns>
  237. /// <exception cref="System.Exception">Unrecognized MediaEncodingQuality value.</exception>
  238. protected int GetNumberOfThreads(bool isWebm)
  239. {
  240. // Webm: http://www.webmproject.org/docs/encoder-parameters/
  241. // The decoder will usually automatically use an appropriate number of threads according to how many cores are available but it can only use multiple threads
  242. // for the coefficient data if the encoder selected --token-parts > 0 at encode time.
  243. switch (GetQualitySetting())
  244. {
  245. case EncodingQuality.HighSpeed:
  246. return 2;
  247. case EncodingQuality.HighQuality:
  248. return isWebm ? Math.Min(3, Environment.ProcessorCount - 1) : 2;
  249. case EncodingQuality.MaxQuality:
  250. return isWebm ? Math.Max(2, Environment.ProcessorCount - 1) : 0;
  251. default:
  252. throw new Exception("Unrecognized MediaEncodingQuality value.");
  253. }
  254. }
  255. /// <summary>
  256. /// Gets the video bitrate to specify on the command line
  257. /// </summary>
  258. /// <param name="state">The state.</param>
  259. /// <param name="videoCodec">The video codec.</param>
  260. /// <returns>System.String.</returns>
  261. protected string GetVideoQualityParam(StreamState state, string videoCodec)
  262. {
  263. // webm
  264. if (videoCodec.Equals("libvpx", StringComparison.OrdinalIgnoreCase))
  265. {
  266. // http://www.webmproject.org/docs/encoder-parameters/
  267. return "-speed 16 -quality good -profile:v 0 -slices 8";
  268. }
  269. // asf/wmv
  270. if (videoCodec.Equals("wmv2", StringComparison.OrdinalIgnoreCase))
  271. {
  272. return "-g 100 -qmax 15";
  273. }
  274. if (videoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase))
  275. {
  276. return "-preset superfast";
  277. }
  278. if (videoCodec.Equals("mpeg4", StringComparison.OrdinalIgnoreCase))
  279. {
  280. return "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  281. }
  282. return string.Empty;
  283. }
  284. protected string GetAudioFilterParam(StreamState state, bool isHls)
  285. {
  286. var volParam = string.Empty;
  287. var audioSampleRate = string.Empty;
  288. var channels = GetNumAudioChannelsParam(state.Request, state.AudioStream);
  289. // Boost volume to 200% when downsampling from 6ch to 2ch
  290. if (channels.HasValue && channels.Value <= 2 && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  291. {
  292. volParam = ",volume=2.000000";
  293. }
  294. if (state.Request.AudioSampleRate.HasValue)
  295. {
  296. audioSampleRate = state.Request.AudioSampleRate.Value + ":";
  297. }
  298. var adelay = isHls ? "adelay=1," : string.Empty;
  299. var pts = string.Empty;
  300. if (state.SubtitleStream != null)
  301. {
  302. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  303. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  304. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  305. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  306. {
  307. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  308. pts = string.Format(",asetpts=PTS-{0}/TB",
  309. Math.Round(seconds).ToString(UsCulture));
  310. }
  311. }
  312. return string.Format("-af \"{0}aresample={1}async=1{2}{3}\"",
  313. adelay,
  314. audioSampleRate,
  315. volParam,
  316. pts);
  317. }
  318. /// <summary>
  319. /// If we're going to put a fixed size on the command line, this will calculate it
  320. /// </summary>
  321. /// <param name="state">The state.</param>
  322. /// <param name="outputVideoCodec">The output video codec.</param>
  323. /// <param name="performTextSubtitleConversion">if set to <c>true</c> [perform text subtitle conversion].</param>
  324. /// <returns>System.String.</returns>
  325. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec, bool performTextSubtitleConversion)
  326. {
  327. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  328. var assSubtitleParam = string.Empty;
  329. var copyTsParam = string.Empty;
  330. var yadifParam = "yadif=0:-1:0,";
  331. var request = state.VideoRequest;
  332. if (state.SubtitleStream != null)
  333. {
  334. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  335. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  336. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  337. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  338. {
  339. assSubtitleParam = GetTextSubtitleParam(state, performTextSubtitleConversion);
  340. copyTsParam = " -copyts";
  341. }
  342. }
  343. // If fixed dimensions were supplied
  344. if (request.Width.HasValue && request.Height.HasValue)
  345. {
  346. var widthParam = request.Width.Value.ToString(UsCulture);
  347. var heightParam = request.Height.Value.ToString(UsCulture);
  348. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"",yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  349. }
  350. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  351. // If a fixed width was requested
  352. if (request.Width.HasValue)
  353. {
  354. var widthParam = request.Width.Value.ToString(UsCulture);
  355. return isH264Output ?
  356. string.Format("{3} -vf \"{0}scale={1}:trunc(ow/a/2)*2{2}\"",yadifParam, widthParam, assSubtitleParam, copyTsParam) :
  357. string.Format("{3} -vf \"{0}scale={1}:-1{2}\"",yadifParam, widthParam, assSubtitleParam, copyTsParam);
  358. }
  359. // If a fixed height was requested
  360. if (request.Height.HasValue)
  361. {
  362. var heightParam = request.Height.Value.ToString(UsCulture);
  363. return isH264Output ?
  364. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:{1}{2}\"",yadifParam, heightParam, assSubtitleParam, copyTsParam) :
  365. string.Format("{3} -vf \"{0}scale=-1:{1}{2}\"",yadifParam, heightParam, assSubtitleParam, copyTsParam);
  366. }
  367. // If a max width was requested
  368. if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null))
  369. {
  370. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  371. return isH264Output ?
  372. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):trunc(ow/a/2)*2{2}\"",yadifParam, maxWidthParam, assSubtitleParam, copyTsParam) :
  373. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):-1{2}\"",yadifParam, maxWidthParam, assSubtitleParam, copyTsParam);
  374. }
  375. // If a max height was requested
  376. if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null))
  377. {
  378. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  379. return isH264Output ?
  380. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:min(ih\\,{1}){2}\"",yadifParam, maxHeightParam, assSubtitleParam, copyTsParam) :
  381. string.Format("{3} -vf \"{0}scale=-1:min(ih\\,{1}){2}\"",yadifParam, maxHeightParam, assSubtitleParam, copyTsParam);
  382. }
  383. if (state.VideoStream == null)
  384. {
  385. // No way to figure this out
  386. return string.Empty;
  387. }
  388. // Need to perform calculations manually
  389. // Try to account for bad media info
  390. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  391. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  392. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  393. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  394. if (isH264Output)
  395. {
  396. var widthParam = outputSize.Width.ToString(UsCulture);
  397. var heightParam = outputSize.Height.ToString(UsCulture);
  398. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"",yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  399. }
  400. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  401. return string.Format("{3} -vf \"{0}scale={1}:-1{2}\"",yadifParam, Convert.ToInt32(outputSize.Width), assSubtitleParam, copyTsParam);
  402. }
  403. /// <summary>
  404. /// Gets the text subtitle param.
  405. /// </summary>
  406. /// <param name="state">The state.</param>
  407. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  408. /// <returns>System.String.</returns>
  409. protected string GetTextSubtitleParam(StreamState state, bool performConversion)
  410. {
  411. var path = state.SubtitleStream.IsExternal ? GetConvertedAssPath(state.MediaPath, state.SubtitleStream, performConversion) :
  412. GetExtractedAssPath(state, performConversion);
  413. if (string.IsNullOrEmpty(path))
  414. {
  415. return string.Empty;
  416. }
  417. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  418. return string.Format(",ass='{0}',setpts=PTS -{1}/TB",
  419. path.Replace('\\', '/').Replace(":/", "\\:/"),
  420. Math.Round(seconds).ToString(UsCulture));
  421. }
  422. /// <summary>
  423. /// Gets the extracted ass path.
  424. /// </summary>
  425. /// <param name="state">The state.</param>
  426. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  427. /// <returns>System.String.</returns>
  428. private string GetExtractedAssPath(StreamState state, bool performConversion)
  429. {
  430. var path = FFMpegManager.Instance.GetSubtitleCachePath(state.MediaPath, state.SubtitleStream, ".ass");
  431. if (performConversion)
  432. {
  433. InputType type;
  434. var inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, null, state.PlayableStreamFileNames, out type);
  435. try
  436. {
  437. var parentPath = Path.GetDirectoryName(path);
  438. Directory.CreateDirectory(parentPath);
  439. var task = MediaEncoder.ExtractTextSubtitle(inputPath, type, state.SubtitleStream.Index, path, CancellationToken.None);
  440. Task.WaitAll(task);
  441. }
  442. catch
  443. {
  444. return null;
  445. }
  446. }
  447. return path;
  448. }
  449. /// <summary>
  450. /// Gets the converted ass path.
  451. /// </summary>
  452. /// <param name="mediaPath">The media path.</param>
  453. /// <param name="subtitleStream">The subtitle stream.</param>
  454. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  455. /// <returns>System.String.</returns>
  456. private string GetConvertedAssPath(string mediaPath, MediaStream subtitleStream, bool performConversion)
  457. {
  458. var path = FFMpegManager.Instance.GetSubtitleCachePath(mediaPath, subtitleStream, ".ass");
  459. if (performConversion)
  460. {
  461. try
  462. {
  463. var parentPath = Path.GetDirectoryName(path);
  464. Directory.CreateDirectory(parentPath);
  465. var task = MediaEncoder.ConvertTextSubtitleToAss(subtitleStream.Path, path, subtitleStream.Language, CancellationToken.None);
  466. Task.WaitAll(task);
  467. }
  468. catch
  469. {
  470. return null;
  471. }
  472. }
  473. return path;
  474. }
  475. /// <summary>
  476. /// Gets the internal graphical subtitle param.
  477. /// </summary>
  478. /// <param name="state">The state.</param>
  479. /// <param name="outputVideoCodec">The output video codec.</param>
  480. /// <returns>System.String.</returns>
  481. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  482. {
  483. var outputSizeParam = string.Empty;
  484. var request = state.VideoRequest;
  485. // Add resolution params, if specified
  486. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  487. {
  488. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec, false).TrimEnd('"');
  489. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  490. }
  491. var videoSizeParam = string.Empty;
  492. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  493. {
  494. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  495. }
  496. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p{3},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{1}] [sub] overlay{2}\"",
  497. state.SubtitleStream.Index,
  498. state.VideoStream.Index,
  499. outputSizeParam,
  500. videoSizeParam);
  501. }
  502. /// <summary>
  503. /// Gets the probe size argument.
  504. /// </summary>
  505. /// <param name="mediaPath">The media path.</param>
  506. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  507. /// <param name="videoType">Type of the video.</param>
  508. /// <param name="isoType">Type of the iso.</param>
  509. /// <returns>System.String.</returns>
  510. protected string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  511. {
  512. var type = !isVideo ? MediaEncoderHelpers.GetInputType(null, null) :
  513. MediaEncoderHelpers.GetInputType(videoType, isoType);
  514. return MediaEncoder.GetProbeSizeArgument(type);
  515. }
  516. /// <summary>
  517. /// Gets the number of audio channels to specify on the command line
  518. /// </summary>
  519. /// <param name="request">The request.</param>
  520. /// <param name="audioStream">The audio stream.</param>
  521. /// <returns>System.Nullable{System.Int32}.</returns>
  522. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  523. {
  524. if (audioStream != null)
  525. {
  526. if (audioStream.Channels > 2 && request.AudioCodec.HasValue)
  527. {
  528. if (request.AudioCodec.Value == AudioCodecs.Wma)
  529. {
  530. // wmav2 currently only supports two channel output
  531. return 2;
  532. }
  533. }
  534. }
  535. return request.AudioChannels;
  536. }
  537. /// <summary>
  538. /// Determines whether the specified stream is H264.
  539. /// </summary>
  540. /// <param name="stream">The stream.</param>
  541. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  542. protected bool IsH264(MediaStream stream)
  543. {
  544. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  545. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  546. }
  547. /// <summary>
  548. /// Gets the name of the output audio codec
  549. /// </summary>
  550. /// <param name="request">The request.</param>
  551. /// <returns>System.String.</returns>
  552. protected string GetAudioCodec(StreamRequest request)
  553. {
  554. var codec = request.AudioCodec;
  555. if (codec.HasValue)
  556. {
  557. if (codec == AudioCodecs.Aac)
  558. {
  559. return "aac -strict experimental";
  560. }
  561. if (codec == AudioCodecs.Mp3)
  562. {
  563. return "libmp3lame";
  564. }
  565. if (codec == AudioCodecs.Vorbis)
  566. {
  567. return "libvorbis";
  568. }
  569. if (codec == AudioCodecs.Wma)
  570. {
  571. return "wmav2";
  572. }
  573. return codec.ToString().ToLower();
  574. }
  575. return "copy";
  576. }
  577. /// <summary>
  578. /// Gets the name of the output video codec
  579. /// </summary>
  580. /// <param name="request">The request.</param>
  581. /// <returns>System.String.</returns>
  582. protected string GetVideoCodec(VideoStreamRequest request)
  583. {
  584. var codec = request.VideoCodec;
  585. if (codec.HasValue)
  586. {
  587. if (codec == VideoCodecs.H264)
  588. {
  589. return "libx264";
  590. }
  591. if (codec == VideoCodecs.Vpx)
  592. {
  593. return "libvpx";
  594. }
  595. if (codec == VideoCodecs.Wmv)
  596. {
  597. return "wmv2";
  598. }
  599. if (codec == VideoCodecs.Theora)
  600. {
  601. return "libtheora";
  602. }
  603. return codec.ToString().ToLower();
  604. }
  605. return "copy";
  606. }
  607. /// <summary>
  608. /// Gets the input argument.
  609. /// </summary>
  610. /// <param name="state">The state.</param>
  611. /// <returns>System.String.</returns>
  612. protected string GetInputArgument(StreamState state)
  613. {
  614. if (state.SendInputOverStandardInput)
  615. {
  616. return "-";
  617. }
  618. var type = InputType.File;
  619. var inputPath = new[] { state.MediaPath };
  620. if (state.IsInputVideo)
  621. {
  622. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  623. {
  624. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  625. }
  626. }
  627. return MediaEncoder.GetInputArgument(inputPath, type);
  628. }
  629. /// <summary>
  630. /// Starts the FFMPEG.
  631. /// </summary>
  632. /// <param name="state">The state.</param>
  633. /// <param name="outputPath">The output path.</param>
  634. /// <returns>Task.</returns>
  635. protected async Task StartFfMpeg(StreamState state, string outputPath)
  636. {
  637. if (!File.Exists(MediaEncoder.EncoderPath))
  638. {
  639. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  640. }
  641. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  642. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  643. {
  644. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  645. }
  646. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  647. if (ServerConfigurationManager.Configuration.EnableDebugEncodingLogging)
  648. {
  649. commandLineArgs = "-loglevel debug " + commandLineArgs;
  650. }
  651. var process = new Process
  652. {
  653. StartInfo = new ProcessStartInfo
  654. {
  655. CreateNoWindow = true,
  656. UseShellExecute = false,
  657. // Must consume both stdout and stderr or deadlocks may occur
  658. RedirectStandardOutput = true,
  659. RedirectStandardError = true,
  660. FileName = MediaEncoder.EncoderPath,
  661. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  662. Arguments = commandLineArgs,
  663. WindowStyle = ProcessWindowStyle.Hidden,
  664. ErrorDialog = false,
  665. RedirectStandardInput = state.SendInputOverStandardInput
  666. },
  667. EnableRaisingEvents = true
  668. };
  669. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  670. Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  671. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  672. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  673. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  674. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  675. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  676. try
  677. {
  678. process.Start();
  679. }
  680. catch (Exception ex)
  681. {
  682. Logger.ErrorException("Error starting ffmpeg", ex);
  683. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  684. state.LogFileStream.Dispose();
  685. throw;
  686. }
  687. if (state.SendInputOverStandardInput)
  688. {
  689. StreamToStandardInput(process, state);
  690. }
  691. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  692. process.BeginOutputReadLine();
  693. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  694. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  695. // Wait for the file to exist before proceeeding
  696. while (!File.Exists(outputPath))
  697. {
  698. await Task.Delay(100).ConfigureAwait(false);
  699. }
  700. // Allow a small amount of time to buffer a little
  701. if (state.IsInputVideo)
  702. {
  703. await Task.Delay(500).ConfigureAwait(false);
  704. }
  705. // This is arbitrary, but add a little buffer time when internet streaming
  706. if (state.IsRemote)
  707. {
  708. await Task.Delay(3000).ConfigureAwait(false);
  709. }
  710. }
  711. private async void StreamToStandardInput(Process process, StreamState state)
  712. {
  713. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  714. try
  715. {
  716. await StreamToStandardInputInternal(process, state).ConfigureAwait(false);
  717. }
  718. catch (OperationCanceledException)
  719. {
  720. Logger.Debug("Stream to standard input closed normally.");
  721. }
  722. catch (Exception ex)
  723. {
  724. Logger.ErrorException("Error writing to standard input", ex);
  725. }
  726. }
  727. private async Task StreamToStandardInputInternal(Process process, StreamState state)
  728. {
  729. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  730. using (var fileStream = FileSystem.GetFileStream(state.MediaPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  731. {
  732. await new EndlessStreamCopy().CopyStream(fileStream, process.StandardInput.BaseStream, state.StandardInputCancellationTokenSource.Token).ConfigureAwait(false);
  733. }
  734. }
  735. protected int? GetVideoBitrateParam(StreamState state)
  736. {
  737. return state.VideoRequest.VideoBitRate;
  738. }
  739. protected int? GetAudioBitrateParam(StreamState state)
  740. {
  741. if (state.Request.AudioBitRate.HasValue)
  742. {
  743. // Make sure we don't request a bitrate higher than the source
  744. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  745. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  746. }
  747. return null;
  748. }
  749. /// <summary>
  750. /// Gets the user agent param.
  751. /// </summary>
  752. /// <param name="path">The path.</param>
  753. /// <returns>System.String.</returns>
  754. protected string GetUserAgentParam(string path)
  755. {
  756. var useragent = GetUserAgent(path);
  757. if (!string.IsNullOrEmpty(useragent))
  758. {
  759. return "-user-agent \"" + useragent + "\"";
  760. }
  761. return string.Empty;
  762. }
  763. /// <summary>
  764. /// Gets the user agent.
  765. /// </summary>
  766. /// <param name="path">The path.</param>
  767. /// <returns>System.String.</returns>
  768. protected string GetUserAgent(string path)
  769. {
  770. if (string.IsNullOrEmpty(path))
  771. {
  772. throw new ArgumentNullException("path");
  773. }
  774. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  775. {
  776. return "QuickTime/7.7.4";
  777. }
  778. return string.Empty;
  779. }
  780. /// <summary>
  781. /// Processes the exited.
  782. /// </summary>
  783. /// <param name="process">The process.</param>
  784. /// <param name="state">The state.</param>
  785. protected async void OnFfMpegProcessExited(Process process, StreamState state)
  786. {
  787. if (state.IsoMount != null)
  788. {
  789. state.IsoMount.Dispose();
  790. state.IsoMount = null;
  791. }
  792. if (state.StandardInputCancellationTokenSource != null)
  793. {
  794. state.StandardInputCancellationTokenSource.Cancel();
  795. }
  796. var outputFilePath = GetOutputFilePath(state);
  797. state.LogFileStream.Dispose();
  798. try
  799. {
  800. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  801. }
  802. catch
  803. {
  804. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  805. }
  806. if (!string.IsNullOrEmpty(state.LiveTvStreamId))
  807. {
  808. try
  809. {
  810. await LiveTvManager.CloseLiveStream(state.LiveTvStreamId, CancellationToken.None).ConfigureAwait(false);
  811. }
  812. catch (Exception ex)
  813. {
  814. Logger.ErrorException("Error closing live tv stream", ex);
  815. }
  816. }
  817. }
  818. /// <summary>
  819. /// Gets the state.
  820. /// </summary>
  821. /// <param name="request">The request.</param>
  822. /// <param name="cancellationToken">The cancellation token.</param>
  823. /// <returns>StreamState.</returns>
  824. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  825. {
  826. var url = Request.PathInfo;
  827. if (!request.AudioCodec.HasValue)
  828. {
  829. request.AudioCodec = InferAudioCodec(url);
  830. }
  831. var state = new StreamState
  832. {
  833. Request = request,
  834. RequestedUrl = url
  835. };
  836. Guid itemId;
  837. if (string.Equals(request.Type, "Recording", StringComparison.OrdinalIgnoreCase))
  838. {
  839. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  840. state.VideoType = VideoType.VideoFile;
  841. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  842. state.PlayableStreamFileNames = new List<string>();
  843. if (!string.IsNullOrEmpty(recording.RecordingInfo.Path) && File.Exists(recording.RecordingInfo.Path))
  844. {
  845. state.MediaPath = recording.RecordingInfo.Path;
  846. state.IsRemote = false;
  847. }
  848. else if (!string.IsNullOrEmpty(recording.RecordingInfo.Url))
  849. {
  850. state.MediaPath = recording.RecordingInfo.Url;
  851. state.IsRemote = true;
  852. }
  853. else
  854. {
  855. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  856. state.LiveTvStreamId = streamInfo.Id;
  857. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  858. {
  859. state.MediaPath = streamInfo.Path;
  860. state.IsRemote = false;
  861. }
  862. else if (!string.IsNullOrEmpty(streamInfo.Url))
  863. {
  864. state.MediaPath = streamInfo.Url;
  865. state.IsRemote = true;
  866. }
  867. }
  868. itemId = recording.Id;
  869. //state.RunTimeTicks = recording.RunTimeTicks;
  870. state.SendInputOverStandardInput = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  871. }
  872. else if (string.Equals(request.Type, "Channel", StringComparison.OrdinalIgnoreCase))
  873. {
  874. var channel = LiveTvManager.GetInternalChannel(request.Id);
  875. state.VideoType = VideoType.VideoFile;
  876. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  877. state.PlayableStreamFileNames = new List<string>();
  878. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  879. state.LiveTvStreamId = streamInfo.Id;
  880. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  881. {
  882. state.MediaPath = streamInfo.Path;
  883. state.IsRemote = false;
  884. }
  885. else if (!string.IsNullOrEmpty(streamInfo.Url))
  886. {
  887. state.MediaPath = streamInfo.Url;
  888. state.IsRemote = true;
  889. }
  890. itemId = channel.Id;
  891. state.SendInputOverStandardInput = true;
  892. }
  893. else
  894. {
  895. var item = DtoService.GetItemByDtoId(request.Id);
  896. state.MediaPath = item.Path;
  897. state.IsRemote = item.LocationType == LocationType.Remote;
  898. var video = item as Video;
  899. if (video != null)
  900. {
  901. state.IsInputVideo = true;
  902. state.VideoType = video.VideoType;
  903. state.IsoType = video.IsoType;
  904. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  905. ? new List<string>()
  906. : video.PlayableStreamFileNames.ToList();
  907. }
  908. state.RunTimeTicks = item.RunTimeTicks;
  909. itemId = item.Id;
  910. }
  911. var videoRequest = request as VideoStreamRequest;
  912. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  913. {
  914. ItemId = itemId
  915. }).ToList();
  916. if (videoRequest != null)
  917. {
  918. if (!videoRequest.VideoCodec.HasValue)
  919. {
  920. videoRequest.VideoCodec = InferVideoCodec(url);
  921. }
  922. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  923. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  924. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  925. }
  926. else
  927. {
  928. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  929. }
  930. state.HasMediaStreams = mediaStreams.Count > 0;
  931. return state;
  932. }
  933. /// <summary>
  934. /// Infers the audio codec based on the url
  935. /// </summary>
  936. /// <param name="url">The URL.</param>
  937. /// <returns>System.Nullable{AudioCodecs}.</returns>
  938. private AudioCodecs? InferAudioCodec(string url)
  939. {
  940. var ext = Path.GetExtension(url);
  941. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  942. {
  943. return AudioCodecs.Mp3;
  944. }
  945. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  946. {
  947. return AudioCodecs.Aac;
  948. }
  949. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  950. {
  951. return AudioCodecs.Wma;
  952. }
  953. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  954. {
  955. return AudioCodecs.Vorbis;
  956. }
  957. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  958. {
  959. return AudioCodecs.Vorbis;
  960. }
  961. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  962. {
  963. return AudioCodecs.Vorbis;
  964. }
  965. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  966. {
  967. return AudioCodecs.Vorbis;
  968. }
  969. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  970. {
  971. return AudioCodecs.Vorbis;
  972. }
  973. return null;
  974. }
  975. /// <summary>
  976. /// Infers the video codec.
  977. /// </summary>
  978. /// <param name="url">The URL.</param>
  979. /// <returns>System.Nullable{VideoCodecs}.</returns>
  980. private VideoCodecs? InferVideoCodec(string url)
  981. {
  982. var ext = Path.GetExtension(url);
  983. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  984. {
  985. return VideoCodecs.Wmv;
  986. }
  987. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  988. {
  989. return VideoCodecs.Vpx;
  990. }
  991. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  992. {
  993. return VideoCodecs.Theora;
  994. }
  995. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  996. {
  997. return VideoCodecs.H264;
  998. }
  999. return VideoCodecs.Copy;
  1000. }
  1001. }
  1002. }