BaseProgressiveStreamingService.cs 14 KB

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