2
0

VideoHandler.cs 13 KB

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