VideoHandler.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. using MediaBrowser.Common.Drawing;
  2. using MediaBrowser.Common.Net.Handlers;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Model.DTO;
  5. using MediaBrowser.Model.Entities;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.ComponentModel.Composition;
  9. using System.Drawing;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Net;
  13. namespace MediaBrowser.Api.HttpHandlers
  14. {
  15. /// <summary>
  16. /// Supported output formats: mkv,m4v,mp4,asf,wmv,mov,webm,ogv,3gp,avi,ts,flv
  17. /// </summary>
  18. [Export(typeof(BaseHandler))]
  19. class VideoHandler : BaseMediaHandler<Video, VideoOutputFormats>
  20. {
  21. public override bool HandlesRequest(HttpListenerRequest request)
  22. {
  23. return ApiService.IsApiUrlMatch("video", request);
  24. }
  25. /// <summary>
  26. /// We can output these files directly, but we can't encode them
  27. /// </summary>
  28. protected override IEnumerable<VideoOutputFormats> UnsupportedOutputEncodingFormats
  29. {
  30. get
  31. {
  32. // mp4, 3gp, mov - muxer does not support non-seekable output
  33. // avi, mov, mkv, m4v - can't stream these when encoding. the player will try to download them completely before starting playback.
  34. // wmv - can't seem to figure out the output format name
  35. return new VideoOutputFormats[] { VideoOutputFormats.Mp4, VideoOutputFormats.ThreeGp, VideoOutputFormats.M4V, VideoOutputFormats.Mkv, VideoOutputFormats.Avi, VideoOutputFormats.Mov, VideoOutputFormats.Wmv };
  36. }
  37. }
  38. /// <summary>
  39. /// Determines whether or not we can just output the original file directly
  40. /// </summary>
  41. protected override bool RequiresConversion()
  42. {
  43. string currentFormat = Path.GetExtension(LibraryItem.Path).Replace(".", string.Empty);
  44. // For now we won't allow these to pass through.
  45. // Later we'll add some intelligence to allow it when possible
  46. if (currentFormat.Equals("mp4", StringComparison.OrdinalIgnoreCase) || currentFormat.Equals("mkv", StringComparison.OrdinalIgnoreCase) || currentFormat.Equals("m4v", StringComparison.OrdinalIgnoreCase))
  47. {
  48. return true;
  49. }
  50. if (base.RequiresConversion())
  51. {
  52. return true;
  53. }
  54. // See if the video requires conversion
  55. if (RequiresVideoConversion())
  56. {
  57. return true;
  58. }
  59. // See if the audio requires conversion
  60. AudioStream audioStream = (LibraryItem.AudioStreams ?? new List<AudioStream>()).FirstOrDefault();
  61. if (audioStream != null)
  62. {
  63. if (RequiresAudioConversion(audioStream))
  64. {
  65. return true;
  66. }
  67. }
  68. // Yay
  69. return false;
  70. }
  71. /// <summary>
  72. /// Translates the output file extension to the format param that follows "-f" on the ffmpeg command line
  73. /// </summary>
  74. private string GetFfMpegOutputFormat(VideoOutputFormats outputFormat)
  75. {
  76. if (outputFormat == VideoOutputFormats.Mkv)
  77. {
  78. return "matroska";
  79. }
  80. if (outputFormat == VideoOutputFormats.Ts)
  81. {
  82. return "mpegts";
  83. }
  84. if (outputFormat == VideoOutputFormats.Ogv)
  85. {
  86. return "ogg";
  87. }
  88. return outputFormat.ToString().ToLower();
  89. }
  90. /// <summary>
  91. /// Creates arguments to pass to ffmpeg
  92. /// </summary>
  93. protected override string GetCommandLineArguments()
  94. {
  95. VideoOutputFormats outputFormat = GetConversionOutputFormat();
  96. return string.Format("-i \"{0}\" -threads 0 {1} {2} -f {3} -",
  97. LibraryItem.Path,
  98. GetVideoArguments(outputFormat),
  99. GetAudioArguments(outputFormat),
  100. GetFfMpegOutputFormat(outputFormat)
  101. );
  102. }
  103. /// <summary>
  104. /// Gets video arguments to pass to ffmpeg
  105. /// </summary>
  106. private string GetVideoArguments(VideoOutputFormats outputFormat)
  107. {
  108. // Get the output codec name
  109. string codec = GetVideoCodec(outputFormat);
  110. string args = "-vcodec " + codec;
  111. // If we're encoding video, add additional params
  112. if (!codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  113. {
  114. // Add resolution params, if specified
  115. if (Width.HasValue || Height.HasValue || MaxHeight.HasValue || MaxWidth.HasValue)
  116. {
  117. Size size = DrawingUtils.Resize(LibraryItem.Width, LibraryItem.Height, Width, Height, MaxWidth, MaxHeight);
  118. args += string.Format(" -s {0}x{1}", size.Width, size.Height);
  119. }
  120. }
  121. return args;
  122. }
  123. /// <summary>
  124. /// Gets audio arguments to pass to ffmpeg
  125. /// </summary>
  126. private string GetAudioArguments(VideoOutputFormats outputFormat)
  127. {
  128. AudioStream audioStream = (LibraryItem.AudioStreams ?? new List<AudioStream>()).FirstOrDefault();
  129. // If the video doesn't have an audio stream, return empty
  130. if (audioStream == null)
  131. {
  132. return string.Empty;
  133. }
  134. // Get the output codec name
  135. string codec = GetAudioCodec(audioStream, outputFormat);
  136. string args = "-acodec " + codec;
  137. // If we're encoding audio, add additional params
  138. if (!codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  139. {
  140. // Add the number of audio channels
  141. int? channels = GetNumAudioChannelsParam(codec, audioStream.Channels);
  142. if (channels.HasValue)
  143. {
  144. args += " -ac " + channels.Value;
  145. }
  146. // Add the audio sample rate
  147. int? sampleRate = GetSampleRateParam(audioStream.SampleRate);
  148. if (sampleRate.HasValue)
  149. {
  150. args += " -ar " + sampleRate.Value;
  151. }
  152. }
  153. return args;
  154. }
  155. /// <summary>
  156. /// Gets the name of the output video codec
  157. /// </summary>
  158. private string GetVideoCodec(VideoOutputFormats outputFormat)
  159. {
  160. // Some output containers require specific codecs
  161. if (outputFormat == VideoOutputFormats.Webm)
  162. {
  163. // Per webm specification, it must be vpx
  164. return "libvpx";
  165. }
  166. if (outputFormat == VideoOutputFormats.Asf)
  167. {
  168. return "wmv2";
  169. }
  170. if (outputFormat == VideoOutputFormats.Wmv)
  171. {
  172. return "wmv2";
  173. }
  174. if (outputFormat == VideoOutputFormats.Ogv)
  175. {
  176. return "libtheora";
  177. }
  178. // Skip encoding when possible
  179. if (!RequiresVideoConversion())
  180. {
  181. return "copy";
  182. }
  183. return "libx264";
  184. }
  185. /// <summary>
  186. /// Gets the name of the output audio codec
  187. /// </summary>
  188. private string GetAudioCodec(AudioStream audioStream, VideoOutputFormats outputFormat)
  189. {
  190. // Some output containers require specific codecs
  191. if (outputFormat == VideoOutputFormats.Webm)
  192. {
  193. // Per webm specification, it must be vorbis
  194. return "libvorbis";
  195. }
  196. if (outputFormat == VideoOutputFormats.Asf)
  197. {
  198. return "wmav2";
  199. }
  200. if (outputFormat == VideoOutputFormats.Wmv)
  201. {
  202. return "wmav2";
  203. }
  204. if (outputFormat == VideoOutputFormats.Ogv)
  205. {
  206. return "libvorbis";
  207. }
  208. // Skip encoding when possible
  209. if (!RequiresAudioConversion(audioStream))
  210. {
  211. return "copy";
  212. }
  213. return "libvo_aacenc";
  214. }
  215. /// <summary>
  216. /// Gets the number of audio channels to specify on the command line
  217. /// </summary>
  218. private int? GetNumAudioChannelsParam(string audioCodec, int libraryItemChannels)
  219. {
  220. if (libraryItemChannels > 2)
  221. {
  222. if (audioCodec.Equals("libvo_aacenc"))
  223. {
  224. // libvo_aacenc currently only supports two channel output
  225. return 2;
  226. }
  227. if (audioCodec.Equals("wmav2"))
  228. {
  229. // wmav2 currently only supports two channel output
  230. return 2;
  231. }
  232. }
  233. return GetNumAudioChannelsParam(libraryItemChannels);
  234. }
  235. /// <summary>
  236. /// Determines if the video stream requires encoding
  237. /// </summary>
  238. private bool RequiresVideoConversion()
  239. {
  240. // Check dimensions
  241. // If a specific width is required, validate that
  242. if (Width.HasValue)
  243. {
  244. if (Width.Value != LibraryItem.Width)
  245. {
  246. return true;
  247. }
  248. }
  249. // If a specific height is required, validate that
  250. if (Height.HasValue)
  251. {
  252. if (Height.Value != LibraryItem.Height)
  253. {
  254. return true;
  255. }
  256. }
  257. // If a max width is required, validate that
  258. if (MaxWidth.HasValue)
  259. {
  260. if (MaxWidth.Value < LibraryItem.Width)
  261. {
  262. return true;
  263. }
  264. }
  265. // If a max height is required, validate that
  266. if (MaxHeight.HasValue)
  267. {
  268. if (MaxHeight.Value < LibraryItem.Height)
  269. {
  270. return true;
  271. }
  272. }
  273. // If the codec is already h264, don't encode
  274. if (LibraryItem.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 || LibraryItem.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1)
  275. {
  276. return false;
  277. }
  278. return false;
  279. }
  280. /// <summary>
  281. /// Determines if the audio stream requires encoding
  282. /// </summary>
  283. private bool RequiresAudioConversion(AudioStream audio)
  284. {
  285. // If the input stream has more audio channels than the client can handle, we need to encode
  286. if (AudioChannels.HasValue)
  287. {
  288. if (audio.Channels > AudioChannels.Value)
  289. {
  290. return true;
  291. }
  292. }
  293. // Aac, ac-3 and mp3 are all pretty much universally supported. No need to encode them
  294. if (audio.Codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1)
  295. {
  296. return false;
  297. }
  298. if (audio.Codec.IndexOf("ac-3", StringComparison.OrdinalIgnoreCase) != -1 || audio.Codec.IndexOf("ac3", StringComparison.OrdinalIgnoreCase) != -1)
  299. {
  300. return false;
  301. }
  302. if (audio.Codec.IndexOf("mpeg", StringComparison.OrdinalIgnoreCase) != -1 || audio.Codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1)
  303. {
  304. return false;
  305. }
  306. return true;
  307. }
  308. /// <summary>
  309. /// Gets the fixed output video height, in pixels
  310. /// </summary>
  311. private int? Height
  312. {
  313. get
  314. {
  315. string val = QueryString["height"];
  316. if (string.IsNullOrEmpty(val))
  317. {
  318. return null;
  319. }
  320. return int.Parse(val);
  321. }
  322. }
  323. /// <summary>
  324. /// Gets the fixed output video width, in pixels
  325. /// </summary>
  326. private int? Width
  327. {
  328. get
  329. {
  330. string val = QueryString["width"];
  331. if (string.IsNullOrEmpty(val))
  332. {
  333. return null;
  334. }
  335. return int.Parse(val);
  336. }
  337. }
  338. /// <summary>
  339. /// Gets the maximum output video height, in pixels
  340. /// </summary>
  341. private int? MaxHeight
  342. {
  343. get
  344. {
  345. string val = QueryString["maxheight"];
  346. if (string.IsNullOrEmpty(val))
  347. {
  348. return null;
  349. }
  350. return int.Parse(val);
  351. }
  352. }
  353. /// <summary>
  354. /// Gets the maximum output video width, in pixels
  355. /// </summary>
  356. private int? MaxWidth
  357. {
  358. get
  359. {
  360. string val = QueryString["maxwidth"];
  361. if (string.IsNullOrEmpty(val))
  362. {
  363. return null;
  364. }
  365. return int.Parse(val);
  366. }
  367. }
  368. }
  369. }