BaseStreamingService.cs 91 KB

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