BaseProgressiveStreamingService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. using MediaBrowser.Api.Images;
  2. using MediaBrowser.Common.MediaInfo;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Entities.Audio;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Controller.Persistence;
  11. using MediaBrowser.Model.Dto;
  12. using MediaBrowser.Model.Entities;
  13. using MediaBrowser.Model.IO;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.Net.Http;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Api.Playback.Progressive
  20. {
  21. /// <summary>
  22. /// Class BaseProgressiveStreamingService
  23. /// </summary>
  24. public abstract class BaseProgressiveStreamingService : BaseStreamingService
  25. {
  26. protected readonly IItemRepository ItemRepository;
  27. protected readonly IImageProcessor ImageProcessor;
  28. protected BaseProgressiveStreamingService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IItemRepository itemRepository, IDtoService dtoService, IImageProcessor imageProcessor) :
  29. base(appPaths, userManager, libraryManager, isoManager, mediaEncoder, dtoService)
  30. {
  31. ItemRepository = itemRepository;
  32. ImageProcessor = imageProcessor;
  33. }
  34. /// <summary>
  35. /// Gets the output file extension.
  36. /// </summary>
  37. /// <param name="state">The state.</param>
  38. /// <returns>System.String.</returns>
  39. protected override string GetOutputFileExtension(StreamState state)
  40. {
  41. var ext = base.GetOutputFileExtension(state);
  42. if (!string.IsNullOrEmpty(ext))
  43. {
  44. return ext;
  45. }
  46. var videoRequest = state.Request as VideoStreamRequest;
  47. // Try to infer based on the desired video codec
  48. if (videoRequest != null && videoRequest.VideoCodec.HasValue)
  49. {
  50. var video = state.Item as Video;
  51. if (video != null)
  52. {
  53. switch (videoRequest.VideoCodec.Value)
  54. {
  55. case VideoCodecs.H264:
  56. return ".ts";
  57. case VideoCodecs.Theora:
  58. return ".ogv";
  59. case VideoCodecs.Vpx:
  60. return ".webm";
  61. case VideoCodecs.Wmv:
  62. return ".asf";
  63. }
  64. }
  65. }
  66. // Try to infer based on the desired audio codec
  67. if (state.Request.AudioCodec.HasValue)
  68. {
  69. var audio = state.Item as Audio;
  70. if (audio != null)
  71. {
  72. switch (state.Request.AudioCodec.Value)
  73. {
  74. case AudioCodecs.Aac:
  75. return ".aac";
  76. case AudioCodecs.Mp3:
  77. return ".mp3";
  78. case AudioCodecs.Vorbis:
  79. return ".ogg";
  80. case AudioCodecs.Wma:
  81. return ".wma";
  82. }
  83. }
  84. }
  85. return null;
  86. }
  87. /// <summary>
  88. /// Adds the dlna headers.
  89. /// </summary>
  90. /// <param name="state">The state.</param>
  91. /// <param name="responseHeaders">The response headers.</param>
  92. /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
  93. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  94. private void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
  95. {
  96. var timeSeek = RequestContext.GetHeader("TimeSeekRange.dlna.org");
  97. if (!string.IsNullOrEmpty(timeSeek))
  98. {
  99. ResultFactory.ThrowError(406, "Time seek not supported during encoding.", responseHeaders);
  100. return;
  101. }
  102. var transferMode = RequestContext.GetHeader("transferMode.dlna.org");
  103. responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
  104. var contentFeatures = string.Empty;
  105. var extension = GetOutputFileExtension(state);
  106. // first bit means Time based seek supported, second byte range seek supported (not sure about the order now), so 01 = only byte seek, 10 = time based, 11 = both, 00 = none
  107. var orgOp = isStaticallyStreamed ? ";DLNA.ORG_OP=01" : ";DLNA.ORG_OP=00";
  108. // 0 = native, 1 = transcoded
  109. var orgCi = isStaticallyStreamed ? ";DLNA.ORG_CI=0" : ";DLNA.ORG_CI=1";
  110. const string dlnaflags = ";DLNA.ORG_FLAGS=01500000000000000000000000000000";
  111. if (string.Equals(extension, ".mp3", StringComparison.OrdinalIgnoreCase))
  112. {
  113. contentFeatures = "DLNA.ORG_PN=MP3";
  114. }
  115. else if (string.Equals(extension, ".aac", StringComparison.OrdinalIgnoreCase))
  116. {
  117. contentFeatures = "DLNA.ORG_PN=AAC_ISO";
  118. }
  119. else if (string.Equals(extension, ".wma", StringComparison.OrdinalIgnoreCase))
  120. {
  121. contentFeatures = "DLNA.ORG_PN=WMABASE";
  122. }
  123. else if (string.Equals(extension, ".avi", StringComparison.OrdinalIgnoreCase))
  124. {
  125. contentFeatures = "DLNA.ORG_PN=AVI";
  126. }
  127. else if (string.Equals(extension, ".mp4", StringComparison.OrdinalIgnoreCase))
  128. {
  129. contentFeatures = "DLNA.ORG_PN=MPEG4_P2_SP_AAC";
  130. }
  131. else if (string.Equals(extension, ".mpeg", StringComparison.OrdinalIgnoreCase))
  132. {
  133. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  134. }
  135. else if (string.Equals(extension, ".wmv", StringComparison.OrdinalIgnoreCase))
  136. {
  137. contentFeatures = "DLNA.ORG_PN=WMVHIGH_BASE";
  138. }
  139. else if (string.Equals(extension, ".asf", StringComparison.OrdinalIgnoreCase))
  140. {
  141. // ??
  142. contentFeatures = "DLNA.ORG_PN=WMVHIGH_BASE";
  143. }
  144. else if (string.Equals(extension, ".mkv", StringComparison.OrdinalIgnoreCase))
  145. {
  146. // ??
  147. contentFeatures = "";
  148. }
  149. if (!string.IsNullOrEmpty(contentFeatures))
  150. {
  151. responseHeaders["ContentFeatures.DLNA.ORG"] = (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';');
  152. }
  153. }
  154. /// <summary>
  155. /// Gets the type of the transcoding job.
  156. /// </summary>
  157. /// <value>The type of the transcoding job.</value>
  158. protected override TranscodingJobType TranscodingJobType
  159. {
  160. get { return TranscodingJobType.Progressive; }
  161. }
  162. /// <summary>
  163. /// Processes the request.
  164. /// </summary>
  165. /// <param name="request">The request.</param>
  166. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  167. /// <returns>Task.</returns>
  168. protected object ProcessRequest(StreamRequest request, bool isHeadRequest)
  169. {
  170. var state = GetState(request);
  171. if (request.AlbumArt)
  172. {
  173. return GetAlbumArtResponse(state);
  174. }
  175. var responseHeaders = new Dictionary<string, string>();
  176. if (request.Static && state.Item.LocationType == LocationType.Remote)
  177. {
  178. return GetStaticRemoteStreamResult(state.Item, responseHeaders, isHeadRequest).Result;
  179. }
  180. var outputPath = GetOutputFilePath(state);
  181. var outputPathExists = File.Exists(outputPath);
  182. //var isStatic = request.Static ||
  183. // (outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive));
  184. //AddDlnaHeaders(state, responseHeaders, isStatic);
  185. if (request.Static)
  186. {
  187. return ResultFactory.GetStaticFileResult(RequestContext, state.Item.Path, FileShare.Read, responseHeaders, isHeadRequest);
  188. }
  189. if (outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive))
  190. {
  191. return ResultFactory.GetStaticFileResult(RequestContext, outputPath, FileShare.Read, responseHeaders, isHeadRequest);
  192. }
  193. return GetStreamResult(state, responseHeaders, isHeadRequest).Result;
  194. }
  195. /// <summary>
  196. /// Gets the static remote stream result.
  197. /// </summary>
  198. /// <param name="item">The item.</param>
  199. /// <param name="responseHeaders">The response headers.</param>
  200. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  201. /// <returns>Task{System.Object}.</returns>
  202. private async Task<object> GetStaticRemoteStreamResult(BaseItem item, Dictionary<string, string> responseHeaders, bool isHeadRequest)
  203. {
  204. responseHeaders["Accept-Ranges"] = "none";
  205. var httpClient = new HttpClient();
  206. using (var message = new HttpRequestMessage(HttpMethod.Get, item.Path))
  207. {
  208. var useragent = GetUserAgent(item);
  209. if (!string.IsNullOrEmpty(useragent))
  210. {
  211. message.Headers.Add("User-Agent", useragent);
  212. }
  213. var response = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
  214. response.EnsureSuccessStatusCode();
  215. var contentType = response.Content.Headers.ContentType.MediaType;
  216. // Headers only
  217. if (isHeadRequest)
  218. {
  219. response.Dispose();
  220. httpClient.Dispose();
  221. return ResultFactory.GetResult(null, contentType, responseHeaders);
  222. }
  223. var result = new StaticRemoteStreamWriter(response, httpClient);
  224. result.Options["Content-Type"] = contentType;
  225. // Add the response headers to the result object
  226. foreach (var header in responseHeaders)
  227. {
  228. result.Options[header.Key] = header.Value;
  229. }
  230. return result;
  231. }
  232. }
  233. /// <summary>
  234. /// Gets the album art response.
  235. /// </summary>
  236. /// <param name="state">The state.</param>
  237. /// <returns>System.Object.</returns>
  238. private object GetAlbumArtResponse(StreamState state)
  239. {
  240. var request = new GetItemImage
  241. {
  242. MaxWidth = 800,
  243. MaxHeight = 800,
  244. Type = ImageType.Primary,
  245. Id = state.Item.Id.ToString()
  246. };
  247. // Try and find some image to return
  248. if (!state.Item.HasImage(ImageType.Primary))
  249. {
  250. if (state.Item.HasImage(ImageType.Backdrop))
  251. {
  252. request.Type = ImageType.Backdrop;
  253. }
  254. else if (state.Item.HasImage(ImageType.Thumb))
  255. {
  256. request.Type = ImageType.Thumb;
  257. }
  258. else if (state.Item.HasImage(ImageType.Logo))
  259. {
  260. request.Type = ImageType.Logo;
  261. }
  262. }
  263. return new ImageService(UserManager, LibraryManager, ApplicationPaths, null, ItemRepository, DtoService, ImageProcessor)
  264. {
  265. Logger = Logger,
  266. RequestContext = RequestContext,
  267. ResultFactory = ResultFactory
  268. }.Get(request);
  269. }
  270. /// <summary>
  271. /// Gets the stream result.
  272. /// </summary>
  273. /// <param name="state">The state.</param>
  274. /// <param name="responseHeaders">The response headers.</param>
  275. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  276. /// <returns>Task{System.Object}.</returns>
  277. private async Task<object> GetStreamResult(StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest)
  278. {
  279. // Use the command line args with a dummy playlist path
  280. var outputPath = GetOutputFilePath(state);
  281. var contentType = MimeTypes.GetMimeType(outputPath);
  282. // Headers only
  283. if (isHeadRequest)
  284. {
  285. responseHeaders["Accept-Ranges"] = "none";
  286. return ResultFactory.GetResult(null, contentType, responseHeaders);
  287. }
  288. if (!File.Exists(outputPath))
  289. {
  290. await StartFfMpeg(state, outputPath).ConfigureAwait(false);
  291. }
  292. else
  293. {
  294. ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
  295. }
  296. var result = new ProgressiveStreamWriter(outputPath, Logger);
  297. result.Options["Accept-Ranges"] = "none";
  298. result.Options["Content-Type"] = contentType;
  299. // Add the response headers to the result object
  300. foreach (var item in responseHeaders)
  301. {
  302. result.Options[item.Key] = item.Value;
  303. }
  304. return result;
  305. }
  306. }
  307. }