2
0

BaseStreamingService.cs 78 KB

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