BaseStreamingService.cs 66 KB

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