BaseStreamingService.cs 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Devices;
  5. using MediaBrowser.Controller.Dlna;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.MediaEncoding;
  9. using MediaBrowser.Model.Configuration;
  10. using MediaBrowser.Model.Dlna;
  11. using MediaBrowser.Model.Drawing;
  12. using MediaBrowser.Model.Dto;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.Extensions;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.MediaInfo;
  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.Text;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. using MediaBrowser.Model.Serialization;
  27. namespace MediaBrowser.Api.Playback
  28. {
  29. /// <summary>
  30. /// Class BaseStreamingService
  31. /// </summary>
  32. public abstract class BaseStreamingService : BaseApiService
  33. {
  34. /// <summary>
  35. /// Gets or sets the application paths.
  36. /// </summary>
  37. /// <value>The application paths.</value>
  38. protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
  39. /// <summary>
  40. /// Gets or sets the user manager.
  41. /// </summary>
  42. /// <value>The user manager.</value>
  43. protected IUserManager UserManager { get; private set; }
  44. /// <summary>
  45. /// Gets or sets the library manager.
  46. /// </summary>
  47. /// <value>The library manager.</value>
  48. protected ILibraryManager LibraryManager { get; private set; }
  49. /// <summary>
  50. /// Gets or sets the iso manager.
  51. /// </summary>
  52. /// <value>The iso manager.</value>
  53. protected IIsoManager IsoManager { get; private set; }
  54. /// <summary>
  55. /// Gets or sets the media encoder.
  56. /// </summary>
  57. /// <value>The media encoder.</value>
  58. protected IMediaEncoder MediaEncoder { get; private set; }
  59. protected IFileSystem FileSystem { get; private set; }
  60. protected IDlnaManager DlnaManager { get; private set; }
  61. protected IDeviceManager DeviceManager { get; private set; }
  62. protected ISubtitleEncoder SubtitleEncoder { get; private set; }
  63. protected IMediaSourceManager MediaSourceManager { get; private set; }
  64. protected IZipClient ZipClient { get; private set; }
  65. protected IJsonSerializer JsonSerializer { get; private set; }
  66. /// <summary>
  67. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  68. /// </summary>
  69. protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer)
  70. {
  71. JsonSerializer = jsonSerializer;
  72. ZipClient = zipClient;
  73. MediaSourceManager = mediaSourceManager;
  74. DeviceManager = deviceManager;
  75. SubtitleEncoder = subtitleEncoder;
  76. DlnaManager = dlnaManager;
  77. FileSystem = fileSystem;
  78. ServerConfigurationManager = serverConfig;
  79. UserManager = userManager;
  80. LibraryManager = libraryManager;
  81. IsoManager = isoManager;
  82. MediaEncoder = mediaEncoder;
  83. }
  84. /// <summary>
  85. /// Gets the command line arguments.
  86. /// </summary>
  87. /// <param name="outputPath">The output path.</param>
  88. /// <param name="state">The state.</param>
  89. /// <param name="isEncoding">if set to <c>true</c> [is encoding].</param>
  90. /// <returns>System.String.</returns>
  91. protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding);
  92. /// <summary>
  93. /// Gets the type of the transcoding job.
  94. /// </summary>
  95. /// <value>The type of the transcoding job.</value>
  96. protected abstract TranscodingJobType TranscodingJobType { get; }
  97. /// <summary>
  98. /// Gets the output file extension.
  99. /// </summary>
  100. /// <param name="state">The state.</param>
  101. /// <returns>System.String.</returns>
  102. protected virtual string GetOutputFileExtension(StreamState state)
  103. {
  104. return Path.GetExtension(state.RequestedUrl);
  105. }
  106. /// <summary>
  107. /// Gets the output file path.
  108. /// </summary>
  109. /// <param name="state">The state.</param>
  110. /// <returns>System.String.</returns>
  111. private string GetOutputFilePath(StreamState state)
  112. {
  113. var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
  114. var outputFileExtension = GetOutputFileExtension(state);
  115. var data = GetCommandLineArguments("dummy\\dummy", state, false);
  116. data += "-" + (state.Request.DeviceId ?? string.Empty);
  117. data += "-" + (state.Request.PlaySessionId ?? string.Empty);
  118. data += "-" + (state.Request.ClientTime ?? string.Empty);
  119. var dataHash = data.GetMD5().ToString("N");
  120. if (EnableOutputInSubFolder)
  121. {
  122. return Path.Combine(folder, dataHash, dataHash + (outputFileExtension ?? string.Empty).ToLower());
  123. }
  124. return Path.Combine(folder, dataHash + (outputFileExtension ?? string.Empty).ToLower());
  125. }
  126. protected virtual bool EnableOutputInSubFolder
  127. {
  128. get { return false; }
  129. }
  130. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  131. /// <summary>
  132. /// Gets the fast seek command line parameter.
  133. /// </summary>
  134. /// <param name="request">The request.</param>
  135. /// <returns>System.String.</returns>
  136. /// <value>The fast seek command line parameter.</value>
  137. protected string GetFastSeekCommandLineParameter(StreamRequest request)
  138. {
  139. var time = request.StartTimeTicks ?? 0;
  140. if (time > 0)
  141. {
  142. return string.Format("-ss {0}", MediaEncoder.GetTimeParameter(time));
  143. }
  144. return string.Empty;
  145. }
  146. /// <summary>
  147. /// Gets the map args.
  148. /// </summary>
  149. /// <param name="state">The state.</param>
  150. /// <returns>System.String.</returns>
  151. protected virtual string GetMapArgs(StreamState state)
  152. {
  153. // If we don't have known media info
  154. // If input is video, use -sn to drop subtitles
  155. // Otherwise just return empty
  156. if (state.VideoStream == null && state.AudioStream == null)
  157. {
  158. return state.IsInputVideo ? "-sn" : string.Empty;
  159. }
  160. // We have media info, but we don't know the stream indexes
  161. if (state.VideoStream != null && state.VideoStream.Index == -1)
  162. {
  163. return "-sn";
  164. }
  165. // We have media info, but we don't know the stream indexes
  166. if (state.AudioStream != null && state.AudioStream.Index == -1)
  167. {
  168. return state.IsInputVideo ? "-sn" : string.Empty;
  169. }
  170. var args = string.Empty;
  171. if (state.VideoStream != null)
  172. {
  173. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  174. }
  175. else
  176. {
  177. args += "-map -0:v";
  178. }
  179. if (state.AudioStream != null)
  180. {
  181. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  182. }
  183. else
  184. {
  185. args += " -map -0:a";
  186. }
  187. if (state.SubtitleStream == null)
  188. {
  189. args += " -map -0:s";
  190. }
  191. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  192. {
  193. args += " -map 1:0 -sn";
  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 (type == MediaStreamType.Video)
  217. {
  218. streams = streams.Where(i => !string.Equals(i.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase)).ToList();
  219. }
  220. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  221. {
  222. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  223. streams.FirstOrDefault();
  224. }
  225. // Just return the first one
  226. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  227. }
  228. protected EncodingQuality GetQualitySetting()
  229. {
  230. var quality = ApiEntryPoint.Instance.GetEncodingOptions().EncodingQuality;
  231. if (quality == EncodingQuality.Auto)
  232. {
  233. var cpuCount = Environment.ProcessorCount;
  234. if (cpuCount >= 4)
  235. {
  236. //return EncodingQuality.HighQuality;
  237. }
  238. return EncodingQuality.HighSpeed;
  239. }
  240. return quality;
  241. }
  242. /// <summary>
  243. /// Gets the number of threads.
  244. /// </summary>
  245. /// <returns>System.Int32.</returns>
  246. protected int GetNumberOfThreads(StreamState state, bool isWebm)
  247. {
  248. if (isWebm)
  249. {
  250. // Recommended per docs
  251. return Math.Max(Environment.ProcessorCount - 1, 2);
  252. }
  253. return 0;
  254. }
  255. protected string H264Encoder
  256. {
  257. get
  258. {
  259. var lib = ApiEntryPoint.Instance.GetEncodingOptions().H264Encoder;
  260. if (!string.IsNullOrWhiteSpace(lib))
  261. {
  262. return lib;
  263. }
  264. return "libx264";
  265. }
  266. }
  267. /// <summary>
  268. /// Gets the video bitrate to specify on the command line
  269. /// </summary>
  270. /// <param name="state">The state.</param>
  271. /// <param name="videoCodec">The video codec.</param>
  272. /// <param name="isHls">if set to <c>true</c> [is HLS].</param>
  273. /// <returns>System.String.</returns>
  274. protected string GetVideoQualityParam(StreamState state, string videoCodec, bool isHls)
  275. {
  276. var param = string.Empty;
  277. var isVc1 = state.VideoStream != null &&
  278. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  279. var qualitySetting = GetQualitySetting();
  280. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  281. {
  282. param = "-preset superfast";
  283. switch (qualitySetting)
  284. {
  285. case EncodingQuality.HighSpeed:
  286. param += " -crf 23";
  287. break;
  288. case EncodingQuality.HighQuality:
  289. param += " -crf 20";
  290. break;
  291. case EncodingQuality.MaxQuality:
  292. param += " -crf 18";
  293. break;
  294. }
  295. }
  296. else if (string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
  297. {
  298. param = "-preset fast";
  299. switch (qualitySetting)
  300. {
  301. case EncodingQuality.HighSpeed:
  302. param += " -crf 28";
  303. break;
  304. case EncodingQuality.HighQuality:
  305. param += " -crf 25";
  306. break;
  307. case EncodingQuality.MaxQuality:
  308. param += " -crf 21";
  309. break;
  310. }
  311. }
  312. // h264 (h264_qsv)
  313. else if (string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  314. {
  315. switch (qualitySetting)
  316. {
  317. case EncodingQuality.HighSpeed:
  318. param = "-preset 7";
  319. break;
  320. case EncodingQuality.HighQuality:
  321. param = "-preset 4";
  322. break;
  323. case EncodingQuality.MaxQuality:
  324. param = "-preset 1";
  325. break;
  326. }
  327. }
  328. // h264 (libnvenc)
  329. else if (string.Equals(videoCodec, "libnvenc", StringComparison.OrdinalIgnoreCase))
  330. {
  331. switch (qualitySetting)
  332. {
  333. case EncodingQuality.HighSpeed:
  334. param = "-preset high-performance";
  335. break;
  336. case EncodingQuality.HighQuality:
  337. param = "";
  338. break;
  339. case EncodingQuality.MaxQuality:
  340. param = "-preset high-quality";
  341. break;
  342. }
  343. }
  344. // webm
  345. else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  346. {
  347. // Values 0-3, 0 being highest quality but slower
  348. var profileScore = 0;
  349. string crf;
  350. var qmin = "0";
  351. var qmax = "50";
  352. switch (qualitySetting)
  353. {
  354. case EncodingQuality.HighSpeed:
  355. crf = "10";
  356. break;
  357. case EncodingQuality.HighQuality:
  358. crf = "6";
  359. break;
  360. case EncodingQuality.MaxQuality:
  361. crf = "4";
  362. break;
  363. default:
  364. throw new ArgumentException("Unrecognized quality setting");
  365. }
  366. if (isVc1)
  367. {
  368. profileScore++;
  369. }
  370. // Max of 2
  371. profileScore = Math.Min(profileScore, 2);
  372. // http://www.webmproject.org/docs/encoder-parameters/
  373. param = string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  374. profileScore.ToString(UsCulture),
  375. crf,
  376. qmin,
  377. qmax);
  378. }
  379. else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  380. {
  381. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  382. }
  383. // asf/wmv
  384. else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
  385. {
  386. param = "-qmin 2";
  387. }
  388. else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  389. {
  390. param = "-mbd 2";
  391. }
  392. param += GetVideoBitrateParam(state, videoCodec, isHls);
  393. var framerate = GetFramerateParam(state);
  394. if (framerate.HasValue)
  395. {
  396. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  397. }
  398. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  399. {
  400. param += " -vsync " + state.OutputVideoSync;
  401. }
  402. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  403. {
  404. param += " -profile:v " + state.VideoRequest.Profile;
  405. }
  406. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  407. {
  408. // h264_qsv and libnvenc expect levels to be expressed as a decimal. libx264 supports decimal and non-decimal format
  409. if (String.Equals(H264Encoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) || String.Equals(H264Encoder, "libnvenc", StringComparison.OrdinalIgnoreCase))
  410. {
  411. switch (state.VideoRequest.Level)
  412. {
  413. case "30":
  414. param += " -level 3";
  415. break;
  416. case "31":
  417. param += " -level 3.1";
  418. break;
  419. case "32":
  420. param += " -level 3.2";
  421. break;
  422. case "40":
  423. param += " -level 4";
  424. break;
  425. case "41":
  426. param += " -level 4.1";
  427. break;
  428. case "42":
  429. param += " -level 4.2";
  430. break;
  431. case "50":
  432. param += " -level 5";
  433. break;
  434. case "51":
  435. param += " -level 5.1";
  436. break;
  437. case "52":
  438. param += " -level 5.2";
  439. break;
  440. default:
  441. param += " -level " + state.VideoRequest.Level;
  442. break;
  443. }
  444. }
  445. else
  446. {
  447. param += " -level " + state.VideoRequest.Level;
  448. }
  449. }
  450. return "-pix_fmt yuv420p " + param;
  451. }
  452. protected string GetAudioFilterParam(StreamState state, bool isHls)
  453. {
  454. var volParam = string.Empty;
  455. var audioSampleRate = string.Empty;
  456. var channels = state.OutputAudioChannels;
  457. // Boost volume to 200% when downsampling from 6ch to 2ch
  458. if (channels.HasValue && channels.Value <= 2)
  459. {
  460. if (state.AudioStream != null && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  461. {
  462. volParam = ",volume=" + ApiEntryPoint.Instance.GetEncodingOptions().DownMixAudioBoost.ToString(UsCulture);
  463. }
  464. }
  465. if (state.OutputAudioSampleRate.HasValue)
  466. {
  467. audioSampleRate = state.OutputAudioSampleRate.Value + ":";
  468. }
  469. var adelay = isHls ? "adelay=1," : string.Empty;
  470. var pts = string.Empty;
  471. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream)
  472. {
  473. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  474. pts = string.Format(",asetpts=PTS-{0}/TB", Math.Round(seconds).ToString(UsCulture));
  475. }
  476. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  477. adelay,
  478. audioSampleRate,
  479. volParam,
  480. pts,
  481. state.OutputAudioSync);
  482. }
  483. /// <summary>
  484. /// If we're going to put a fixed size on the command line, this will calculate it
  485. /// </summary>
  486. /// <param name="state">The state.</param>
  487. /// <param name="outputVideoCodec">The output video codec.</param>
  488. /// <param name="allowTimeStampCopy">if set to <c>true</c> [allow time stamp copy].</param>
  489. /// <returns>System.String.</returns>
  490. protected string GetOutputSizeParam(StreamState state,
  491. string outputVideoCodec,
  492. bool allowTimeStampCopy = true)
  493. {
  494. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  495. var request = state.VideoRequest;
  496. var filters = new List<string>();
  497. if (state.DeInterlace)
  498. {
  499. filters.Add("yadif=0:-1:0");
  500. }
  501. // If fixed dimensions were supplied
  502. if (request.Width.HasValue && request.Height.HasValue)
  503. {
  504. var widthParam = request.Width.Value.ToString(UsCulture);
  505. var heightParam = request.Height.Value.ToString(UsCulture);
  506. filters.Add(string.Format("scale=trunc({0}/2)*2:trunc({1}/2)*2", widthParam, heightParam));
  507. }
  508. // 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
  509. else if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  510. {
  511. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  512. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  513. filters.Add(string.Format("scale=trunc(min(max(iw\\,ih*dar)\\,min({0}\\,{1}*dar))/2)*2:trunc(min(max(iw/dar\\,ih)\\,min({0}/dar\\,{1}))/2)*2", maxWidthParam, maxHeightParam));
  514. }
  515. // If a fixed width was requested
  516. else if (request.Width.HasValue)
  517. {
  518. var widthParam = request.Width.Value.ToString(UsCulture);
  519. filters.Add(string.Format("scale={0}:trunc(ow/a/2)*2", widthParam));
  520. }
  521. // If a fixed height was requested
  522. else if (request.Height.HasValue)
  523. {
  524. var heightParam = request.Height.Value.ToString(UsCulture);
  525. filters.Add(string.Format("scale=trunc(oh*a*2)/2:{0}", heightParam));
  526. }
  527. // If a max width was requested
  528. else if (request.MaxWidth.HasValue)
  529. {
  530. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  531. filters.Add(string.Format("scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam));
  532. }
  533. // If a max height was requested
  534. else if (request.MaxHeight.HasValue)
  535. {
  536. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  537. filters.Add(string.Format("scale=trunc(oh*a*2)/2:min(ih\\,{0})", maxHeightParam));
  538. }
  539. if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  540. {
  541. filters[filters.Count - 1] += ":flags=fast_bilinear";
  542. }
  543. var output = string.Empty;
  544. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream)
  545. {
  546. var subParam = GetTextSubtitleParam(state);
  547. filters.Add(subParam);
  548. if (allowTimeStampCopy)
  549. {
  550. output += " -copyts";
  551. }
  552. }
  553. if (filters.Count > 0)
  554. {
  555. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  556. }
  557. return output;
  558. }
  559. /// <summary>
  560. /// Gets the text subtitle param.
  561. /// </summary>
  562. /// <param name="state">The state.</param>
  563. /// <returns>System.String.</returns>
  564. protected string GetTextSubtitleParam(StreamState state)
  565. {
  566. var seconds = Math.Round(TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds);
  567. if (state.SubtitleStream.IsExternal)
  568. {
  569. var subtitlePath = state.SubtitleStream.Path;
  570. var charsetParam = string.Empty;
  571. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  572. {
  573. var charenc = SubtitleEncoder.GetSubtitleFileCharacterSet(subtitlePath, state.MediaSource.Protocol, CancellationToken.None).Result;
  574. if (!string.IsNullOrEmpty(charenc))
  575. {
  576. charsetParam = ":charenc=" + charenc;
  577. }
  578. }
  579. // TODO: Perhaps also use original_size=1920x800 ??
  580. return string.Format("subtitles=filename='{0}'{1},setpts=PTS -{2}/TB",
  581. subtitlePath.Replace("'", "\\'").Replace('\\', '/').Replace(":/", "\\:/"),
  582. charsetParam,
  583. seconds.ToString(UsCulture));
  584. }
  585. var mediaPath = state.MediaPath ?? string.Empty;
  586. return string.Format("subtitles='{0}:si={1}',setpts=PTS -{2}/TB",
  587. mediaPath.Replace("'", "\\'").Replace('\\', '/').Replace(":/", "\\:/"),
  588. state.InternalSubtitleStreamOffset.ToString(UsCulture),
  589. seconds.ToString(UsCulture));
  590. }
  591. /// <summary>
  592. /// Gets the internal graphical subtitle param.
  593. /// </summary>
  594. /// <param name="state">The state.</param>
  595. /// <param name="outputVideoCodec">The output video codec.</param>
  596. /// <returns>System.String.</returns>
  597. protected string GetGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  598. {
  599. var outputSizeParam = string.Empty;
  600. var request = state.VideoRequest;
  601. // Add resolution params, if specified
  602. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  603. {
  604. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec).TrimEnd('"');
  605. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  606. }
  607. var videoSizeParam = string.Empty;
  608. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  609. {
  610. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  611. }
  612. var mapPrefix = state.SubtitleStream.IsExternal ?
  613. 1 :
  614. 0;
  615. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  616. ? 0
  617. : state.SubtitleStream.Index;
  618. return string.Format(" -filter_complex \"[{0}:{1}]format=yuva444p{4},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{2}] [sub] overlay{3}\"",
  619. mapPrefix.ToString(UsCulture),
  620. subtitleStreamIndex.ToString(UsCulture),
  621. state.VideoStream.Index.ToString(UsCulture),
  622. outputSizeParam,
  623. videoSizeParam);
  624. }
  625. /// <summary>
  626. /// Gets the probe size argument.
  627. /// </summary>
  628. /// <param name="state">The state.</param>
  629. /// <returns>System.String.</returns>
  630. private string GetProbeSizeArgument(StreamState state)
  631. {
  632. if (state.PlayableStreamFileNames.Count > 0)
  633. {
  634. return MediaEncoder.GetProbeSizeArgument(state.PlayableStreamFileNames.ToArray(), state.InputProtocol);
  635. }
  636. return MediaEncoder.GetProbeSizeArgument(new[] { state.MediaPath }, state.InputProtocol);
  637. }
  638. /// <summary>
  639. /// Gets the number of audio channels to specify on the command line
  640. /// </summary>
  641. /// <param name="request">The request.</param>
  642. /// <param name="audioStream">The audio stream.</param>
  643. /// <param name="outputAudioCodec">The output audio codec.</param>
  644. /// <returns>System.Nullable{System.Int32}.</returns>
  645. private int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream, string outputAudioCodec)
  646. {
  647. var inputChannels = audioStream == null
  648. ? null
  649. : audioStream.Channels;
  650. var codec = outputAudioCodec ?? string.Empty;
  651. if (codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  652. {
  653. // wmav2 currently only supports two channel output
  654. return Math.Min(2, inputChannels ?? 2);
  655. }
  656. if (request.MaxAudioChannels.HasValue)
  657. {
  658. if (inputChannels.HasValue)
  659. {
  660. return Math.Min(request.MaxAudioChannels.Value, inputChannels.Value);
  661. }
  662. var channelLimit = codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1
  663. ? 2
  664. : 5;
  665. // If we don't have any media info then limit it to 5 to prevent encoding errors due to asking for too many channels
  666. return Math.Min(request.MaxAudioChannels.Value, channelLimit);
  667. }
  668. return request.AudioChannels;
  669. }
  670. /// <summary>
  671. /// Determines whether the specified stream is H264.
  672. /// </summary>
  673. /// <param name="stream">The stream.</param>
  674. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  675. protected bool IsH264(MediaStream stream)
  676. {
  677. var codec = stream.Codec ?? string.Empty;
  678. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  679. codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  680. }
  681. /// <summary>
  682. /// Gets the audio encoder.
  683. /// </summary>
  684. /// <param name="request">The request.</param>
  685. /// <returns>System.String.</returns>
  686. protected string GetAudioEncoder(StreamRequest request)
  687. {
  688. var codec = request.AudioCodec;
  689. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  690. {
  691. return "aac -strict experimental";
  692. }
  693. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  694. {
  695. return "libmp3lame";
  696. }
  697. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  698. {
  699. return "libvorbis";
  700. }
  701. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  702. {
  703. return "wmav2";
  704. }
  705. return codec.ToLower();
  706. }
  707. /// <summary>
  708. /// Gets the name of the output video codec
  709. /// </summary>
  710. /// <param name="request">The request.</param>
  711. /// <returns>System.String.</returns>
  712. protected string GetVideoEncoder(VideoStreamRequest request)
  713. {
  714. var codec = request.VideoCodec;
  715. if (!string.IsNullOrEmpty(codec))
  716. {
  717. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  718. {
  719. return H264Encoder;
  720. }
  721. if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  722. {
  723. return "libvpx";
  724. }
  725. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  726. {
  727. return "wmv2";
  728. }
  729. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  730. {
  731. return "libtheora";
  732. }
  733. return codec.ToLower();
  734. }
  735. return "copy";
  736. }
  737. /// <summary>
  738. /// Gets the input argument.
  739. /// </summary>
  740. /// <param name="state">The state.</param>
  741. /// <returns>System.String.</returns>
  742. protected string GetInputArgument(StreamState state)
  743. {
  744. var arg = "-i " + GetInputPathArgument(state);
  745. if (state.SubtitleStream != null)
  746. {
  747. if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  748. {
  749. arg += " -i \"" + state.SubtitleStream.Path + "\"";
  750. }
  751. }
  752. return arg;
  753. }
  754. private string GetInputPathArgument(StreamState state)
  755. {
  756. var protocol = state.InputProtocol;
  757. var mediaPath = state.MediaPath ?? string.Empty;
  758. var inputPath = new[] { mediaPath };
  759. if (state.IsInputVideo)
  760. {
  761. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  762. {
  763. inputPath = MediaEncoderHelpers.GetInputArgument(mediaPath, state.InputProtocol, state.IsoMount, state.PlayableStreamFileNames);
  764. }
  765. }
  766. return MediaEncoder.GetInputArgument(inputPath, protocol);
  767. }
  768. private async Task AcquireResources(StreamState state, CancellationTokenSource cancellationTokenSource)
  769. {
  770. if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  771. {
  772. state.IsoMount = await IsoManager.Mount(state.MediaPath, cancellationTokenSource.Token).ConfigureAwait(false);
  773. }
  774. if (state.MediaSource.RequiresOpening)
  775. {
  776. var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
  777. {
  778. OpenToken = state.MediaSource.OpenToken
  779. }, false, cancellationTokenSource.Token).ConfigureAwait(false);
  780. AttachMediaSourceInfo(state, liveStreamResponse.MediaSource, state.VideoRequest, state.RequestedUrl);
  781. if (state.VideoRequest != null)
  782. {
  783. TryStreamCopy(state, state.VideoRequest);
  784. }
  785. }
  786. if (state.MediaSource.BufferMs.HasValue)
  787. {
  788. await Task.Delay(state.MediaSource.BufferMs.Value, cancellationTokenSource.Token).ConfigureAwait(false);
  789. }
  790. }
  791. /// <summary>
  792. /// Starts the FFMPEG.
  793. /// </summary>
  794. /// <param name="state">The state.</param>
  795. /// <param name="outputPath">The output path.</param>
  796. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  797. /// <param name="workingDirectory">The working directory.</param>
  798. /// <returns>Task.</returns>
  799. protected async Task<TranscodingJob> StartFfMpeg(StreamState state,
  800. string outputPath,
  801. CancellationTokenSource cancellationTokenSource,
  802. string workingDirectory = null)
  803. {
  804. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  805. await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);
  806. var transcodingId = Guid.NewGuid().ToString("N");
  807. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  808. if (ApiEntryPoint.Instance.GetEncodingOptions().EnableDebugLogging)
  809. {
  810. commandLineArgs = "-loglevel debug " + commandLineArgs;
  811. }
  812. var process = new Process
  813. {
  814. StartInfo = new ProcessStartInfo
  815. {
  816. CreateNoWindow = true,
  817. UseShellExecute = false,
  818. // Must consume both stdout and stderr or deadlocks may occur
  819. RedirectStandardOutput = true,
  820. RedirectStandardError = true,
  821. RedirectStandardInput = true,
  822. FileName = MediaEncoder.EncoderPath,
  823. Arguments = commandLineArgs,
  824. WindowStyle = ProcessWindowStyle.Hidden,
  825. ErrorDialog = false
  826. },
  827. EnableRaisingEvents = true
  828. };
  829. if (!string.IsNullOrWhiteSpace(workingDirectory))
  830. {
  831. process.StartInfo.WorkingDirectory = workingDirectory;
  832. }
  833. var transcodingJob = ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath,
  834. state.Request.PlaySessionId,
  835. state.MediaSource.LiveStreamId,
  836. transcodingId,
  837. TranscodingJobType,
  838. process,
  839. state.Request.DeviceId,
  840. state,
  841. cancellationTokenSource);
  842. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  843. Logger.Info(commandLineLogMessage);
  844. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "transcode-" + Guid.NewGuid() + ".txt");
  845. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  846. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  847. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  848. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(Request.AbsoluteUri + Environment.NewLine + Environment.NewLine + JsonSerializer.SerializeToString(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  849. await state.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false);
  850. process.Exited += (sender, args) => OnFfMpegProcessExited(process, transcodingJob, state);
  851. try
  852. {
  853. process.Start();
  854. }
  855. catch (Exception ex)
  856. {
  857. Logger.ErrorException("Error starting ffmpeg", ex);
  858. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);
  859. throw;
  860. }
  861. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  862. process.BeginOutputReadLine();
  863. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  864. StartStreamingLog(transcodingJob, state, process.StandardError.BaseStream, state.LogFileStream);
  865. // Wait for the file to exist before proceeeding
  866. while (!File.Exists(state.WaitForPath ?? outputPath) && !transcodingJob.HasExited)
  867. {
  868. await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false);
  869. }
  870. if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive)
  871. {
  872. await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);
  873. if (state.ReadInputAtNativeFramerate)
  874. {
  875. await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
  876. }
  877. }
  878. StartThrottler(state, transcodingJob);
  879. return transcodingJob;
  880. }
  881. private void StartThrottler(StreamState state, TranscodingJob transcodingJob)
  882. {
  883. if (EnableThrottling(state) && state.InputProtocol == MediaProtocol.File &&
  884. state.RunTimeTicks.HasValue &&
  885. state.VideoType == VideoType.VideoFile &&
  886. !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  887. {
  888. if (state.RunTimeTicks.Value >= TimeSpan.FromMinutes(5).Ticks && state.IsInputVideo)
  889. {
  890. transcodingJob.TranscodingThrottler = state.TranscodingThrottler = new TranscodingThrottler(transcodingJob, Logger, ServerConfigurationManager);
  891. state.TranscodingThrottler.Start();
  892. }
  893. }
  894. }
  895. protected virtual bool EnableThrottling(StreamState state)
  896. {
  897. return true;
  898. }
  899. private async void StartStreamingLog(TranscodingJob transcodingJob, StreamState state, Stream source, Stream target)
  900. {
  901. try
  902. {
  903. using (var reader = new StreamReader(source))
  904. {
  905. while (!reader.EndOfStream)
  906. {
  907. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  908. ParseLogLine(line, transcodingJob, state);
  909. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  910. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  911. }
  912. }
  913. }
  914. catch (ObjectDisposedException)
  915. {
  916. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  917. }
  918. catch (Exception ex)
  919. {
  920. Logger.ErrorException("Error reading ffmpeg log", ex);
  921. }
  922. }
  923. private void ParseLogLine(string line, TranscodingJob transcodingJob, StreamState state)
  924. {
  925. float? framerate = null;
  926. double? percent = null;
  927. TimeSpan? transcodingPosition = null;
  928. long? bytesTranscoded = null;
  929. var parts = line.Split(' ');
  930. var totalMs = state.RunTimeTicks.HasValue
  931. ? TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalMilliseconds
  932. : 0;
  933. var startMs = state.Request.StartTimeTicks.HasValue
  934. ? TimeSpan.FromTicks(state.Request.StartTimeTicks.Value).TotalMilliseconds
  935. : 0;
  936. for (var i = 0; i < parts.Length; i++)
  937. {
  938. var part = parts[i];
  939. if (string.Equals(part, "fps=", StringComparison.OrdinalIgnoreCase) &&
  940. (i + 1 < parts.Length))
  941. {
  942. var rate = parts[i + 1];
  943. float val;
  944. if (float.TryParse(rate, NumberStyles.Any, UsCulture, out val))
  945. {
  946. framerate = val;
  947. }
  948. }
  949. else if (state.RunTimeTicks.HasValue &&
  950. part.StartsWith("time=", StringComparison.OrdinalIgnoreCase))
  951. {
  952. var time = part.Split(new[] { '=' }, 2).Last();
  953. TimeSpan val;
  954. if (TimeSpan.TryParse(time, UsCulture, out val))
  955. {
  956. var currentMs = startMs + val.TotalMilliseconds;
  957. var percentVal = currentMs / totalMs;
  958. percent = 100 * percentVal;
  959. transcodingPosition = val;
  960. }
  961. }
  962. else if (part.StartsWith("size=", StringComparison.OrdinalIgnoreCase))
  963. {
  964. var size = part.Split(new[] { '=' }, 2).Last();
  965. int? scale = null;
  966. if (size.IndexOf("kb", StringComparison.OrdinalIgnoreCase) != -1)
  967. {
  968. scale = 1024;
  969. size = size.Replace("kb", string.Empty, StringComparison.OrdinalIgnoreCase);
  970. }
  971. if (scale.HasValue)
  972. {
  973. long val;
  974. if (long.TryParse(size, NumberStyles.Any, UsCulture, out val))
  975. {
  976. bytesTranscoded = val * scale.Value;
  977. }
  978. }
  979. }
  980. }
  981. if (framerate.HasValue || percent.HasValue)
  982. {
  983. ApiEntryPoint.Instance.ReportTranscodingProgress(transcodingJob, state, transcodingPosition, framerate, percent, bytesTranscoded);
  984. }
  985. }
  986. private int? GetVideoBitrateParamValue(VideoStreamRequest request, MediaStream videoStream)
  987. {
  988. var bitrate = request.VideoBitRate;
  989. if (videoStream != null)
  990. {
  991. var isUpscaling = request.Height.HasValue && videoStream.Height.HasValue &&
  992. request.Height.Value > videoStream.Height.Value;
  993. if (request.Width.HasValue && videoStream.Width.HasValue &&
  994. request.Width.Value > videoStream.Width.Value)
  995. {
  996. isUpscaling = true;
  997. }
  998. // Don't allow bitrate increases unless upscaling
  999. if (!isUpscaling)
  1000. {
  1001. if (bitrate.HasValue && videoStream.BitRate.HasValue)
  1002. {
  1003. bitrate = Math.Min(bitrate.Value, videoStream.BitRate.Value);
  1004. }
  1005. }
  1006. }
  1007. return bitrate;
  1008. }
  1009. protected string GetVideoBitrateParam(StreamState state, string videoCodec, bool isHls)
  1010. {
  1011. var bitrate = state.OutputVideoBitrate;
  1012. if (bitrate.HasValue)
  1013. {
  1014. var hasFixedResolution = state.VideoRequest.HasFixedResolution;
  1015. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  1016. {
  1017. if (hasFixedResolution)
  1018. {
  1019. return string.Format(" -minrate:v ({0}*.90) -maxrate:v ({0}*1.10) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  1020. }
  1021. // With vpx when crf is used, b:v becomes a max rate
  1022. // https://trac.ffmpeg.org/wiki/vpxEncodingGuide. But higher bitrate source files -b:v causes judder so limite the bitrate but dont allow it to "saturate" the bitrate. So dont contrain it down just up.
  1023. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(UsCulture));
  1024. }
  1025. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  1026. {
  1027. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  1028. }
  1029. // h264_qsv
  1030. if (string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) || string.Equals(videoCodec, "libnvenc", StringComparison.OrdinalIgnoreCase))
  1031. {
  1032. if (hasFixedResolution)
  1033. {
  1034. if (isHls)
  1035. {
  1036. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  1037. }
  1038. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  1039. }
  1040. return string.Format(" -b:v {0} -maxrate ({0}*1.2) -bufsize ({0}*2)", bitrate.Value.ToString(UsCulture));
  1041. }
  1042. // H264
  1043. if (hasFixedResolution)
  1044. {
  1045. if (isHls)
  1046. {
  1047. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  1048. }
  1049. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  1050. }
  1051. return string.Format(" -maxrate {0} -bufsize {1}",
  1052. bitrate.Value.ToString(UsCulture),
  1053. (bitrate.Value * 2).ToString(UsCulture));
  1054. }
  1055. return string.Empty;
  1056. }
  1057. private int? GetAudioBitrateParam(StreamRequest request, MediaStream audioStream)
  1058. {
  1059. if (request.AudioBitRate.HasValue)
  1060. {
  1061. // Make sure we don't request a bitrate higher than the source
  1062. var currentBitrate = audioStream == null ? request.AudioBitRate.Value : audioStream.BitRate ?? request.AudioBitRate.Value;
  1063. return request.AudioBitRate.Value;
  1064. //return Math.Min(currentBitrate, request.AudioBitRate.Value);
  1065. }
  1066. return null;
  1067. }
  1068. /// <summary>
  1069. /// Gets the user agent param.
  1070. /// </summary>
  1071. /// <param name="state">The state.</param>
  1072. /// <returns>System.String.</returns>
  1073. private string GetUserAgentParam(StreamState state)
  1074. {
  1075. string useragent = null;
  1076. state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  1077. if (!string.IsNullOrWhiteSpace(useragent))
  1078. {
  1079. return "-user-agent \"" + useragent + "\"";
  1080. }
  1081. return string.Empty;
  1082. }
  1083. /// <summary>
  1084. /// Processes the exited.
  1085. /// </summary>
  1086. /// <param name="process">The process.</param>
  1087. /// <param name="job">The job.</param>
  1088. /// <param name="state">The state.</param>
  1089. private void OnFfMpegProcessExited(Process process, TranscodingJob job, StreamState state)
  1090. {
  1091. if (job != null)
  1092. {
  1093. job.HasExited = true;
  1094. }
  1095. Logger.Debug("Disposing stream resources");
  1096. state.Dispose();
  1097. try
  1098. {
  1099. Logger.Info("FFMpeg exited with code {0}", process.ExitCode);
  1100. }
  1101. catch
  1102. {
  1103. Logger.Error("FFMpeg exited with an error.");
  1104. }
  1105. // This causes on exited to be called twice:
  1106. //try
  1107. //{
  1108. // // Dispose the process
  1109. // process.Dispose();
  1110. //}
  1111. //catch (Exception ex)
  1112. //{
  1113. // Logger.ErrorException("Error disposing ffmpeg.", ex);
  1114. //}
  1115. }
  1116. protected double? GetFramerateParam(StreamState state)
  1117. {
  1118. if (state.VideoRequest != null)
  1119. {
  1120. if (state.VideoRequest.Framerate.HasValue)
  1121. {
  1122. return state.VideoRequest.Framerate.Value;
  1123. }
  1124. var maxrate = state.VideoRequest.MaxFramerate;
  1125. if (maxrate.HasValue && state.VideoStream != null)
  1126. {
  1127. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  1128. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  1129. {
  1130. return maxrate;
  1131. }
  1132. }
  1133. }
  1134. return null;
  1135. }
  1136. /// <summary>
  1137. /// Parses the parameters.
  1138. /// </summary>
  1139. /// <param name="request">The request.</param>
  1140. private void ParseParams(StreamRequest request)
  1141. {
  1142. var vals = request.Params.Split(';');
  1143. var videoRequest = request as VideoStreamRequest;
  1144. for (var i = 0; i < vals.Length; i++)
  1145. {
  1146. var val = vals[i];
  1147. if (string.IsNullOrWhiteSpace(val))
  1148. {
  1149. continue;
  1150. }
  1151. if (i == 0)
  1152. {
  1153. request.DeviceProfileId = val;
  1154. }
  1155. else if (i == 1)
  1156. {
  1157. request.DeviceId = val;
  1158. }
  1159. else if (i == 2)
  1160. {
  1161. request.MediaSourceId = val;
  1162. }
  1163. else if (i == 3)
  1164. {
  1165. request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  1166. }
  1167. else if (i == 4)
  1168. {
  1169. if (videoRequest != null)
  1170. {
  1171. videoRequest.VideoCodec = val;
  1172. }
  1173. }
  1174. else if (i == 5)
  1175. {
  1176. request.AudioCodec = val;
  1177. }
  1178. else if (i == 6)
  1179. {
  1180. if (videoRequest != null)
  1181. {
  1182. videoRequest.AudioStreamIndex = int.Parse(val, UsCulture);
  1183. }
  1184. }
  1185. else if (i == 7)
  1186. {
  1187. if (videoRequest != null)
  1188. {
  1189. videoRequest.SubtitleStreamIndex = int.Parse(val, UsCulture);
  1190. }
  1191. }
  1192. else if (i == 8)
  1193. {
  1194. if (videoRequest != null)
  1195. {
  1196. videoRequest.VideoBitRate = int.Parse(val, UsCulture);
  1197. }
  1198. }
  1199. else if (i == 9)
  1200. {
  1201. request.AudioBitRate = int.Parse(val, UsCulture);
  1202. }
  1203. else if (i == 10)
  1204. {
  1205. request.MaxAudioChannels = int.Parse(val, UsCulture);
  1206. }
  1207. else if (i == 11)
  1208. {
  1209. if (videoRequest != null)
  1210. {
  1211. videoRequest.MaxFramerate = float.Parse(val, UsCulture);
  1212. }
  1213. }
  1214. else if (i == 12)
  1215. {
  1216. if (videoRequest != null)
  1217. {
  1218. videoRequest.MaxWidth = int.Parse(val, UsCulture);
  1219. }
  1220. }
  1221. else if (i == 13)
  1222. {
  1223. if (videoRequest != null)
  1224. {
  1225. videoRequest.MaxHeight = int.Parse(val, UsCulture);
  1226. }
  1227. }
  1228. else if (i == 14)
  1229. {
  1230. request.StartTimeTicks = long.Parse(val, UsCulture);
  1231. }
  1232. else if (i == 15)
  1233. {
  1234. if (videoRequest != null)
  1235. {
  1236. videoRequest.Level = val;
  1237. }
  1238. }
  1239. else if (i == 16)
  1240. {
  1241. request.ClientTime = val;
  1242. }
  1243. else if (i == 17)
  1244. {
  1245. if (videoRequest != null)
  1246. {
  1247. videoRequest.MaxRefFrames = int.Parse(val, UsCulture);
  1248. }
  1249. }
  1250. else if (i == 18)
  1251. {
  1252. if (videoRequest != null)
  1253. {
  1254. videoRequest.MaxVideoBitDepth = int.Parse(val, UsCulture);
  1255. }
  1256. }
  1257. else if (i == 19)
  1258. {
  1259. if (videoRequest != null)
  1260. {
  1261. videoRequest.Profile = val;
  1262. }
  1263. }
  1264. else if (i == 20)
  1265. {
  1266. if (videoRequest != null)
  1267. {
  1268. videoRequest.Cabac = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  1269. }
  1270. }
  1271. else if (i == 21)
  1272. {
  1273. request.PlaySessionId = val;
  1274. }
  1275. else if (i == 22)
  1276. {
  1277. // api_key
  1278. }
  1279. else if (i == 23)
  1280. {
  1281. request.LiveStreamId = val;
  1282. }
  1283. else if (i == 24)
  1284. {
  1285. // Duplicating ItemId because of MediaMonkey
  1286. }
  1287. }
  1288. }
  1289. /// <summary>
  1290. /// Parses the dlna headers.
  1291. /// </summary>
  1292. /// <param name="request">The request.</param>
  1293. private void ParseDlnaHeaders(StreamRequest request)
  1294. {
  1295. if (!request.StartTimeTicks.HasValue)
  1296. {
  1297. var timeSeek = GetHeader("TimeSeekRange.dlna.org");
  1298. request.StartTimeTicks = ParseTimeSeekHeader(timeSeek);
  1299. }
  1300. }
  1301. /// <summary>
  1302. /// Parses the time seek header.
  1303. /// </summary>
  1304. private long? ParseTimeSeekHeader(string value)
  1305. {
  1306. if (string.IsNullOrWhiteSpace(value))
  1307. {
  1308. return null;
  1309. }
  1310. if (value.IndexOf("npt=", StringComparison.OrdinalIgnoreCase) != 0)
  1311. {
  1312. throw new ArgumentException("Invalid timeseek header");
  1313. }
  1314. value = value.Substring(4).Split(new[] { '-' }, 2)[0];
  1315. if (value.IndexOf(':') == -1)
  1316. {
  1317. // Parses npt times in the format of '417.33'
  1318. double seconds;
  1319. if (double.TryParse(value, NumberStyles.Any, UsCulture, out seconds))
  1320. {
  1321. return TimeSpan.FromSeconds(seconds).Ticks;
  1322. }
  1323. throw new ArgumentException("Invalid timeseek header");
  1324. }
  1325. // Parses npt times in the format of '10:19:25.7'
  1326. var tokens = value.Split(new[] { ':' }, 3);
  1327. double secondsSum = 0;
  1328. var timeFactor = 3600;
  1329. foreach (var time in tokens)
  1330. {
  1331. double digit;
  1332. if (double.TryParse(time, NumberStyles.Any, UsCulture, out digit))
  1333. {
  1334. secondsSum += (digit * timeFactor);
  1335. }
  1336. else
  1337. {
  1338. throw new ArgumentException("Invalid timeseek header");
  1339. }
  1340. timeFactor /= 60;
  1341. }
  1342. return TimeSpan.FromSeconds(secondsSum).Ticks;
  1343. }
  1344. /// <summary>
  1345. /// Gets the state.
  1346. /// </summary>
  1347. /// <param name="request">The request.</param>
  1348. /// <param name="cancellationToken">The cancellation token.</param>
  1349. /// <returns>StreamState.</returns>
  1350. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  1351. {
  1352. ParseDlnaHeaders(request);
  1353. if (!string.IsNullOrWhiteSpace(request.Params))
  1354. {
  1355. ParseParams(request);
  1356. }
  1357. var url = Request.PathInfo;
  1358. if (string.IsNullOrEmpty(request.AudioCodec))
  1359. {
  1360. request.AudioCodec = InferAudioCodec(url);
  1361. }
  1362. var state = new StreamState(MediaSourceManager, Logger)
  1363. {
  1364. Request = request,
  1365. RequestedUrl = url
  1366. };
  1367. if (!string.IsNullOrWhiteSpace(request.AudioCodec))
  1368. {
  1369. state.SupportedAudioCodecs = request.AudioCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  1370. state.Request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault();
  1371. }
  1372. var item = LibraryManager.GetItemById(request.Id);
  1373. state.IsInputVideo = string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1374. var archivable = item as IArchivable;
  1375. state.IsInputArchive = archivable != null && archivable.IsArchive;
  1376. MediaSourceInfo mediaSource;
  1377. if (string.IsNullOrWhiteSpace(request.LiveStreamId))
  1378. {
  1379. var mediaSources = (await MediaSourceManager.GetPlayackMediaSources(request.Id, null, false, new[] { MediaType.Audio, MediaType.Video }, cancellationToken).ConfigureAwait(false)).ToList();
  1380. mediaSource = string.IsNullOrEmpty(request.MediaSourceId)
  1381. ? mediaSources.First()
  1382. : mediaSources.FirstOrDefault(i => string.Equals(i.Id, request.MediaSourceId));
  1383. if (mediaSource == null && string.Equals(request.Id, request.MediaSourceId, StringComparison.OrdinalIgnoreCase))
  1384. {
  1385. mediaSource = mediaSources.First();
  1386. }
  1387. }
  1388. else
  1389. {
  1390. mediaSource = await MediaSourceManager.GetLiveStream(request.LiveStreamId, cancellationToken).ConfigureAwait(false);
  1391. }
  1392. var videoRequest = request as VideoStreamRequest;
  1393. AttachMediaSourceInfo(state, mediaSource, videoRequest, url);
  1394. var container = Path.GetExtension(state.RequestedUrl);
  1395. if (string.IsNullOrEmpty(container))
  1396. {
  1397. container = request.Static ?
  1398. state.InputContainer :
  1399. (Path.GetExtension(GetOutputFilePath(state)) ?? string.Empty).TrimStart('.');
  1400. }
  1401. state.OutputContainer = (container ?? string.Empty).TrimStart('.');
  1402. state.OutputAudioBitrate = GetAudioBitrateParam(state.Request, state.AudioStream);
  1403. state.OutputAudioSampleRate = request.AudioSampleRate;
  1404. state.OutputAudioCodec = state.Request.AudioCodec;
  1405. state.OutputAudioChannels = GetNumAudioChannelsParam(state.Request, state.AudioStream, state.OutputAudioCodec);
  1406. if (videoRequest != null)
  1407. {
  1408. state.OutputVideoCodec = state.VideoRequest.VideoCodec;
  1409. state.OutputVideoBitrate = GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream);
  1410. if (state.OutputVideoBitrate.HasValue)
  1411. {
  1412. var resolution = ResolutionNormalizer.Normalize(state.OutputVideoBitrate.Value,
  1413. state.OutputVideoCodec,
  1414. videoRequest.MaxWidth,
  1415. videoRequest.MaxHeight);
  1416. videoRequest.MaxWidth = resolution.MaxWidth;
  1417. videoRequest.MaxHeight = resolution.MaxHeight;
  1418. }
  1419. }
  1420. ApplyDeviceProfileSettings(state);
  1421. if (videoRequest != null)
  1422. {
  1423. TryStreamCopy(state, videoRequest);
  1424. }
  1425. state.OutputFilePath = GetOutputFilePath(state);
  1426. return state;
  1427. }
  1428. private void TryStreamCopy(StreamState state, VideoStreamRequest videoRequest)
  1429. {
  1430. if (!EnableStreamCopy)
  1431. {
  1432. return;
  1433. }
  1434. if (state.VideoStream != null && CanStreamCopyVideo(videoRequest, state.VideoStream))
  1435. {
  1436. state.OutputVideoCodec = "copy";
  1437. }
  1438. if (state.AudioStream != null && CanStreamCopyAudio(videoRequest, state.AudioStream, state.SupportedAudioCodecs))
  1439. {
  1440. state.OutputAudioCodec = "copy";
  1441. }
  1442. }
  1443. protected virtual bool EnableStreamCopy
  1444. {
  1445. get
  1446. {
  1447. return true;
  1448. }
  1449. }
  1450. private void AttachMediaSourceInfo(StreamState state,
  1451. MediaSourceInfo mediaSource,
  1452. VideoStreamRequest videoRequest,
  1453. string requestedUrl)
  1454. {
  1455. state.MediaPath = mediaSource.Path;
  1456. state.InputProtocol = mediaSource.Protocol;
  1457. state.InputContainer = mediaSource.Container;
  1458. state.InputFileSize = mediaSource.Size;
  1459. state.InputBitrate = mediaSource.Bitrate;
  1460. state.ReadInputAtNativeFramerate = mediaSource.ReadAtNativeFramerate;
  1461. state.RunTimeTicks = mediaSource.RunTimeTicks;
  1462. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  1463. if (mediaSource.VideoType.HasValue)
  1464. {
  1465. state.VideoType = mediaSource.VideoType.Value;
  1466. }
  1467. state.IsoType = mediaSource.IsoType;
  1468. state.PlayableStreamFileNames = mediaSource.PlayableStreamFileNames.ToList();
  1469. if (mediaSource.Timestamp.HasValue)
  1470. {
  1471. state.InputTimestamp = mediaSource.Timestamp.Value;
  1472. }
  1473. state.InputProtocol = mediaSource.Protocol;
  1474. state.MediaPath = mediaSource.Path;
  1475. state.RunTimeTicks = mediaSource.RunTimeTicks;
  1476. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  1477. state.InputBitrate = mediaSource.Bitrate;
  1478. state.InputFileSize = mediaSource.Size;
  1479. state.ReadInputAtNativeFramerate = mediaSource.ReadAtNativeFramerate;
  1480. if (state.ReadInputAtNativeFramerate ||
  1481. mediaSource.Protocol == MediaProtocol.File && string.Equals(mediaSource.Container, "wtv", StringComparison.OrdinalIgnoreCase))
  1482. {
  1483. state.OutputAudioSync = "1000";
  1484. state.InputVideoSync = "-1";
  1485. state.InputAudioSync = "1";
  1486. }
  1487. var mediaStreams = mediaSource.MediaStreams;
  1488. if (videoRequest != null)
  1489. {
  1490. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  1491. {
  1492. videoRequest.VideoCodec = InferVideoCodec(requestedUrl);
  1493. }
  1494. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  1495. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  1496. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  1497. if (state.SubtitleStream != null && !state.SubtitleStream.IsExternal)
  1498. {
  1499. state.InternalSubtitleStreamOffset = mediaStreams.Where(i => i.Type == MediaStreamType.Subtitle && !i.IsExternal).ToList().IndexOf(state.SubtitleStream);
  1500. }
  1501. if (state.VideoStream != null && state.VideoStream.IsInterlaced)
  1502. {
  1503. state.DeInterlace = true;
  1504. }
  1505. EnforceResolutionLimit(state, videoRequest);
  1506. }
  1507. else
  1508. {
  1509. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  1510. }
  1511. state.MediaSource = mediaSource;
  1512. }
  1513. private bool CanStreamCopyVideo(VideoStreamRequest request, MediaStream videoStream)
  1514. {
  1515. if (videoStream.IsInterlaced)
  1516. {
  1517. return false;
  1518. }
  1519. // Can't stream copy if we're burning in subtitles
  1520. if (request.SubtitleStreamIndex.HasValue)
  1521. {
  1522. if (request.SubtitleMethod == SubtitleDeliveryMethod.Encode)
  1523. {
  1524. return false;
  1525. }
  1526. }
  1527. // Source and target codecs must match
  1528. if (!string.Equals(request.VideoCodec, videoStream.Codec, StringComparison.OrdinalIgnoreCase))
  1529. {
  1530. return false;
  1531. }
  1532. // If client is requesting a specific video profile, it must match the source
  1533. if (!string.IsNullOrEmpty(request.Profile))
  1534. {
  1535. if (string.IsNullOrEmpty(videoStream.Profile))
  1536. {
  1537. return false;
  1538. }
  1539. if (!string.Equals(request.Profile, videoStream.Profile, StringComparison.OrdinalIgnoreCase))
  1540. {
  1541. var currentScore = GetVideoProfileScore(videoStream.Profile);
  1542. var requestedScore = GetVideoProfileScore(request.Profile);
  1543. if (currentScore == -1 || currentScore > requestedScore)
  1544. {
  1545. return false;
  1546. }
  1547. }
  1548. }
  1549. // Video width must fall within requested value
  1550. if (request.MaxWidth.HasValue)
  1551. {
  1552. if (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value)
  1553. {
  1554. return false;
  1555. }
  1556. }
  1557. // Video height must fall within requested value
  1558. if (request.MaxHeight.HasValue)
  1559. {
  1560. if (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value)
  1561. {
  1562. return false;
  1563. }
  1564. }
  1565. // Video framerate must fall within requested value
  1566. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  1567. if (requestedFramerate.HasValue)
  1568. {
  1569. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  1570. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  1571. {
  1572. return false;
  1573. }
  1574. }
  1575. // Video bitrate must fall within requested value
  1576. if (request.VideoBitRate.HasValue)
  1577. {
  1578. if (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value)
  1579. {
  1580. return false;
  1581. }
  1582. }
  1583. if (request.MaxVideoBitDepth.HasValue)
  1584. {
  1585. if (videoStream.BitDepth.HasValue && videoStream.BitDepth.Value > request.MaxVideoBitDepth.Value)
  1586. {
  1587. return false;
  1588. }
  1589. }
  1590. if (request.MaxRefFrames.HasValue)
  1591. {
  1592. if (videoStream.RefFrames.HasValue && videoStream.RefFrames.Value > request.MaxRefFrames.Value)
  1593. {
  1594. return false;
  1595. }
  1596. }
  1597. // If a specific level was requested, the source must match or be less than
  1598. if (!string.IsNullOrEmpty(request.Level))
  1599. {
  1600. double requestLevel;
  1601. if (double.TryParse(request.Level, NumberStyles.Any, UsCulture, out requestLevel))
  1602. {
  1603. if (!videoStream.Level.HasValue)
  1604. {
  1605. return false;
  1606. }
  1607. if (videoStream.Level.Value > requestLevel)
  1608. {
  1609. return false;
  1610. }
  1611. }
  1612. }
  1613. if (request.Cabac.HasValue && request.Cabac.Value)
  1614. {
  1615. if (videoStream.IsCabac.HasValue && !videoStream.IsCabac.Value)
  1616. {
  1617. return false;
  1618. }
  1619. }
  1620. return request.EnableAutoStreamCopy;
  1621. }
  1622. private int GetVideoProfileScore(string profile)
  1623. {
  1624. var list = new List<string>
  1625. {
  1626. "Constrained Baseline",
  1627. "Baseline",
  1628. "Extended",
  1629. "Main",
  1630. "High",
  1631. "Progressive High",
  1632. "Constrained High"
  1633. };
  1634. return Array.FindIndex(list.ToArray(), t => string.Equals(t, profile, StringComparison.OrdinalIgnoreCase));
  1635. }
  1636. private bool CanStreamCopyAudio(VideoStreamRequest request, MediaStream audioStream, List<string> supportedAudioCodecs)
  1637. {
  1638. // Source and target codecs must match
  1639. if (string.IsNullOrEmpty(audioStream.Codec) || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
  1640. {
  1641. return false;
  1642. }
  1643. // Video bitrate must fall within requested value
  1644. if (request.AudioBitRate.HasValue)
  1645. {
  1646. if (!audioStream.BitRate.HasValue || audioStream.BitRate.Value <= 0)
  1647. {
  1648. return false;
  1649. }
  1650. if (audioStream.BitRate.Value > request.AudioBitRate.Value)
  1651. {
  1652. return false;
  1653. }
  1654. }
  1655. // Channels must fall within requested value
  1656. var channels = request.AudioChannels ?? request.MaxAudioChannels;
  1657. if (channels.HasValue)
  1658. {
  1659. if (!audioStream.Channels.HasValue || audioStream.Channels.Value <= 0)
  1660. {
  1661. return false;
  1662. }
  1663. if (audioStream.Channels.Value > channels.Value)
  1664. {
  1665. return false;
  1666. }
  1667. }
  1668. // Sample rate must fall within requested value
  1669. if (request.AudioSampleRate.HasValue)
  1670. {
  1671. if (!audioStream.SampleRate.HasValue || audioStream.SampleRate.Value <= 0)
  1672. {
  1673. return false;
  1674. }
  1675. if (audioStream.SampleRate.Value > request.AudioSampleRate.Value)
  1676. {
  1677. return false;
  1678. }
  1679. }
  1680. return request.EnableAutoStreamCopy;
  1681. }
  1682. private void ApplyDeviceProfileSettings(StreamState state)
  1683. {
  1684. var headers = new Dictionary<string, string>();
  1685. foreach (var key in Request.Headers.AllKeys)
  1686. {
  1687. headers[key] = Request.Headers[key];
  1688. }
  1689. if (!string.IsNullOrWhiteSpace(state.Request.DeviceProfileId))
  1690. {
  1691. state.DeviceProfile = DlnaManager.GetProfile(state.Request.DeviceProfileId);
  1692. }
  1693. else
  1694. {
  1695. if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
  1696. {
  1697. var caps = DeviceManager.GetCapabilities(state.Request.DeviceId);
  1698. if (caps != null)
  1699. {
  1700. state.DeviceProfile = caps.DeviceProfile;
  1701. }
  1702. else
  1703. {
  1704. state.DeviceProfile = DlnaManager.GetProfile(headers);
  1705. }
  1706. }
  1707. }
  1708. var profile = state.DeviceProfile;
  1709. if (profile == null)
  1710. {
  1711. // Don't use settings from the default profile.
  1712. // Only use a specific profile if it was requested.
  1713. return;
  1714. }
  1715. var audioCodec = state.ActualOutputAudioCodec;
  1716. var videoCodec = state.ActualOutputVideoCodec;
  1717. var mediaProfile = state.VideoRequest == null ?
  1718. profile.GetAudioMediaProfile(state.OutputContainer, audioCodec, state.OutputAudioChannels, state.OutputAudioBitrate) :
  1719. profile.GetVideoMediaProfile(state.OutputContainer,
  1720. audioCodec,
  1721. videoCodec,
  1722. state.OutputWidth,
  1723. state.OutputHeight,
  1724. state.TargetVideoBitDepth,
  1725. state.OutputVideoBitrate,
  1726. state.TargetVideoProfile,
  1727. state.TargetVideoLevel,
  1728. state.TargetFramerate,
  1729. state.TargetPacketLength,
  1730. state.TargetTimestamp,
  1731. state.IsTargetAnamorphic,
  1732. state.IsTargetCabac,
  1733. state.TargetRefFrames,
  1734. state.TargetVideoStreamCount,
  1735. state.TargetAudioStreamCount);
  1736. if (mediaProfile != null)
  1737. {
  1738. state.MimeType = mediaProfile.MimeType;
  1739. }
  1740. if (!state.Request.Static)
  1741. {
  1742. var transcodingProfile = state.VideoRequest == null ?
  1743. profile.GetAudioTranscodingProfile(state.OutputContainer, audioCodec) :
  1744. profile.GetVideoTranscodingProfile(state.OutputContainer, audioCodec, videoCodec);
  1745. if (transcodingProfile != null)
  1746. {
  1747. state.EstimateContentLength = transcodingProfile.EstimateContentLength;
  1748. state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
  1749. state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  1750. }
  1751. }
  1752. }
  1753. /// <summary>
  1754. /// Adds the dlna headers.
  1755. /// </summary>
  1756. /// <param name="state">The state.</param>
  1757. /// <param name="responseHeaders">The response headers.</param>
  1758. /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
  1759. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1760. protected void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
  1761. {
  1762. var profile = state.DeviceProfile;
  1763. var transferMode = GetHeader("transferMode.dlna.org");
  1764. responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
  1765. responseHeaders["realTimeInfo.dlna.org"] = "DLNA.ORG_TLAG=*";
  1766. if (string.Equals(GetHeader("getMediaInfo.sec"), "1", StringComparison.OrdinalIgnoreCase))
  1767. {
  1768. if (state.RunTimeTicks.HasValue)
  1769. {
  1770. var ms = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalMilliseconds;
  1771. responseHeaders["MediaInfo.sec"] = string.Format("SEC_Duration={0};", Convert.ToInt32(ms).ToString(CultureInfo.InvariantCulture));
  1772. }
  1773. }
  1774. if (state.RunTimeTicks.HasValue && !isStaticallyStreamed && profile != null)
  1775. {
  1776. AddTimeSeekResponseHeaders(state, responseHeaders);
  1777. }
  1778. if (profile == null)
  1779. {
  1780. profile = DlnaManager.GetDefaultProfile();
  1781. }
  1782. var audioCodec = state.ActualOutputAudioCodec;
  1783. if (state.VideoRequest == null)
  1784. {
  1785. responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
  1786. .BuildAudioHeader(
  1787. state.OutputContainer,
  1788. audioCodec,
  1789. state.OutputAudioBitrate,
  1790. state.OutputAudioSampleRate,
  1791. state.OutputAudioChannels,
  1792. isStaticallyStreamed,
  1793. state.RunTimeTicks,
  1794. state.TranscodeSeekInfo
  1795. );
  1796. }
  1797. else
  1798. {
  1799. var videoCodec = state.ActualOutputVideoCodec;
  1800. responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
  1801. .BuildVideoHeader(
  1802. state.OutputContainer,
  1803. videoCodec,
  1804. audioCodec,
  1805. state.OutputWidth,
  1806. state.OutputHeight,
  1807. state.TargetVideoBitDepth,
  1808. state.OutputVideoBitrate,
  1809. state.TargetTimestamp,
  1810. isStaticallyStreamed,
  1811. state.RunTimeTicks,
  1812. state.TargetVideoProfile,
  1813. state.TargetVideoLevel,
  1814. state.TargetFramerate,
  1815. state.TargetPacketLength,
  1816. state.TranscodeSeekInfo,
  1817. state.IsTargetAnamorphic,
  1818. state.IsTargetCabac,
  1819. state.TargetRefFrames,
  1820. state.TargetVideoStreamCount,
  1821. state.TargetAudioStreamCount
  1822. ).FirstOrDefault() ?? string.Empty;
  1823. }
  1824. foreach (var item in responseHeaders)
  1825. {
  1826. Request.Response.AddHeader(item.Key, item.Value);
  1827. }
  1828. }
  1829. private void AddTimeSeekResponseHeaders(StreamState state, IDictionary<string, string> responseHeaders)
  1830. {
  1831. var runtimeSeconds = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds.ToString(UsCulture);
  1832. var startSeconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds.ToString(UsCulture);
  1833. responseHeaders["TimeSeekRange.dlna.org"] = string.Format("npt={0}-{1}/{1}", startSeconds, runtimeSeconds);
  1834. responseHeaders["X-AvailableSeekRange"] = string.Format("1 npt={0}-{1}", startSeconds, runtimeSeconds);
  1835. }
  1836. /// <summary>
  1837. /// Enforces the resolution limit.
  1838. /// </summary>
  1839. /// <param name="state">The state.</param>
  1840. /// <param name="videoRequest">The video request.</param>
  1841. private void EnforceResolutionLimit(StreamState state, VideoStreamRequest videoRequest)
  1842. {
  1843. // Switch the incoming params to be ceilings rather than fixed values
  1844. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1845. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1846. videoRequest.Width = null;
  1847. videoRequest.Height = null;
  1848. }
  1849. protected string GetInputModifier(StreamState state, bool genPts = true)
  1850. {
  1851. var inputModifier = string.Empty;
  1852. var probeSize = GetProbeSizeArgument(state);
  1853. inputModifier += " " + probeSize;
  1854. inputModifier = inputModifier.Trim();
  1855. var userAgentParam = GetUserAgentParam(state);
  1856. if (!string.IsNullOrWhiteSpace(userAgentParam))
  1857. {
  1858. inputModifier += " " + userAgentParam;
  1859. }
  1860. inputModifier = inputModifier.Trim();
  1861. inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
  1862. inputModifier = inputModifier.Trim();
  1863. if (state.VideoRequest != null && genPts)
  1864. {
  1865. inputModifier += " -fflags +genpts";
  1866. }
  1867. if (!string.IsNullOrEmpty(state.InputAudioSync))
  1868. {
  1869. inputModifier += " -async " + state.InputAudioSync;
  1870. }
  1871. if (!string.IsNullOrEmpty(state.InputVideoSync))
  1872. {
  1873. inputModifier += " -vsync " + state.InputVideoSync;
  1874. }
  1875. if (state.ReadInputAtNativeFramerate)
  1876. {
  1877. inputModifier += " -re";
  1878. }
  1879. return inputModifier;
  1880. }
  1881. /// <summary>
  1882. /// Infers the audio codec based on the url
  1883. /// </summary>
  1884. /// <param name="url">The URL.</param>
  1885. /// <returns>System.Nullable{AudioCodecs}.</returns>
  1886. private string InferAudioCodec(string url)
  1887. {
  1888. var ext = Path.GetExtension(url);
  1889. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  1890. {
  1891. return "mp3";
  1892. }
  1893. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  1894. {
  1895. return "aac";
  1896. }
  1897. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  1898. {
  1899. return "wma";
  1900. }
  1901. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  1902. {
  1903. return "vorbis";
  1904. }
  1905. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  1906. {
  1907. return "vorbis";
  1908. }
  1909. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1910. {
  1911. return "vorbis";
  1912. }
  1913. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1914. {
  1915. return "vorbis";
  1916. }
  1917. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  1918. {
  1919. return "vorbis";
  1920. }
  1921. return "copy";
  1922. }
  1923. /// <summary>
  1924. /// Infers the video codec.
  1925. /// </summary>
  1926. /// <param name="url">The URL.</param>
  1927. /// <returns>System.Nullable{VideoCodecs}.</returns>
  1928. private string InferVideoCodec(string url)
  1929. {
  1930. var ext = Path.GetExtension(url);
  1931. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  1932. {
  1933. return "wmv";
  1934. }
  1935. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1936. {
  1937. return "vpx";
  1938. }
  1939. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1940. {
  1941. return "theora";
  1942. }
  1943. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  1944. {
  1945. return "h264";
  1946. }
  1947. return "copy";
  1948. }
  1949. }
  1950. }