BaseStreamingService.cs 103 KB

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