BaseStreamingService.cs 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  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 2;
  249. case EncodingQuality.MaxQuality:
  250. return isWebm ? 2 : 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, bool isHls)
  262. {
  263. var param = string.Empty;
  264. var hasFixedResolution = state.VideoRequest.HasFixedResolution;
  265. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  266. {
  267. switch (GetQualitySetting())
  268. {
  269. case EncodingQuality.HighSpeed:
  270. param = "-preset ultrafast";
  271. break;
  272. case EncodingQuality.HighQuality:
  273. param = "-preset superfast";
  274. break;
  275. case EncodingQuality.MaxQuality:
  276. param = "-preset superfast";
  277. break;
  278. }
  279. if (!hasFixedResolution)
  280. {
  281. param += " -crf 18";
  282. }
  283. }
  284. // webm
  285. else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  286. {
  287. // http://www.webmproject.org/docs/encoder-parameters/
  288. param = "-speed 16 -quality good -profile:v 0 -slices 8";
  289. if (!hasFixedResolution)
  290. {
  291. param += " -crf 18";
  292. }
  293. }
  294. else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  295. {
  296. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  297. }
  298. // asf/wmv
  299. else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
  300. {
  301. param = "-qmin 2";
  302. }
  303. else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  304. {
  305. param = "-mbd 2";
  306. }
  307. param += GetVideoBitrateParam(state, videoCodec, isHls);
  308. var framerate = GetFramerateParam(state);
  309. if (framerate.HasValue)
  310. {
  311. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  312. }
  313. if (!string.IsNullOrEmpty(state.VideoSync))
  314. {
  315. param += " -vsync " + state.VideoSync;
  316. }
  317. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  318. {
  319. param += " -profile:v " + state.VideoRequest.Profile;
  320. }
  321. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  322. {
  323. param += " -level " + state.VideoRequest.Level;
  324. }
  325. return param;
  326. }
  327. protected string GetAudioFilterParam(StreamState state, bool isHls)
  328. {
  329. var volParam = string.Empty;
  330. var audioSampleRate = string.Empty;
  331. var channels = GetNumAudioChannelsParam(state.Request, state.AudioStream);
  332. // Boost volume to 200% when downsampling from 6ch to 2ch
  333. if (channels.HasValue && channels.Value <= 2 && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  334. {
  335. volParam = ",volume=2.000000";
  336. }
  337. if (state.Request.AudioSampleRate.HasValue)
  338. {
  339. audioSampleRate = state.Request.AudioSampleRate.Value + ":";
  340. }
  341. var adelay = isHls ? "adelay=1," : string.Empty;
  342. var pts = string.Empty;
  343. if (state.SubtitleStream != null)
  344. {
  345. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  346. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  347. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  348. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  349. {
  350. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  351. pts = string.Format(",asetpts=PTS-{0}/TB",
  352. Math.Round(seconds).ToString(UsCulture));
  353. }
  354. }
  355. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  356. adelay,
  357. audioSampleRate,
  358. volParam,
  359. pts,
  360. state.AudioSync);
  361. }
  362. /// <summary>
  363. /// If we're going to put a fixed size on the command line, this will calculate it
  364. /// </summary>
  365. /// <param name="state">The state.</param>
  366. /// <param name="outputVideoCodec">The output video codec.</param>
  367. /// <param name="performTextSubtitleConversion">if set to <c>true</c> [perform text subtitle conversion].</param>
  368. /// <returns>System.String.</returns>
  369. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec, bool performTextSubtitleConversion)
  370. {
  371. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  372. var assSubtitleParam = string.Empty;
  373. var copyTsParam = string.Empty;
  374. var yadifParam = state.DeInterlace ? "yadif=0:-1:0," : string.Empty;
  375. var request = state.VideoRequest;
  376. if (state.SubtitleStream != null)
  377. {
  378. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  379. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  380. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  381. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  382. {
  383. assSubtitleParam = GetTextSubtitleParam(state, performTextSubtitleConversion);
  384. copyTsParam = " -copyts";
  385. }
  386. }
  387. // If fixed dimensions were supplied
  388. if (request.Width.HasValue && request.Height.HasValue)
  389. {
  390. var widthParam = request.Width.Value.ToString(UsCulture);
  391. var heightParam = request.Height.Value.ToString(UsCulture);
  392. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  393. }
  394. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  395. // If a fixed width was requested
  396. if (request.Width.HasValue)
  397. {
  398. var widthParam = request.Width.Value.ToString(UsCulture);
  399. return isH264Output ?
  400. string.Format("{3} -vf \"{0}scale={1}:trunc(ow/a/2)*2{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam) :
  401. string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam);
  402. }
  403. // If a fixed height was requested
  404. if (request.Height.HasValue)
  405. {
  406. var heightParam = request.Height.Value.ToString(UsCulture);
  407. return isH264Output ?
  408. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam) :
  409. string.Format("{3} -vf \"{0}scale=-1:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam);
  410. }
  411. // If a max width was requested
  412. if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null))
  413. {
  414. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  415. return isH264Output ?
  416. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):trunc(ow/a/2)*2{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam) :
  417. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):-1{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam);
  418. }
  419. // If a max height was requested
  420. if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null))
  421. {
  422. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  423. return isH264Output ?
  424. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam) :
  425. string.Format("{3} -vf \"{0}scale=-1:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam);
  426. }
  427. if (state.VideoStream == null)
  428. {
  429. // No way to figure this out
  430. return string.Empty;
  431. }
  432. // Need to perform calculations manually
  433. // Try to account for bad media info
  434. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  435. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  436. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  437. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  438. if (isH264Output)
  439. {
  440. var widthParam = outputSize.Width.ToString(UsCulture);
  441. var heightParam = outputSize.Height.ToString(UsCulture);
  442. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  443. }
  444. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  445. return string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, Convert.ToInt32(outputSize.Width), assSubtitleParam, copyTsParam);
  446. }
  447. /// <summary>
  448. /// Gets the text subtitle param.
  449. /// </summary>
  450. /// <param name="state">The state.</param>
  451. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  452. /// <returns>System.String.</returns>
  453. protected string GetTextSubtitleParam(StreamState state, bool performConversion)
  454. {
  455. var path = state.SubtitleStream.IsExternal ? GetConvertedAssPath(state.MediaPath, state.SubtitleStream, performConversion) :
  456. GetExtractedAssPath(state, performConversion);
  457. if (string.IsNullOrEmpty(path))
  458. {
  459. return string.Empty;
  460. }
  461. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  462. return string.Format(",ass='{0}',setpts=PTS -{1}/TB",
  463. path.Replace('\\', '/').Replace(":/", "\\:/"),
  464. Math.Round(seconds).ToString(UsCulture));
  465. }
  466. /// <summary>
  467. /// Gets the extracted ass path.
  468. /// </summary>
  469. /// <param name="state">The state.</param>
  470. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  471. /// <returns>System.String.</returns>
  472. private string GetExtractedAssPath(StreamState state, bool performConversion)
  473. {
  474. var path = FFMpegManager.Instance.GetSubtitleCachePath(state.MediaPath, state.SubtitleStream, ".ass");
  475. if (performConversion)
  476. {
  477. InputType type;
  478. var inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, null, state.PlayableStreamFileNames, out type);
  479. try
  480. {
  481. var parentPath = Path.GetDirectoryName(path);
  482. Directory.CreateDirectory(parentPath);
  483. // Don't re-encode ass/ssa to ass because ffmpeg ass encoder fails if there's more than one ass rectangle. Affect Anime mostly.
  484. // See https://lists.ffmpeg.org/pipermail/ffmpeg-cvslog/2013-April/063616.html
  485. bool isAssSubtitle = string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase);
  486. var task = MediaEncoder.ExtractTextSubtitle(inputPath, type, state.SubtitleStream.Index, isAssSubtitle, path, CancellationToken.None);
  487. Task.WaitAll(task);
  488. }
  489. catch
  490. {
  491. return null;
  492. }
  493. }
  494. return path;
  495. }
  496. /// <summary>
  497. /// Gets the converted ass path.
  498. /// </summary>
  499. /// <param name="mediaPath">The media path.</param>
  500. /// <param name="subtitleStream">The subtitle stream.</param>
  501. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  502. /// <returns>System.String.</returns>
  503. private string GetConvertedAssPath(string mediaPath, MediaStream subtitleStream, bool performConversion)
  504. {
  505. var path = FFMpegManager.Instance.GetSubtitleCachePath(mediaPath, subtitleStream, ".ass");
  506. if (performConversion)
  507. {
  508. try
  509. {
  510. var parentPath = Path.GetDirectoryName(path);
  511. Directory.CreateDirectory(parentPath);
  512. var task = MediaEncoder.ConvertTextSubtitleToAss(subtitleStream.Path, path, subtitleStream.Language, CancellationToken.None);
  513. Task.WaitAll(task);
  514. }
  515. catch
  516. {
  517. return null;
  518. }
  519. }
  520. return path;
  521. }
  522. /// <summary>
  523. /// Gets the internal graphical subtitle param.
  524. /// </summary>
  525. /// <param name="state">The state.</param>
  526. /// <param name="outputVideoCodec">The output video codec.</param>
  527. /// <returns>System.String.</returns>
  528. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  529. {
  530. var outputSizeParam = string.Empty;
  531. var request = state.VideoRequest;
  532. // Add resolution params, if specified
  533. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  534. {
  535. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec, false).TrimEnd('"');
  536. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  537. }
  538. var videoSizeParam = string.Empty;
  539. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  540. {
  541. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  542. }
  543. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p{3},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{1}] [sub] overlay{2}\"",
  544. state.SubtitleStream.Index,
  545. state.VideoStream.Index,
  546. outputSizeParam,
  547. videoSizeParam);
  548. }
  549. /// <summary>
  550. /// Gets the probe size argument.
  551. /// </summary>
  552. /// <param name="mediaPath">The media path.</param>
  553. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  554. /// <param name="videoType">Type of the video.</param>
  555. /// <param name="isoType">Type of the iso.</param>
  556. /// <returns>System.String.</returns>
  557. private string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  558. {
  559. var type = !isVideo ? MediaEncoderHelpers.GetInputType(null, null) :
  560. MediaEncoderHelpers.GetInputType(videoType, isoType);
  561. return MediaEncoder.GetProbeSizeArgument(type);
  562. }
  563. /// <summary>
  564. /// Gets the number of audio channels to specify on the command line
  565. /// </summary>
  566. /// <param name="request">The request.</param>
  567. /// <param name="audioStream">The audio stream.</param>
  568. /// <returns>System.Nullable{System.Int32}.</returns>
  569. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  570. {
  571. if (audioStream != null)
  572. {
  573. if (audioStream.Channels > 2 && request.AudioCodec.HasValue)
  574. {
  575. if (request.AudioCodec.Value == AudioCodecs.Wma)
  576. {
  577. // wmav2 currently only supports two channel output
  578. return 2;
  579. }
  580. }
  581. }
  582. return request.AudioChannels;
  583. }
  584. /// <summary>
  585. /// Determines whether the specified stream is H264.
  586. /// </summary>
  587. /// <param name="stream">The stream.</param>
  588. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  589. protected bool IsH264(MediaStream stream)
  590. {
  591. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  592. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  593. }
  594. /// <summary>
  595. /// Gets the name of the output audio codec
  596. /// </summary>
  597. /// <param name="request">The request.</param>
  598. /// <returns>System.String.</returns>
  599. protected string GetAudioCodec(StreamRequest request)
  600. {
  601. var codec = request.AudioCodec;
  602. if (codec.HasValue)
  603. {
  604. if (codec == AudioCodecs.Aac)
  605. {
  606. return "aac -strict experimental";
  607. }
  608. if (codec == AudioCodecs.Mp3)
  609. {
  610. return "libmp3lame";
  611. }
  612. if (codec == AudioCodecs.Vorbis)
  613. {
  614. return "libvorbis";
  615. }
  616. if (codec == AudioCodecs.Wma)
  617. {
  618. return "wmav2";
  619. }
  620. return codec.ToString().ToLower();
  621. }
  622. return "copy";
  623. }
  624. /// <summary>
  625. /// Gets the name of the output video codec
  626. /// </summary>
  627. /// <param name="request">The request.</param>
  628. /// <returns>System.String.</returns>
  629. protected string GetVideoCodec(VideoStreamRequest request)
  630. {
  631. var codec = request.VideoCodec;
  632. if (codec.HasValue)
  633. {
  634. if (codec == VideoCodecs.H264)
  635. {
  636. return "libx264";
  637. }
  638. if (codec == VideoCodecs.Vpx)
  639. {
  640. return "libvpx";
  641. }
  642. if (codec == VideoCodecs.Wmv)
  643. {
  644. return "msmpeg4";
  645. }
  646. if (codec == VideoCodecs.Theora)
  647. {
  648. return "libtheora";
  649. }
  650. return codec.ToString().ToLower();
  651. }
  652. return "copy";
  653. }
  654. /// <summary>
  655. /// Gets the input argument.
  656. /// </summary>
  657. /// <param name="state">The state.</param>
  658. /// <returns>System.String.</returns>
  659. protected string GetInputArgument(StreamState state)
  660. {
  661. if (state.SendInputOverStandardInput)
  662. {
  663. return "-";
  664. }
  665. var type = InputType.File;
  666. var inputPath = new[] { state.MediaPath };
  667. if (state.IsInputVideo)
  668. {
  669. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  670. {
  671. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  672. }
  673. }
  674. return MediaEncoder.GetInputArgument(inputPath, type);
  675. }
  676. /// <summary>
  677. /// Starts the FFMPEG.
  678. /// </summary>
  679. /// <param name="state">The state.</param>
  680. /// <param name="outputPath">The output path.</param>
  681. /// <returns>Task.</returns>
  682. protected async Task StartFfMpeg(StreamState state, string outputPath)
  683. {
  684. if (!File.Exists(MediaEncoder.EncoderPath))
  685. {
  686. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  687. }
  688. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  689. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  690. {
  691. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  692. }
  693. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  694. if (ServerConfigurationManager.Configuration.EnableDebugEncodingLogging)
  695. {
  696. commandLineArgs = "-loglevel debug " + commandLineArgs;
  697. }
  698. var process = new Process
  699. {
  700. StartInfo = new ProcessStartInfo
  701. {
  702. CreateNoWindow = true,
  703. UseShellExecute = false,
  704. // Must consume both stdout and stderr or deadlocks may occur
  705. RedirectStandardOutput = true,
  706. RedirectStandardError = true,
  707. FileName = MediaEncoder.EncoderPath,
  708. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  709. Arguments = commandLineArgs,
  710. WindowStyle = ProcessWindowStyle.Hidden,
  711. ErrorDialog = false,
  712. RedirectStandardInput = state.SendInputOverStandardInput
  713. },
  714. EnableRaisingEvents = true
  715. };
  716. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  717. Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  718. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  719. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  720. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  721. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  722. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  723. try
  724. {
  725. process.Start();
  726. }
  727. catch (Exception ex)
  728. {
  729. Logger.ErrorException("Error starting ffmpeg", ex);
  730. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  731. state.LogFileStream.Dispose();
  732. throw;
  733. }
  734. if (state.SendInputOverStandardInput)
  735. {
  736. StreamToStandardInput(process, state);
  737. }
  738. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  739. process.BeginOutputReadLine();
  740. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  741. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  742. // Wait for the file to exist before proceeeding
  743. while (!File.Exists(outputPath))
  744. {
  745. await Task.Delay(100).ConfigureAwait(false);
  746. }
  747. // Allow a small amount of time to buffer a little
  748. if (state.IsInputVideo)
  749. {
  750. await Task.Delay(500).ConfigureAwait(false);
  751. }
  752. // This is arbitrary, but add a little buffer time when internet streaming
  753. if (state.IsRemote)
  754. {
  755. await Task.Delay(3000).ConfigureAwait(false);
  756. }
  757. }
  758. private async void StreamToStandardInput(Process process, StreamState state)
  759. {
  760. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  761. try
  762. {
  763. await StreamToStandardInputInternal(process, state).ConfigureAwait(false);
  764. }
  765. catch (OperationCanceledException)
  766. {
  767. Logger.Debug("Stream to standard input closed normally.");
  768. }
  769. catch (Exception ex)
  770. {
  771. Logger.ErrorException("Error writing to standard input", ex);
  772. }
  773. }
  774. private async Task StreamToStandardInputInternal(Process process, StreamState state)
  775. {
  776. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  777. using (var fileStream = FileSystem.GetFileStream(state.MediaPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  778. {
  779. await new EndlessStreamCopy().CopyStream(fileStream, process.StandardInput.BaseStream, state.StandardInputCancellationTokenSource.Token).ConfigureAwait(false);
  780. }
  781. }
  782. protected int? GetVideoBitrateParamValue(StreamState state)
  783. {
  784. return state.VideoRequest.VideoBitRate;
  785. }
  786. protected string GetVideoBitrateParam(StreamState state, string videoCodec, bool isHls)
  787. {
  788. var bitrate = GetVideoBitrateParamValue(state);
  789. if (bitrate.HasValue)
  790. {
  791. var hasFixedResolution = state.VideoRequest.HasFixedResolution;
  792. if (isHls)
  793. {
  794. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  795. }
  796. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  797. {
  798. if (hasFixedResolution)
  799. {
  800. return string.Format(" -minrate:v ({0}*.90) -maxrate:v ({0}*1.10) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  801. }
  802. // With vpx when crf is used, b:v becomes a max rate
  803. // https://trac.ffmpeg.org/wiki/vpxEncodingGuide
  804. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  805. }
  806. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  807. {
  808. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  809. }
  810. // H264
  811. if (hasFixedResolution)
  812. {
  813. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  814. }
  815. return string.Format(" -maxrate {0} -bufsize {1}",
  816. bitrate.Value.ToString(UsCulture),
  817. (bitrate.Value * 2).ToString(UsCulture));
  818. }
  819. return string.Empty;
  820. }
  821. protected int? GetAudioBitrateParam(StreamState state)
  822. {
  823. if (state.Request.AudioBitRate.HasValue)
  824. {
  825. // Make sure we don't request a bitrate higher than the source
  826. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  827. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  828. }
  829. return null;
  830. }
  831. /// <summary>
  832. /// Gets the user agent param.
  833. /// </summary>
  834. /// <param name="path">The path.</param>
  835. /// <returns>System.String.</returns>
  836. private string GetUserAgentParam(string path)
  837. {
  838. var useragent = GetUserAgent(path);
  839. if (!string.IsNullOrEmpty(useragent))
  840. {
  841. return "-user-agent \"" + useragent + "\"";
  842. }
  843. return string.Empty;
  844. }
  845. /// <summary>
  846. /// Gets the user agent.
  847. /// </summary>
  848. /// <param name="path">The path.</param>
  849. /// <returns>System.String.</returns>
  850. protected string GetUserAgent(string path)
  851. {
  852. if (string.IsNullOrEmpty(path))
  853. {
  854. throw new ArgumentNullException("path");
  855. }
  856. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  857. {
  858. return "QuickTime/7.7.4";
  859. }
  860. return string.Empty;
  861. }
  862. /// <summary>
  863. /// Processes the exited.
  864. /// </summary>
  865. /// <param name="process">The process.</param>
  866. /// <param name="state">The state.</param>
  867. protected async void OnFfMpegProcessExited(Process process, StreamState state)
  868. {
  869. if (state.IsoMount != null)
  870. {
  871. state.IsoMount.Dispose();
  872. state.IsoMount = null;
  873. }
  874. if (state.StandardInputCancellationTokenSource != null)
  875. {
  876. state.StandardInputCancellationTokenSource.Cancel();
  877. }
  878. var outputFilePath = GetOutputFilePath(state);
  879. state.LogFileStream.Dispose();
  880. try
  881. {
  882. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  883. }
  884. catch
  885. {
  886. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  887. }
  888. if (!string.IsNullOrEmpty(state.LiveTvStreamId))
  889. {
  890. try
  891. {
  892. await LiveTvManager.CloseLiveStream(state.LiveTvStreamId, CancellationToken.None).ConfigureAwait(false);
  893. }
  894. catch (Exception ex)
  895. {
  896. Logger.ErrorException("Error closing live tv stream", ex);
  897. }
  898. }
  899. }
  900. protected double? GetFramerateParam(StreamState state)
  901. {
  902. if (state.VideoRequest != null && state.VideoRequest.Framerate.HasValue)
  903. {
  904. return state.VideoRequest.Framerate.Value;
  905. }
  906. if (state.VideoStream != null)
  907. {
  908. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  909. if (contentRate.HasValue && contentRate.Value > 23.976)
  910. {
  911. return 23.976;
  912. }
  913. }
  914. return null;
  915. }
  916. /// <summary>
  917. /// Gets the state.
  918. /// </summary>
  919. /// <param name="request">The request.</param>
  920. /// <param name="cancellationToken">The cancellation token.</param>
  921. /// <returns>StreamState.</returns>
  922. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  923. {
  924. if (request.ThrowDebugError)
  925. {
  926. throw new InvalidOperationException("You asked for a debug error, you got one.");
  927. }
  928. var user = AuthorizationRequestFilterAttribute.GetCurrentUser(Request, UserManager);
  929. if (user != null && !user.Configuration.EnableMediaPlayback)
  930. {
  931. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  932. }
  933. var url = Request.PathInfo;
  934. if (!request.AudioCodec.HasValue)
  935. {
  936. request.AudioCodec = InferAudioCodec(url);
  937. }
  938. var state = new StreamState
  939. {
  940. Request = request,
  941. RequestedUrl = url
  942. };
  943. var item = DtoService.GetItemByDtoId(request.Id);
  944. if (item is ILiveTvRecording)
  945. {
  946. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  947. state.VideoType = VideoType.VideoFile;
  948. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  949. state.PlayableStreamFileNames = new List<string>();
  950. if (!string.IsNullOrEmpty(recording.RecordingInfo.Path) && File.Exists(recording.RecordingInfo.Path))
  951. {
  952. state.MediaPath = recording.RecordingInfo.Path;
  953. state.IsRemote = false;
  954. }
  955. else if (!string.IsNullOrEmpty(recording.RecordingInfo.Url))
  956. {
  957. state.MediaPath = recording.RecordingInfo.Url;
  958. state.IsRemote = true;
  959. }
  960. else
  961. {
  962. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  963. state.LiveTvStreamId = streamInfo.Id;
  964. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  965. {
  966. state.MediaPath = streamInfo.Path;
  967. state.IsRemote = false;
  968. }
  969. else if (!string.IsNullOrEmpty(streamInfo.Url))
  970. {
  971. state.MediaPath = streamInfo.Url;
  972. state.IsRemote = true;
  973. }
  974. }
  975. //state.RunTimeTicks = recording.RunTimeTicks;
  976. state.ReadInputAtNativeFramerate = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  977. state.SendInputOverStandardInput = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  978. state.AudioSync = "1000";
  979. state.DeInterlace = true;
  980. }
  981. else if (item is LiveTvChannel)
  982. {
  983. var channel = LiveTvManager.GetInternalChannel(request.Id);
  984. state.VideoType = VideoType.VideoFile;
  985. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  986. state.PlayableStreamFileNames = new List<string>();
  987. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  988. state.LiveTvStreamId = streamInfo.Id;
  989. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  990. {
  991. state.MediaPath = streamInfo.Path;
  992. state.IsRemote = false;
  993. }
  994. else if (!string.IsNullOrEmpty(streamInfo.Url))
  995. {
  996. state.MediaPath = streamInfo.Url;
  997. state.IsRemote = true;
  998. }
  999. state.SendInputOverStandardInput = true;
  1000. state.ReadInputAtNativeFramerate = true;
  1001. state.AudioSync = "1000";
  1002. state.DeInterlace = true;
  1003. }
  1004. else
  1005. {
  1006. state.MediaPath = item.Path;
  1007. state.IsRemote = item.LocationType == LocationType.Remote;
  1008. var video = item as Video;
  1009. if (video != null)
  1010. {
  1011. state.IsInputVideo = true;
  1012. state.VideoType = video.VideoType;
  1013. state.IsoType = video.IsoType;
  1014. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  1015. ? new List<string>()
  1016. : video.PlayableStreamFileNames.ToList();
  1017. }
  1018. state.RunTimeTicks = item.RunTimeTicks;
  1019. }
  1020. var videoRequest = request as VideoStreamRequest;
  1021. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  1022. {
  1023. ItemId = item.Id
  1024. }).ToList();
  1025. if (videoRequest != null)
  1026. {
  1027. if (!videoRequest.VideoCodec.HasValue)
  1028. {
  1029. videoRequest.VideoCodec = InferVideoCodec(url);
  1030. }
  1031. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  1032. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  1033. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  1034. EnforceResolutionLimit(state, videoRequest);
  1035. }
  1036. else
  1037. {
  1038. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  1039. }
  1040. state.HasMediaStreams = mediaStreams.Count > 0;
  1041. return state;
  1042. }
  1043. /// <summary>
  1044. /// Enforces the resolution limit.
  1045. /// </summary>
  1046. /// <param name="state">The state.</param>
  1047. /// <param name="videoRequest">The video request.</param>
  1048. private void EnforceResolutionLimit(StreamState state, VideoStreamRequest videoRequest)
  1049. {
  1050. // If enabled, allow whatever the client asks for
  1051. if (ServerConfigurationManager.Configuration.AllowVideoUpscaling)
  1052. {
  1053. return;
  1054. }
  1055. // Switch the incoming params to be ceilings rather than fixed values
  1056. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1057. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1058. videoRequest.Width = null;
  1059. videoRequest.Height = null;
  1060. }
  1061. protected string GetInputModifier(StreamState state)
  1062. {
  1063. var inputModifier = string.Empty;
  1064. var probeSize = GetProbeSizeArgument(state.MediaPath, state.IsInputVideo, state.VideoType, state.IsoType);
  1065. inputModifier += " " + probeSize;
  1066. inputModifier = inputModifier.Trim();
  1067. inputModifier += " " + GetUserAgentParam(state.MediaPath);
  1068. inputModifier = inputModifier.Trim();
  1069. inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
  1070. inputModifier = inputModifier.Trim();
  1071. if (state.VideoRequest != null)
  1072. {
  1073. inputModifier += " -fflags genpts";
  1074. }
  1075. if (!string.IsNullOrEmpty(state.InputFormat))
  1076. {
  1077. inputModifier += " -f " + state.InputFormat;
  1078. }
  1079. if (!string.IsNullOrEmpty(state.InputVideoCodec))
  1080. {
  1081. inputModifier += " -vcodec " + state.InputVideoCodec;
  1082. }
  1083. if (!string.IsNullOrEmpty(state.InputAudioCodec))
  1084. {
  1085. inputModifier += " -acodec " + state.InputAudioCodec;
  1086. }
  1087. if (state.ReadInputAtNativeFramerate)
  1088. {
  1089. inputModifier += " -re";
  1090. }
  1091. return inputModifier;
  1092. }
  1093. /// <summary>
  1094. /// Infers the audio codec based on the url
  1095. /// </summary>
  1096. /// <param name="url">The URL.</param>
  1097. /// <returns>System.Nullable{AudioCodecs}.</returns>
  1098. private AudioCodecs? InferAudioCodec(string url)
  1099. {
  1100. var ext = Path.GetExtension(url);
  1101. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  1102. {
  1103. return AudioCodecs.Mp3;
  1104. }
  1105. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  1106. {
  1107. return AudioCodecs.Aac;
  1108. }
  1109. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  1110. {
  1111. return AudioCodecs.Wma;
  1112. }
  1113. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  1114. {
  1115. return AudioCodecs.Vorbis;
  1116. }
  1117. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  1118. {
  1119. return AudioCodecs.Vorbis;
  1120. }
  1121. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1122. {
  1123. return AudioCodecs.Vorbis;
  1124. }
  1125. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1126. {
  1127. return AudioCodecs.Vorbis;
  1128. }
  1129. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  1130. {
  1131. return AudioCodecs.Vorbis;
  1132. }
  1133. return null;
  1134. }
  1135. /// <summary>
  1136. /// Infers the video codec.
  1137. /// </summary>
  1138. /// <param name="url">The URL.</param>
  1139. /// <returns>System.Nullable{VideoCodecs}.</returns>
  1140. private VideoCodecs? InferVideoCodec(string url)
  1141. {
  1142. var ext = Path.GetExtension(url);
  1143. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  1144. {
  1145. return VideoCodecs.Wmv;
  1146. }
  1147. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1148. {
  1149. return VideoCodecs.Vpx;
  1150. }
  1151. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1152. {
  1153. return VideoCodecs.Theora;
  1154. }
  1155. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  1156. {
  1157. return VideoCodecs.H264;
  1158. }
  1159. return VideoCodecs.Copy;
  1160. }
  1161. }
  1162. }