BaseStreamingService.cs 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640
  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.MediaEncoding;
  9. using MediaBrowser.Controller.Persistence;
  10. using MediaBrowser.Model.Configuration;
  11. using MediaBrowser.Model.Drawing;
  12. using MediaBrowser.Model.Entities;
  13. using MediaBrowser.Model.IO;
  14. using MediaBrowser.Model.Library;
  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 IEncodingManager EncodingManager { get; private set; }
  57. protected IDtoService DtoService { get; private set; }
  58. protected IFileSystem FileSystem { get; private set; }
  59. protected IItemRepository ItemRepository { get; private set; }
  60. protected ILiveTvManager LiveTvManager { get; private set; }
  61. /// <summary>
  62. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  63. /// </summary>
  64. /// <param name="serverConfig">The server configuration.</param>
  65. /// <param name="userManager">The user manager.</param>
  66. /// <param name="libraryManager">The library manager.</param>
  67. /// <param name="isoManager">The iso manager.</param>
  68. /// <param name="mediaEncoder">The media encoder.</param>
  69. /// <param name="dtoService">The dto service.</param>
  70. /// <param name="fileSystem">The file system.</param>
  71. /// <param name="itemRepository">The item repository.</param>
  72. protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository, ILiveTvManager liveTvManager, IEncodingManager encodingManager)
  73. {
  74. EncodingManager = encodingManager;
  75. LiveTvManager = liveTvManager;
  76. ItemRepository = itemRepository;
  77. FileSystem = fileSystem;
  78. DtoService = dtoService;
  79. ServerConfigurationManager = serverConfig;
  80. UserManager = userManager;
  81. LibraryManager = libraryManager;
  82. IsoManager = isoManager;
  83. MediaEncoder = mediaEncoder;
  84. }
  85. /// <summary>
  86. /// Gets the command line arguments.
  87. /// </summary>
  88. /// <param name="outputPath">The output path.</param>
  89. /// <param name="state">The state.</param>
  90. /// <param name="performSubtitleConversions">if set to <c>true</c> [perform subtitle conversions].</param>
  91. /// <returns>System.String.</returns>
  92. protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool performSubtitleConversions);
  93. /// <summary>
  94. /// Gets the type of the transcoding job.
  95. /// </summary>
  96. /// <value>The type of the transcoding job.</value>
  97. protected abstract TranscodingJobType TranscodingJobType { get; }
  98. /// <summary>
  99. /// Gets the output file extension.
  100. /// </summary>
  101. /// <param name="state">The state.</param>
  102. /// <returns>System.String.</returns>
  103. protected virtual string GetOutputFileExtension(StreamState state)
  104. {
  105. return Path.GetExtension(state.RequestedUrl);
  106. }
  107. /// <summary>
  108. /// Gets the output file path.
  109. /// </summary>
  110. /// <param name="state">The state.</param>
  111. /// <returns>System.String.</returns>
  112. protected virtual string GetOutputFilePath(StreamState state)
  113. {
  114. var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
  115. var outputFileExtension = GetOutputFileExtension(state);
  116. return Path.Combine(folder, GetCommandLineArguments("dummy\\dummy", state, false).GetMD5() + (outputFileExtension ?? string.Empty).ToLower());
  117. }
  118. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  119. /// <summary>
  120. /// The fast seek offset seconds
  121. /// </summary>
  122. private const int FastSeekOffsetSeconds = 1;
  123. /// <summary>
  124. /// Gets the fast seek command line parameter.
  125. /// </summary>
  126. /// <param name="request">The request.</param>
  127. /// <returns>System.String.</returns>
  128. /// <value>The fast seek command line parameter.</value>
  129. protected string GetFastSeekCommandLineParameter(StreamRequest request)
  130. {
  131. var time = request.StartTimeTicks;
  132. if (time.HasValue)
  133. {
  134. var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds;
  135. if (seconds > 0)
  136. {
  137. return string.Format("-ss {0}", seconds.ToString(UsCulture));
  138. }
  139. }
  140. return string.Empty;
  141. }
  142. /// <summary>
  143. /// Gets the slow seek command line parameter.
  144. /// </summary>
  145. /// <param name="request">The request.</param>
  146. /// <returns>System.String.</returns>
  147. /// <value>The slow seek command line parameter.</value>
  148. protected string GetSlowSeekCommandLineParameter(StreamRequest request)
  149. {
  150. var time = request.StartTimeTicks;
  151. if (time.HasValue)
  152. {
  153. if (TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds > 0)
  154. {
  155. return string.Format(" -ss {0}", FastSeekOffsetSeconds.ToString(UsCulture));
  156. }
  157. }
  158. return string.Empty;
  159. }
  160. /// <summary>
  161. /// Gets the map args.
  162. /// </summary>
  163. /// <param name="state">The state.</param>
  164. /// <returns>System.String.</returns>
  165. protected virtual string GetMapArgs(StreamState state)
  166. {
  167. var args = string.Empty;
  168. if (state.IsRemote || !state.HasMediaStreams)
  169. {
  170. return string.Empty;
  171. }
  172. if (state.VideoStream != null)
  173. {
  174. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  175. }
  176. else
  177. {
  178. args += "-map -0:v";
  179. }
  180. if (state.AudioStream != null)
  181. {
  182. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  183. }
  184. else
  185. {
  186. args += " -map -0:a";
  187. }
  188. if (state.SubtitleStream == null)
  189. {
  190. args += " -map -0:s";
  191. }
  192. return args;
  193. }
  194. /// <summary>
  195. /// Determines which stream will be used for playback
  196. /// </summary>
  197. /// <param name="allStream">All stream.</param>
  198. /// <param name="desiredIndex">Index of the desired.</param>
  199. /// <param name="type">The type.</param>
  200. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  201. /// <returns>MediaStream.</returns>
  202. private MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  203. {
  204. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  205. if (desiredIndex.HasValue)
  206. {
  207. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  208. if (stream != null)
  209. {
  210. return stream;
  211. }
  212. }
  213. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  214. {
  215. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  216. streams.FirstOrDefault();
  217. }
  218. // Just return the first one
  219. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  220. }
  221. protected EncodingQuality GetQualitySetting()
  222. {
  223. var quality = ServerConfigurationManager.Configuration.MediaEncodingQuality;
  224. if (quality == EncodingQuality.Auto)
  225. {
  226. var cpuCount = Environment.ProcessorCount;
  227. if (cpuCount >= 4)
  228. {
  229. //return EncodingQuality.HighQuality;
  230. }
  231. return EncodingQuality.HighSpeed;
  232. }
  233. return quality;
  234. }
  235. /// <summary>
  236. /// Gets the number of threads.
  237. /// </summary>
  238. /// <returns>System.Int32.</returns>
  239. /// <exception cref="System.Exception">Unrecognized MediaEncodingQuality value.</exception>
  240. protected int GetNumberOfThreads(StreamState state, bool isWebm)
  241. {
  242. // Use more when this is true. -re will keep cpu usage under control
  243. if (state.ReadInputAtNativeFramerate)
  244. {
  245. if (isWebm)
  246. {
  247. return Math.Max(Environment.ProcessorCount - 1, 1);
  248. }
  249. return 0;
  250. }
  251. // Webm: http://www.webmproject.org/docs/encoder-parameters/
  252. // 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
  253. // for the coefficient data if the encoder selected --token-parts > 0 at encode time.
  254. switch (GetQualitySetting())
  255. {
  256. case EncodingQuality.HighSpeed:
  257. return 2;
  258. case EncodingQuality.HighQuality:
  259. return 2;
  260. case EncodingQuality.MaxQuality:
  261. return isWebm ? 2 : 0;
  262. default:
  263. throw new Exception("Unrecognized MediaEncodingQuality value.");
  264. }
  265. }
  266. /// <summary>
  267. /// Gets the video bitrate to specify on the command line
  268. /// </summary>
  269. /// <param name="state">The state.</param>
  270. /// <param name="videoCodec">The video codec.</param>
  271. /// <returns>System.String.</returns>
  272. protected string GetVideoQualityParam(StreamState state, string videoCodec, bool isHls)
  273. {
  274. var param = string.Empty;
  275. var hasFixedResolution = state.VideoRequest.HasFixedResolution;
  276. var qualitySetting = GetQualitySetting();
  277. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  278. {
  279. switch (qualitySetting)
  280. {
  281. case EncodingQuality.HighSpeed:
  282. param = "-preset ultrafast";
  283. break;
  284. case EncodingQuality.HighQuality:
  285. param = "-preset superfast";
  286. break;
  287. case EncodingQuality.MaxQuality:
  288. param = "-preset superfast";
  289. break;
  290. }
  291. if (!isHls)
  292. {
  293. switch (qualitySetting)
  294. {
  295. case EncodingQuality.HighSpeed:
  296. param += " -crf 23";
  297. break;
  298. case EncodingQuality.HighQuality:
  299. param += " -crf 20";
  300. break;
  301. case EncodingQuality.MaxQuality:
  302. param += " -crf 18";
  303. break;
  304. }
  305. }
  306. }
  307. // webm
  308. else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  309. {
  310. // http://www.webmproject.org/docs/encoder-parameters/
  311. param = "-speed 16 -quality good -profile:v 0 -slices 8";
  312. if (!hasFixedResolution)
  313. {
  314. switch (qualitySetting)
  315. {
  316. case EncodingQuality.HighSpeed:
  317. param += " -crf 18";
  318. break;
  319. case EncodingQuality.HighQuality:
  320. param += " -crf 10";
  321. break;
  322. case EncodingQuality.MaxQuality:
  323. param += " -crf 4";
  324. break;
  325. }
  326. }
  327. }
  328. else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  329. {
  330. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  331. }
  332. // asf/wmv
  333. else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
  334. {
  335. param = "-qmin 2";
  336. }
  337. else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  338. {
  339. param = "-mbd 2";
  340. }
  341. param += GetVideoBitrateParam(state, videoCodec, isHls);
  342. var framerate = GetFramerateParam(state);
  343. if (framerate.HasValue)
  344. {
  345. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  346. }
  347. if (!string.IsNullOrEmpty(state.VideoSync))
  348. {
  349. param += " -vsync " + state.VideoSync;
  350. }
  351. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  352. {
  353. param += " -profile:v " + state.VideoRequest.Profile;
  354. }
  355. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  356. {
  357. param += " -level " + state.VideoRequest.Level;
  358. }
  359. return param;
  360. }
  361. protected string GetAudioFilterParam(StreamState state, bool isHls)
  362. {
  363. var volParam = string.Empty;
  364. var audioSampleRate = string.Empty;
  365. var channels = GetNumAudioChannelsParam(state.Request, state.AudioStream);
  366. // Boost volume to 200% when downsampling from 6ch to 2ch
  367. if (channels.HasValue && channels.Value <= 2 && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  368. {
  369. volParam = ",volume=2.000000";
  370. }
  371. if (state.Request.AudioSampleRate.HasValue)
  372. {
  373. audioSampleRate = state.Request.AudioSampleRate.Value + ":";
  374. }
  375. var adelay = isHls ? "adelay=1," : string.Empty;
  376. var pts = string.Empty;
  377. if (state.SubtitleStream != null)
  378. {
  379. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  380. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  381. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  382. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  383. {
  384. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  385. pts = string.Format(",asetpts=PTS-{0}/TB",
  386. Math.Round(seconds).ToString(UsCulture));
  387. }
  388. }
  389. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  390. adelay,
  391. audioSampleRate,
  392. volParam,
  393. pts,
  394. state.AudioSync);
  395. }
  396. /// <summary>
  397. /// If we're going to put a fixed size on the command line, this will calculate it
  398. /// </summary>
  399. /// <param name="state">The state.</param>
  400. /// <param name="outputVideoCodec">The output video codec.</param>
  401. /// <param name="performTextSubtitleConversion">if set to <c>true</c> [perform text subtitle conversion].</param>
  402. /// <returns>System.String.</returns>
  403. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec, bool performTextSubtitleConversion)
  404. {
  405. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  406. var assSubtitleParam = string.Empty;
  407. var copyTsParam = string.Empty;
  408. var yadifParam = state.DeInterlace ? "yadif=0:-1:0," : string.Empty;
  409. var request = state.VideoRequest;
  410. if (state.SubtitleStream != null)
  411. {
  412. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  413. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  414. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  415. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  416. {
  417. assSubtitleParam = GetTextSubtitleParam(state, performTextSubtitleConversion);
  418. copyTsParam = " -copyts";
  419. }
  420. }
  421. // If fixed dimensions were supplied
  422. if (request.Width.HasValue && request.Height.HasValue)
  423. {
  424. var widthParam = request.Width.Value.ToString(UsCulture);
  425. var heightParam = request.Height.Value.ToString(UsCulture);
  426. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  427. }
  428. // If Max dimensions were supplied
  429. //this makes my brain hurt. For width selects lowest even number between input width and width req size and selects lowest even number from in width*display aspect and requested size
  430. if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  431. {
  432. var MaxwidthParam = request.MaxWidth.Value.ToString(UsCulture);
  433. var MaxheightParam = request.MaxHeight.Value.ToString(UsCulture);
  434. return string.Format("{4} -vf \"{0}scale=trunc(min(iw\\,{1})/2)*2:trunc(min((iw/dar)\\,{2})/2)*2{3}\"", yadifParam, MaxwidthParam, MaxheightParam, assSubtitleParam, copyTsParam);
  435. }
  436. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  437. // If a fixed width was requested
  438. if (request.Width.HasValue)
  439. {
  440. var widthParam = request.Width.Value.ToString(UsCulture);
  441. return isH264Output ?
  442. string.Format("{3} -vf \"{0}scale={1}:trunc(ow/a/2)*2{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam) :
  443. string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam);
  444. }
  445. // If a fixed height was requested
  446. if (request.Height.HasValue)
  447. {
  448. var heightParam = request.Height.Value.ToString(UsCulture);
  449. return isH264Output ?
  450. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam) :
  451. string.Format("{3} -vf \"{0}scale=-1:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam);
  452. }
  453. // If a max width was requested
  454. if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null))
  455. {
  456. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  457. return isH264Output ?
  458. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):trunc(ow/a/2)*2{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam) :
  459. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):-1{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam);
  460. }
  461. // If a max height was requested
  462. if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null))
  463. {
  464. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  465. return isH264Output ?
  466. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam) :
  467. string.Format("{3} -vf \"{0}scale=-1:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam);
  468. }
  469. if (state.VideoStream == null)
  470. {
  471. // No way to figure this out
  472. return string.Empty;
  473. }
  474. // Need to perform calculations manually
  475. // Try to account for bad media info
  476. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  477. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  478. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  479. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  480. if (isH264Output)
  481. {
  482. var widthParam = outputSize.Width.ToString(UsCulture);
  483. var heightParam = outputSize.Height.ToString(UsCulture);
  484. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  485. }
  486. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  487. return string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, Convert.ToInt32(outputSize.Width), assSubtitleParam, copyTsParam);
  488. }
  489. /// <summary>
  490. /// Gets the text subtitle param.
  491. /// </summary>
  492. /// <param name="state">The state.</param>
  493. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  494. /// <returns>System.String.</returns>
  495. protected string GetTextSubtitleParam(StreamState state, bool performConversion)
  496. {
  497. var path = state.SubtitleStream.IsExternal ? GetConvertedAssPath(state.MediaPath, state.SubtitleStream, performConversion) :
  498. GetExtractedAssPath(state, performConversion);
  499. if (string.IsNullOrEmpty(path))
  500. {
  501. return string.Empty;
  502. }
  503. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  504. return string.Format(",ass='{0}',setpts=PTS -{1}/TB",
  505. path.Replace('\\', '/').Replace(":/", "\\:/"),
  506. Math.Round(seconds).ToString(UsCulture));
  507. }
  508. /// <summary>
  509. /// Gets the extracted ass path.
  510. /// </summary>
  511. /// <param name="state">The state.</param>
  512. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  513. /// <returns>System.String.</returns>
  514. private string GetExtractedAssPath(StreamState state, bool performConversion)
  515. {
  516. var path = EncodingManager.GetSubtitleCachePath(state.MediaPath, state.SubtitleStream.Index, ".ass");
  517. if (performConversion)
  518. {
  519. InputType type;
  520. var inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, null, state.PlayableStreamFileNames, out type);
  521. try
  522. {
  523. var parentPath = Path.GetDirectoryName(path);
  524. Directory.CreateDirectory(parentPath);
  525. // Don't re-encode ass/ssa to ass because ffmpeg ass encoder fails if there's more than one ass rectangle. Affect Anime mostly.
  526. // See https://lists.ffmpeg.org/pipermail/ffmpeg-cvslog/2013-April/063616.html
  527. var isAssSubtitle = string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase);
  528. var task = MediaEncoder.ExtractTextSubtitle(inputPath, type, state.SubtitleStream.Index, isAssSubtitle, path, CancellationToken.None);
  529. Task.WaitAll(task);
  530. }
  531. catch
  532. {
  533. return null;
  534. }
  535. }
  536. return path;
  537. }
  538. /// <summary>
  539. /// Gets the converted ass path.
  540. /// </summary>
  541. /// <param name="mediaPath">The media path.</param>
  542. /// <param name="subtitleStream">The subtitle stream.</param>
  543. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  544. /// <returns>System.String.</returns>
  545. private string GetConvertedAssPath(string mediaPath, MediaStream subtitleStream, bool performConversion)
  546. {
  547. var path = EncodingManager.GetSubtitleCachePath(subtitleStream.Path, ".ass");
  548. if (performConversion)
  549. {
  550. try
  551. {
  552. var parentPath = Path.GetDirectoryName(path);
  553. Directory.CreateDirectory(parentPath);
  554. var task = MediaEncoder.ConvertTextSubtitleToAss(subtitleStream.Path, path, subtitleStream.Language, CancellationToken.None);
  555. Task.WaitAll(task);
  556. }
  557. catch
  558. {
  559. return null;
  560. }
  561. }
  562. return path;
  563. }
  564. /// <summary>
  565. /// Gets the internal graphical subtitle param.
  566. /// </summary>
  567. /// <param name="state">The state.</param>
  568. /// <param name="outputVideoCodec">The output video codec.</param>
  569. /// <returns>System.String.</returns>
  570. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  571. {
  572. var outputSizeParam = string.Empty;
  573. var request = state.VideoRequest;
  574. // Add resolution params, if specified
  575. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  576. {
  577. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec, false).TrimEnd('"');
  578. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  579. }
  580. var videoSizeParam = string.Empty;
  581. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  582. {
  583. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  584. }
  585. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p{3},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{1}] [sub] overlay{2}\"",
  586. state.SubtitleStream.Index,
  587. state.VideoStream.Index,
  588. outputSizeParam,
  589. videoSizeParam);
  590. }
  591. /// <summary>
  592. /// Gets the probe size argument.
  593. /// </summary>
  594. /// <param name="mediaPath">The media path.</param>
  595. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  596. /// <param name="videoType">Type of the video.</param>
  597. /// <param name="isoType">Type of the iso.</param>
  598. /// <returns>System.String.</returns>
  599. private string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  600. {
  601. var type = !isVideo ? MediaEncoderHelpers.GetInputType(null, null) :
  602. MediaEncoderHelpers.GetInputType(videoType, isoType);
  603. return MediaEncoder.GetProbeSizeArgument(type);
  604. }
  605. /// <summary>
  606. /// Gets the number of audio channels to specify on the command line
  607. /// </summary>
  608. /// <param name="request">The request.</param>
  609. /// <param name="audioStream">The audio stream.</param>
  610. /// <returns>System.Nullable{System.Int32}.</returns>
  611. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  612. {
  613. if (audioStream != null)
  614. {
  615. if (audioStream.Channels > 2 && string.Equals(request.AudioCodec, "wma", StringComparison.OrdinalIgnoreCase))
  616. {
  617. // wmav2 currently only supports two channel output
  618. return 2;
  619. }
  620. }
  621. if (request.MaxAudioChannels.HasValue)
  622. {
  623. if (audioStream != null && audioStream.Channels.HasValue)
  624. {
  625. return Math.Min(request.MaxAudioChannels.Value, audioStream.Channels.Value);
  626. }
  627. return request.MaxAudioChannels.Value;
  628. }
  629. return request.AudioChannels;
  630. }
  631. /// <summary>
  632. /// Determines whether the specified stream is H264.
  633. /// </summary>
  634. /// <param name="stream">The stream.</param>
  635. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  636. protected bool IsH264(MediaStream stream)
  637. {
  638. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  639. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  640. }
  641. /// <summary>
  642. /// Gets the name of the output audio codec
  643. /// </summary>
  644. /// <param name="request">The request.</param>
  645. /// <returns>System.String.</returns>
  646. protected string GetAudioCodec(StreamRequest request)
  647. {
  648. var codec = request.AudioCodec;
  649. if (!string.IsNullOrEmpty(codec))
  650. {
  651. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  652. {
  653. return "aac -strict experimental";
  654. }
  655. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  656. {
  657. return "libmp3lame";
  658. }
  659. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  660. {
  661. return "libvorbis";
  662. }
  663. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  664. {
  665. return "wmav2";
  666. }
  667. return codec.ToLower();
  668. }
  669. return "copy";
  670. }
  671. /// <summary>
  672. /// Gets the name of the output video codec
  673. /// </summary>
  674. /// <param name="request">The request.</param>
  675. /// <returns>System.String.</returns>
  676. protected string GetVideoCodec(VideoStreamRequest request)
  677. {
  678. var codec = request.VideoCodec;
  679. if (!string.IsNullOrEmpty(codec))
  680. {
  681. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  682. {
  683. return "libx264";
  684. }
  685. if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  686. {
  687. return "libvpx";
  688. }
  689. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  690. {
  691. return "msmpeg4";
  692. }
  693. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  694. {
  695. return "libtheora";
  696. }
  697. return codec.ToLower();
  698. }
  699. return "copy";
  700. }
  701. /// <summary>
  702. /// Gets the input argument.
  703. /// </summary>
  704. /// <param name="state">The state.</param>
  705. /// <returns>System.String.</returns>
  706. protected string GetInputArgument(StreamState state)
  707. {
  708. if (state.SendInputOverStandardInput)
  709. {
  710. return "-";
  711. }
  712. var type = InputType.File;
  713. var inputPath = new[] { state.MediaPath };
  714. if (state.IsInputVideo)
  715. {
  716. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  717. {
  718. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  719. }
  720. }
  721. return MediaEncoder.GetInputArgument(inputPath, type);
  722. }
  723. /// <summary>
  724. /// Starts the FFMPEG.
  725. /// </summary>
  726. /// <param name="state">The state.</param>
  727. /// <param name="outputPath">The output path.</param>
  728. /// <returns>Task.</returns>
  729. protected async Task StartFfMpeg(StreamState state, string outputPath)
  730. {
  731. if (!File.Exists(MediaEncoder.EncoderPath))
  732. {
  733. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  734. }
  735. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  736. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  737. {
  738. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  739. }
  740. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  741. if (ServerConfigurationManager.Configuration.EnableDebugEncodingLogging)
  742. {
  743. commandLineArgs = "-loglevel debug " + commandLineArgs;
  744. }
  745. var process = new Process
  746. {
  747. StartInfo = new ProcessStartInfo
  748. {
  749. CreateNoWindow = true,
  750. UseShellExecute = false,
  751. // Must consume both stdout and stderr or deadlocks may occur
  752. RedirectStandardOutput = true,
  753. RedirectStandardError = true,
  754. FileName = MediaEncoder.EncoderPath,
  755. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  756. Arguments = commandLineArgs,
  757. WindowStyle = ProcessWindowStyle.Hidden,
  758. ErrorDialog = false,
  759. RedirectStandardInput = state.SendInputOverStandardInput
  760. },
  761. EnableRaisingEvents = true
  762. };
  763. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  764. Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  765. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  766. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  767. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  768. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  769. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  770. try
  771. {
  772. process.Start();
  773. }
  774. catch (Exception ex)
  775. {
  776. Logger.ErrorException("Error starting ffmpeg", ex);
  777. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  778. state.LogFileStream.Dispose();
  779. throw;
  780. }
  781. if (state.SendInputOverStandardInput)
  782. {
  783. StreamToStandardInput(process, state);
  784. }
  785. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  786. process.BeginOutputReadLine();
  787. #pragma warning disable 4014
  788. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  789. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  790. #pragma warning restore 4014
  791. // Wait for the file to exist before proceeeding
  792. while (!File.Exists(outputPath))
  793. {
  794. await Task.Delay(100).ConfigureAwait(false);
  795. }
  796. // Allow a small amount of time to buffer a little
  797. if (state.IsInputVideo)
  798. {
  799. await Task.Delay(500).ConfigureAwait(false);
  800. }
  801. // This is arbitrary, but add a little buffer time when internet streaming
  802. if (state.IsRemote)
  803. {
  804. await Task.Delay(3000).ConfigureAwait(false);
  805. }
  806. }
  807. private async void StreamToStandardInput(Process process, StreamState state)
  808. {
  809. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  810. try
  811. {
  812. await StreamToStandardInputInternal(process, state).ConfigureAwait(false);
  813. }
  814. catch (OperationCanceledException)
  815. {
  816. Logger.Debug("Stream to standard input closed normally.");
  817. }
  818. catch (Exception ex)
  819. {
  820. Logger.ErrorException("Error writing to standard input", ex);
  821. }
  822. }
  823. private async Task StreamToStandardInputInternal(Process process, StreamState state)
  824. {
  825. state.StandardInputCancellationTokenSource = new CancellationTokenSource();
  826. using (var fileStream = FileSystem.GetFileStream(state.MediaPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  827. {
  828. await new EndlessStreamCopy().CopyStream(fileStream, process.StandardInput.BaseStream, state.StandardInputCancellationTokenSource.Token).ConfigureAwait(false);
  829. }
  830. }
  831. protected int? GetVideoBitrateParamValue(StreamState state)
  832. {
  833. var bitrate = state.VideoRequest.VideoBitRate;
  834. if (state.VideoStream != null)
  835. {
  836. var isUpscaling = state.VideoRequest.Height.HasValue && state.VideoStream.Height.HasValue &&
  837. state.VideoRequest.Height.Value > state.VideoStream.Height.Value;
  838. if (state.VideoRequest.Width.HasValue && state.VideoStream.Width.HasValue &&
  839. state.VideoRequest.Width.Value > state.VideoStream.Width.Value)
  840. {
  841. isUpscaling = true;
  842. }
  843. // Don't allow bitrate increases unless upscaling
  844. if (!isUpscaling)
  845. {
  846. if (bitrate.HasValue && state.VideoStream.BitRate.HasValue)
  847. {
  848. bitrate = Math.Min(bitrate.Value, state.VideoStream.BitRate.Value);
  849. }
  850. }
  851. }
  852. return bitrate;
  853. }
  854. protected string GetVideoBitrateParam(StreamState state, string videoCodec, bool isHls)
  855. {
  856. var bitrate = GetVideoBitrateParamValue(state);
  857. if (bitrate.HasValue)
  858. {
  859. var hasFixedResolution = state.VideoRequest.HasFixedResolution;
  860. if (isHls)
  861. {
  862. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  863. }
  864. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  865. {
  866. if (hasFixedResolution)
  867. {
  868. return string.Format(" -minrate:v ({0}*.90) -maxrate:v ({0}*1.10) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  869. }
  870. // With vpx when crf is used, b:v becomes a max rate
  871. // https://trac.ffmpeg.org/wiki/vpxEncodingGuide
  872. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  873. //return string.Format(" -minrate:v ({0}*.95) -maxrate:v ({0}*1.05) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  874. }
  875. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  876. {
  877. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  878. }
  879. // H264
  880. if (hasFixedResolution)
  881. {
  882. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  883. }
  884. return string.Format(" -maxrate {0} -bufsize {1}",
  885. bitrate.Value.ToString(UsCulture),
  886. (bitrate.Value * 2).ToString(UsCulture));
  887. }
  888. return string.Empty;
  889. }
  890. protected int? GetAudioBitrateParam(StreamState state)
  891. {
  892. if (state.Request.AudioBitRate.HasValue)
  893. {
  894. // Make sure we don't request a bitrate higher than the source
  895. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  896. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  897. }
  898. return null;
  899. }
  900. /// <summary>
  901. /// Gets the user agent param.
  902. /// </summary>
  903. /// <param name="path">The path.</param>
  904. /// <returns>System.String.</returns>
  905. private string GetUserAgentParam(string path)
  906. {
  907. var useragent = GetUserAgent(path);
  908. if (!string.IsNullOrEmpty(useragent))
  909. {
  910. return "-user-agent \"" + useragent + "\"";
  911. }
  912. return string.Empty;
  913. }
  914. /// <summary>
  915. /// Gets the user agent.
  916. /// </summary>
  917. /// <param name="path">The path.</param>
  918. /// <returns>System.String.</returns>
  919. protected string GetUserAgent(string path)
  920. {
  921. if (string.IsNullOrEmpty(path))
  922. {
  923. throw new ArgumentNullException("path");
  924. }
  925. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  926. {
  927. return "QuickTime/7.7.4";
  928. }
  929. return string.Empty;
  930. }
  931. /// <summary>
  932. /// Processes the exited.
  933. /// </summary>
  934. /// <param name="process">The process.</param>
  935. /// <param name="state">The state.</param>
  936. protected async void OnFfMpegProcessExited(Process process, StreamState state)
  937. {
  938. if (state.IsoMount != null)
  939. {
  940. state.IsoMount.Dispose();
  941. state.IsoMount = null;
  942. }
  943. if (state.StandardInputCancellationTokenSource != null)
  944. {
  945. state.StandardInputCancellationTokenSource.Cancel();
  946. }
  947. var outputFilePath = GetOutputFilePath(state);
  948. state.LogFileStream.Dispose();
  949. try
  950. {
  951. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  952. }
  953. catch
  954. {
  955. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  956. }
  957. if (!string.IsNullOrEmpty(state.LiveTvStreamId))
  958. {
  959. try
  960. {
  961. await LiveTvManager.CloseLiveStream(state.LiveTvStreamId, CancellationToken.None).ConfigureAwait(false);
  962. }
  963. catch (Exception ex)
  964. {
  965. Logger.ErrorException("Error closing live tv stream", ex);
  966. }
  967. }
  968. }
  969. protected double? GetFramerateParam(StreamState state)
  970. {
  971. if (state.VideoRequest != null)
  972. {
  973. if (state.VideoRequest.Framerate.HasValue)
  974. {
  975. return state.VideoRequest.Framerate.Value;
  976. }
  977. var maxrate = state.VideoRequest.MaxFramerate ?? 23.976;
  978. if (state.VideoStream != null)
  979. {
  980. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  981. if (contentRate.HasValue && contentRate.Value > maxrate)
  982. {
  983. return maxrate;
  984. }
  985. }
  986. }
  987. return null;
  988. }
  989. /// <summary>
  990. /// Parses the parameters.
  991. /// </summary>
  992. /// <param name="request">The request.</param>
  993. private void ParseParams(StreamRequest request)
  994. {
  995. var vals = request.Params.Split(';');
  996. var videoRequest = request as VideoStreamRequest;
  997. for (var i = 0; i < vals.Length; i++)
  998. {
  999. var val = vals[i];
  1000. if (string.IsNullOrWhiteSpace(val))
  1001. {
  1002. continue;
  1003. }
  1004. if (i == 0)
  1005. {
  1006. // Device profile name
  1007. }
  1008. else if (i == 1)
  1009. {
  1010. request.DeviceId = val;
  1011. }
  1012. else if (i == 2)
  1013. {
  1014. request.MediaSourceId = val;
  1015. }
  1016. else if (i == 3)
  1017. {
  1018. request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  1019. }
  1020. else if (i == 4)
  1021. {
  1022. if (videoRequest != null)
  1023. {
  1024. videoRequest.VideoCodec = val;
  1025. }
  1026. }
  1027. else if (i == 5)
  1028. {
  1029. request.AudioCodec = val;
  1030. }
  1031. else if (i == 6)
  1032. {
  1033. if (videoRequest != null)
  1034. {
  1035. videoRequest.AudioStreamIndex = int.Parse(val, UsCulture);
  1036. }
  1037. }
  1038. else if (i == 7)
  1039. {
  1040. if (videoRequest != null)
  1041. {
  1042. videoRequest.SubtitleStreamIndex = int.Parse(val, UsCulture);
  1043. }
  1044. }
  1045. else if (i == 8)
  1046. {
  1047. if (videoRequest != null)
  1048. {
  1049. videoRequest.VideoBitRate = int.Parse(val, UsCulture);
  1050. }
  1051. }
  1052. else if (i == 9)
  1053. {
  1054. request.AudioBitRate = int.Parse(val, UsCulture);
  1055. }
  1056. else if (i == 10)
  1057. {
  1058. request.MaxAudioChannels = int.Parse(val, UsCulture);
  1059. }
  1060. else if (i == 11)
  1061. {
  1062. if (videoRequest != null)
  1063. {
  1064. videoRequest.MaxWidth = int.Parse(val, UsCulture);
  1065. }
  1066. }
  1067. else if (i == 12)
  1068. {
  1069. if (videoRequest != null)
  1070. {
  1071. videoRequest.MaxHeight = int.Parse(val, UsCulture);
  1072. }
  1073. }
  1074. else if (i == 13)
  1075. {
  1076. if (videoRequest != null)
  1077. {
  1078. videoRequest.Framerate = int.Parse(val, UsCulture);
  1079. }
  1080. }
  1081. else if (i == 14)
  1082. {
  1083. if (videoRequest != null)
  1084. {
  1085. request.StartTimeTicks = long.Parse(val, UsCulture);
  1086. }
  1087. }
  1088. else if (i == 15)
  1089. {
  1090. if (videoRequest != null)
  1091. {
  1092. videoRequest.Profile = val;
  1093. }
  1094. }
  1095. else if (i == 16)
  1096. {
  1097. if (videoRequest != null)
  1098. {
  1099. videoRequest.Level = val;
  1100. }
  1101. }
  1102. }
  1103. }
  1104. /// <summary>
  1105. /// Gets the state.
  1106. /// </summary>
  1107. /// <param name="request">The request.</param>
  1108. /// <param name="cancellationToken">The cancellation token.</param>
  1109. /// <returns>StreamState.</returns>
  1110. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  1111. {
  1112. if (!string.IsNullOrWhiteSpace(request.Params))
  1113. {
  1114. ParseParams(request);
  1115. }
  1116. if (request.ThrowDebugError)
  1117. {
  1118. throw new InvalidOperationException("You asked for a debug error, you got one.");
  1119. }
  1120. var user = AuthorizationRequestFilterAttribute.GetCurrentUser(Request, UserManager);
  1121. var url = Request.PathInfo;
  1122. if (string.IsNullOrEmpty(request.AudioCodec))
  1123. {
  1124. request.AudioCodec = InferAudioCodec(url);
  1125. }
  1126. var state = new StreamState
  1127. {
  1128. Request = request,
  1129. RequestedUrl = url
  1130. };
  1131. var item = string.IsNullOrEmpty(request.MediaSourceId) ?
  1132. DtoService.GetItemByDtoId(request.Id) :
  1133. DtoService.GetItemByDtoId(request.MediaSourceId);
  1134. if (user != null && item.GetPlayAccess(user) != PlayAccess.Full)
  1135. {
  1136. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  1137. }
  1138. if (item is ILiveTvRecording)
  1139. {
  1140. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  1141. state.VideoType = VideoType.VideoFile;
  1142. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1143. state.PlayableStreamFileNames = new List<string>();
  1144. var path = recording.RecordingInfo.Path;
  1145. var mediaUrl = recording.RecordingInfo.Url;
  1146. if (string.IsNullOrWhiteSpace(path) && string.IsNullOrWhiteSpace(mediaUrl))
  1147. {
  1148. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  1149. state.LiveTvStreamId = streamInfo.Id;
  1150. path = streamInfo.Path;
  1151. mediaUrl = streamInfo.Url;
  1152. }
  1153. if (!string.IsNullOrEmpty(path) && File.Exists(path))
  1154. {
  1155. state.MediaPath = path;
  1156. state.IsRemote = false;
  1157. state.SendInputOverStandardInput = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  1158. }
  1159. else if (!string.IsNullOrEmpty(mediaUrl))
  1160. {
  1161. state.MediaPath = mediaUrl;
  1162. state.IsRemote = true;
  1163. }
  1164. //state.RunTimeTicks = recording.RunTimeTicks;
  1165. if (recording.RecordingInfo.Status == RecordingStatus.InProgress && !state.IsRemote)
  1166. {
  1167. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  1168. }
  1169. state.ReadInputAtNativeFramerate = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  1170. state.AudioSync = "1000";
  1171. state.DeInterlace = true;
  1172. state.InputVideoSync = "-1";
  1173. state.InputAudioSync = "1";
  1174. }
  1175. else if (item is LiveTvChannel)
  1176. {
  1177. var channel = LiveTvManager.GetInternalChannel(request.Id);
  1178. state.VideoType = VideoType.VideoFile;
  1179. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1180. state.PlayableStreamFileNames = new List<string>();
  1181. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  1182. state.LiveTvStreamId = streamInfo.Id;
  1183. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  1184. {
  1185. state.MediaPath = streamInfo.Path;
  1186. state.IsRemote = false;
  1187. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  1188. }
  1189. else if (!string.IsNullOrEmpty(streamInfo.Url))
  1190. {
  1191. state.MediaPath = streamInfo.Url;
  1192. state.IsRemote = true;
  1193. }
  1194. state.ReadInputAtNativeFramerate = true;
  1195. state.AudioSync = "1000";
  1196. state.DeInterlace = true;
  1197. state.InputVideoSync = "-1";
  1198. state.InputAudioSync = "1";
  1199. }
  1200. else
  1201. {
  1202. state.MediaPath = item.Path;
  1203. state.IsRemote = item.LocationType == LocationType.Remote;
  1204. var video = item as Video;
  1205. if (video != null)
  1206. {
  1207. state.IsInputVideo = true;
  1208. state.VideoType = video.VideoType;
  1209. state.IsoType = video.IsoType;
  1210. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  1211. ? new List<string>()
  1212. : video.PlayableStreamFileNames.ToList();
  1213. }
  1214. state.RunTimeTicks = item.RunTimeTicks;
  1215. }
  1216. var videoRequest = request as VideoStreamRequest;
  1217. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  1218. {
  1219. ItemId = item.Id
  1220. }).ToList();
  1221. if (videoRequest != null)
  1222. {
  1223. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  1224. {
  1225. videoRequest.VideoCodec = InferVideoCodec(url);
  1226. }
  1227. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  1228. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  1229. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  1230. if (state.VideoStream != null && state.VideoStream.IsInterlaced)
  1231. {
  1232. state.DeInterlace = true;
  1233. }
  1234. EnforceResolutionLimit(state, videoRequest);
  1235. }
  1236. else
  1237. {
  1238. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  1239. }
  1240. state.HasMediaStreams = mediaStreams.Count > 0;
  1241. state.SegmentLength = state.ReadInputAtNativeFramerate ? 5 : 10;
  1242. state.HlsListSize = state.ReadInputAtNativeFramerate ? 100 : 1440;
  1243. return state;
  1244. }
  1245. /// <summary>
  1246. /// Enforces the resolution limit.
  1247. /// </summary>
  1248. /// <param name="state">The state.</param>
  1249. /// <param name="videoRequest">The video request.</param>
  1250. private void EnforceResolutionLimit(StreamState state, VideoStreamRequest videoRequest)
  1251. {
  1252. // If enabled, allow whatever the client asks for
  1253. if (ServerConfigurationManager.Configuration.AllowVideoUpscaling)
  1254. {
  1255. return;
  1256. }
  1257. // Switch the incoming params to be ceilings rather than fixed values
  1258. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1259. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1260. videoRequest.Width = null;
  1261. videoRequest.Height = null;
  1262. }
  1263. protected string GetInputModifier(StreamState state)
  1264. {
  1265. var inputModifier = string.Empty;
  1266. var probeSize = GetProbeSizeArgument(state.MediaPath, state.IsInputVideo, state.VideoType, state.IsoType);
  1267. inputModifier += " " + probeSize;
  1268. inputModifier = inputModifier.Trim();
  1269. inputModifier += " " + GetUserAgentParam(state.MediaPath);
  1270. inputModifier = inputModifier.Trim();
  1271. inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
  1272. inputModifier = inputModifier.Trim();
  1273. if (state.VideoRequest != null)
  1274. {
  1275. inputModifier += " -fflags genpts";
  1276. }
  1277. if (!string.IsNullOrEmpty(state.InputFormat))
  1278. {
  1279. inputModifier += " -f " + state.InputFormat;
  1280. }
  1281. if (!string.IsNullOrEmpty(state.InputVideoCodec))
  1282. {
  1283. inputModifier += " -vcodec " + state.InputVideoCodec;
  1284. }
  1285. if (!string.IsNullOrEmpty(state.InputAudioCodec))
  1286. {
  1287. inputModifier += " -acodec " + state.InputAudioCodec;
  1288. }
  1289. if (!string.IsNullOrEmpty(state.InputAudioSync))
  1290. {
  1291. inputModifier += " -async " + state.InputAudioSync;
  1292. }
  1293. if (!string.IsNullOrEmpty(state.InputVideoSync))
  1294. {
  1295. inputModifier += " -vsync " + state.InputVideoSync;
  1296. }
  1297. if (state.ReadInputAtNativeFramerate)
  1298. {
  1299. inputModifier += " -re";
  1300. }
  1301. return inputModifier;
  1302. }
  1303. /// <summary>
  1304. /// Infers the audio codec based on the url
  1305. /// </summary>
  1306. /// <param name="url">The URL.</param>
  1307. /// <returns>System.Nullable{AudioCodecs}.</returns>
  1308. private string InferAudioCodec(string url)
  1309. {
  1310. var ext = Path.GetExtension(url);
  1311. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  1312. {
  1313. return "mp3";
  1314. }
  1315. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  1316. {
  1317. return "aac";
  1318. }
  1319. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  1320. {
  1321. return "wma";
  1322. }
  1323. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  1324. {
  1325. return "vorbis";
  1326. }
  1327. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  1328. {
  1329. return "vorbis";
  1330. }
  1331. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1332. {
  1333. return "vorbis";
  1334. }
  1335. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1336. {
  1337. return "vorbis";
  1338. }
  1339. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  1340. {
  1341. return "vorbis";
  1342. }
  1343. return null;
  1344. }
  1345. /// <summary>
  1346. /// Infers the video codec.
  1347. /// </summary>
  1348. /// <param name="url">The URL.</param>
  1349. /// <returns>System.Nullable{VideoCodecs}.</returns>
  1350. private string InferVideoCodec(string url)
  1351. {
  1352. var ext = Path.GetExtension(url);
  1353. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  1354. {
  1355. return "wmv";
  1356. }
  1357. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1358. {
  1359. return "vpx";
  1360. }
  1361. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1362. {
  1363. return "theora";
  1364. }
  1365. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  1366. {
  1367. return "h264";
  1368. }
  1369. return "copy";
  1370. }
  1371. }
  1372. }