BaseStreamingService.cs 67 KB

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