BaseStreamingService.cs 68 KB

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