BaseStreamingService.cs 92 KB

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