BaseStreamingService.cs 105 KB

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