BaseStreamingService.cs 87 KB

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