BaseStreamingService.cs 82 KB

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