BaseStreamingService.cs 51 KB

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