BaseStreamingService.cs 105 KB

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