VideosController.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Jellyfin.Api.Attributes;
  10. using Jellyfin.Api.Extensions;
  11. using Jellyfin.Api.Helpers;
  12. using Jellyfin.Api.ModelBinders;
  13. using Jellyfin.Extensions;
  14. using MediaBrowser.Common.Api;
  15. using MediaBrowser.Common.Configuration;
  16. using MediaBrowser.Common.Net;
  17. using MediaBrowser.Controller.Configuration;
  18. using MediaBrowser.Controller.Dto;
  19. using MediaBrowser.Controller.Entities;
  20. using MediaBrowser.Controller.Library;
  21. using MediaBrowser.Controller.MediaEncoding;
  22. using MediaBrowser.Controller.Streaming;
  23. using MediaBrowser.Model.Dlna;
  24. using MediaBrowser.Model.Dto;
  25. using MediaBrowser.Model.Entities;
  26. using MediaBrowser.Model.MediaInfo;
  27. using MediaBrowser.Model.Net;
  28. using MediaBrowser.Model.Querying;
  29. using Microsoft.AspNetCore.Authorization;
  30. using Microsoft.AspNetCore.Http;
  31. using Microsoft.AspNetCore.Mvc;
  32. namespace Jellyfin.Api.Controllers;
  33. /// <summary>
  34. /// The videos controller.
  35. /// </summary>
  36. public class VideosController : BaseJellyfinApiController
  37. {
  38. private readonly ILibraryManager _libraryManager;
  39. private readonly IUserManager _userManager;
  40. private readonly IDtoService _dtoService;
  41. private readonly IMediaSourceManager _mediaSourceManager;
  42. private readonly IServerConfigurationManager _serverConfigurationManager;
  43. private readonly IMediaEncoder _mediaEncoder;
  44. private readonly ITranscodeManager _transcodeManager;
  45. private readonly IHttpClientFactory _httpClientFactory;
  46. private readonly EncodingHelper _encodingHelper;
  47. private readonly TranscodingJobType _transcodingJobType = TranscodingJobType.Progressive;
  48. /// <summary>
  49. /// Initializes a new instance of the <see cref="VideosController"/> class.
  50. /// </summary>
  51. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  52. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  53. /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
  54. /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
  55. /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  56. /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
  57. /// <param name="transcodeManager">Instance of the <see cref="ITranscodeManager"/> interface.</param>
  58. /// <param name="httpClientFactory">Instance of the <see cref="IHttpClientFactory"/> interface.</param>
  59. /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
  60. public VideosController(
  61. ILibraryManager libraryManager,
  62. IUserManager userManager,
  63. IDtoService dtoService,
  64. IMediaSourceManager mediaSourceManager,
  65. IServerConfigurationManager serverConfigurationManager,
  66. IMediaEncoder mediaEncoder,
  67. ITranscodeManager transcodeManager,
  68. IHttpClientFactory httpClientFactory,
  69. EncodingHelper encodingHelper)
  70. {
  71. _libraryManager = libraryManager;
  72. _userManager = userManager;
  73. _dtoService = dtoService;
  74. _mediaSourceManager = mediaSourceManager;
  75. _serverConfigurationManager = serverConfigurationManager;
  76. _mediaEncoder = mediaEncoder;
  77. _transcodeManager = transcodeManager;
  78. _httpClientFactory = httpClientFactory;
  79. _encodingHelper = encodingHelper;
  80. }
  81. /// <summary>
  82. /// Gets additional parts for a video.
  83. /// </summary>
  84. /// <param name="itemId">The item id.</param>
  85. /// <param name="userId">Optional. Filter by user id, and attach user data.</param>
  86. /// <response code="200">Additional parts returned.</response>
  87. /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the parts.</returns>
  88. [HttpGet("{itemId}/AdditionalParts")]
  89. [Authorize]
  90. [ProducesResponseType(StatusCodes.Status200OK)]
  91. public ActionResult<QueryResult<BaseItemDto>> GetAdditionalPart([FromRoute, Required] Guid itemId, [FromQuery] Guid? userId)
  92. {
  93. userId = RequestHelpers.GetUserId(User, userId);
  94. var user = userId.IsNullOrEmpty()
  95. ? null
  96. : _userManager.GetUserById(userId.Value);
  97. var item = itemId.IsEmpty()
  98. ? (userId.IsNullOrEmpty()
  99. ? _libraryManager.RootFolder
  100. : _libraryManager.GetUserRootFolder())
  101. : _libraryManager.GetItemById<BaseItem>(itemId, user);
  102. if (item is null)
  103. {
  104. return NotFound();
  105. }
  106. var dtoOptions = new DtoOptions();
  107. dtoOptions = dtoOptions.AddClientFields(User);
  108. BaseItemDto[] items;
  109. if (item is Video video)
  110. {
  111. items = video.GetAdditionalParts()
  112. .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, video))
  113. .ToArray();
  114. }
  115. else
  116. {
  117. items = Array.Empty<BaseItemDto>();
  118. }
  119. var result = new QueryResult<BaseItemDto>(items);
  120. return result;
  121. }
  122. /// <summary>
  123. /// Removes alternate video sources.
  124. /// </summary>
  125. /// <param name="itemId">The item id.</param>
  126. /// <response code="204">Alternate sources deleted.</response>
  127. /// <response code="404">Video not found.</response>
  128. /// <returns>A <see cref="NoContentResult"/> indicating success, or a <see cref="NotFoundResult"/> if the video doesn't exist.</returns>
  129. [HttpDelete("{itemId}/AlternateSources")]
  130. [Authorize(Policy = Policies.RequiresElevation)]
  131. [ProducesResponseType(StatusCodes.Status204NoContent)]
  132. [ProducesResponseType(StatusCodes.Status404NotFound)]
  133. public async Task<ActionResult> DeleteAlternateSources([FromRoute, Required] Guid itemId)
  134. {
  135. var item = _libraryManager.GetItemById<Video>(itemId, User.GetUserId());
  136. if (item is null)
  137. {
  138. return NotFound();
  139. }
  140. if (item.LinkedAlternateVersions.Length == 0)
  141. {
  142. item = _libraryManager.GetItemById<Video>(Guid.Parse(item.PrimaryVersionId));
  143. }
  144. if (item is null)
  145. {
  146. return NotFound();
  147. }
  148. foreach (var link in item.GetLinkedAlternateVersions())
  149. {
  150. link.SetPrimaryVersionId(null);
  151. link.LinkedAlternateVersions = Array.Empty<LinkedChild>();
  152. await link.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  153. }
  154. item.LinkedAlternateVersions = Array.Empty<LinkedChild>();
  155. item.SetPrimaryVersionId(null);
  156. await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  157. return NoContent();
  158. }
  159. /// <summary>
  160. /// Merges videos into a single record.
  161. /// </summary>
  162. /// <param name="ids">Item id list. This allows multiple, comma delimited.</param>
  163. /// <response code="204">Videos merged.</response>
  164. /// <response code="400">Supply at least 2 video ids.</response>
  165. /// <returns>A <see cref="NoContentResult"/> indicating success, or a <see cref="BadRequestResult"/> if less than two ids were supplied.</returns>
  166. [HttpPost("MergeVersions")]
  167. [Authorize(Policy = Policies.RequiresElevation)]
  168. [ProducesResponseType(StatusCodes.Status204NoContent)]
  169. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  170. public async Task<ActionResult> MergeVersions([FromQuery, Required, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] Guid[] ids)
  171. {
  172. var userId = User.GetUserId();
  173. var items = ids
  174. .Select(i => _libraryManager.GetItemById<BaseItem>(i, userId))
  175. .OfType<Video>()
  176. .OrderBy(i => i.Id)
  177. .ToList();
  178. if (items.Count < 2)
  179. {
  180. return BadRequest("Please supply at least two videos to merge.");
  181. }
  182. var primaryVersion = items.FirstOrDefault(i => i.MediaSourceCount > 1 && string.IsNullOrEmpty(i.PrimaryVersionId));
  183. if (primaryVersion is null)
  184. {
  185. primaryVersion = items
  186. .OrderBy(i =>
  187. {
  188. if (i.Video3DFormat.HasValue || i.VideoType != VideoType.VideoFile)
  189. {
  190. return 1;
  191. }
  192. return 0;
  193. })
  194. .ThenByDescending(i => i.GetDefaultVideoStream()?.Width ?? 0)
  195. .First();
  196. }
  197. var alternateVersionsOfPrimary = primaryVersion.LinkedAlternateVersions.ToList();
  198. foreach (var item in items.Where(i => !i.Id.Equals(primaryVersion.Id)))
  199. {
  200. item.SetPrimaryVersionId(primaryVersion.Id.ToString("N", CultureInfo.InvariantCulture));
  201. await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  202. if (!alternateVersionsOfPrimary.Any(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase)))
  203. {
  204. alternateVersionsOfPrimary.Add(new LinkedChild
  205. {
  206. Path = item.Path,
  207. ItemId = item.Id
  208. });
  209. }
  210. foreach (var linkedItem in item.LinkedAlternateVersions)
  211. {
  212. if (!alternateVersionsOfPrimary.Any(i => string.Equals(i.Path, linkedItem.Path, StringComparison.OrdinalIgnoreCase)))
  213. {
  214. alternateVersionsOfPrimary.Add(linkedItem);
  215. }
  216. }
  217. if (item.LinkedAlternateVersions.Length > 0)
  218. {
  219. item.LinkedAlternateVersions = Array.Empty<LinkedChild>();
  220. await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  221. }
  222. }
  223. primaryVersion.LinkedAlternateVersions = alternateVersionsOfPrimary.ToArray();
  224. await primaryVersion.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  225. return NoContent();
  226. }
  227. /// <summary>
  228. /// Gets a video stream.
  229. /// </summary>
  230. /// <param name="itemId">The item id.</param>
  231. /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, mpg, avi, 3gp, wmv, wtv, m2ts, mov, iso, flv. </param>
  232. /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
  233. /// <param name="params">The streaming parameters.</param>
  234. /// <param name="tag">The tag.</param>
  235. /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
  236. /// <param name="playSessionId">The play session id.</param>
  237. /// <param name="segmentContainer">The segment container.</param>
  238. /// <param name="segmentLength">The segment length.</param>
  239. /// <param name="minSegments">The minimum number of segments.</param>
  240. /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
  241. /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
  242. /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension.</param>
  243. /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
  244. /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
  245. /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
  246. /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
  247. /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
  248. /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
  249. /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
  250. /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
  251. /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
  252. /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
  253. /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
  254. /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
  255. /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
  256. /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
  257. /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
  258. /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
  259. /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
  260. /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
  261. /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
  262. /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
  263. /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
  264. /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
  265. /// <param name="maxRefFrames">Optional.</param>
  266. /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
  267. /// <param name="requireAvc">Optional. Whether to require avc.</param>
  268. /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
  269. /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
  270. /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
  271. /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
  272. /// <param name="liveStreamId">The live stream id.</param>
  273. /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
  274. /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension.</param>
  275. /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
  276. /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
  277. /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
  278. /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
  279. /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
  280. /// <param name="streamOptions">Optional. The streaming options.</param>
  281. /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
  282. /// <response code="200">Video stream returned.</response>
  283. /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
  284. [HttpGet("{itemId}/stream")]
  285. [HttpHead("{itemId}/stream", Name = "HeadVideoStream")]
  286. [ProducesResponseType(StatusCodes.Status200OK)]
  287. [ProducesVideoFile]
  288. public async Task<ActionResult> GetVideoStream(
  289. [FromRoute, Required] Guid itemId,
  290. [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? container,
  291. [FromQuery] bool? @static,
  292. [FromQuery] string? @params,
  293. [FromQuery] string? tag,
  294. [FromQuery, ParameterObsolete] string? deviceProfileId,
  295. [FromQuery] string? playSessionId,
  296. [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
  297. [FromQuery] int? segmentLength,
  298. [FromQuery] int? minSegments,
  299. [FromQuery] string? mediaSourceId,
  300. [FromQuery] string? deviceId,
  301. [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
  302. [FromQuery] bool? enableAutoStreamCopy,
  303. [FromQuery] bool? allowVideoStreamCopy,
  304. [FromQuery] bool? allowAudioStreamCopy,
  305. [FromQuery] bool? breakOnNonKeyFrames,
  306. [FromQuery] int? audioSampleRate,
  307. [FromQuery] int? maxAudioBitDepth,
  308. [FromQuery] int? audioBitRate,
  309. [FromQuery] int? audioChannels,
  310. [FromQuery] int? maxAudioChannels,
  311. [FromQuery] string? profile,
  312. [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
  313. [FromQuery] float? framerate,
  314. [FromQuery] float? maxFramerate,
  315. [FromQuery] bool? copyTimestamps,
  316. [FromQuery] long? startTimeTicks,
  317. [FromQuery] int? width,
  318. [FromQuery] int? height,
  319. [FromQuery] int? maxWidth,
  320. [FromQuery] int? maxHeight,
  321. [FromQuery] int? videoBitRate,
  322. [FromQuery] int? subtitleStreamIndex,
  323. [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
  324. [FromQuery] int? maxRefFrames,
  325. [FromQuery] int? maxVideoBitDepth,
  326. [FromQuery] bool? requireAvc,
  327. [FromQuery] bool? deInterlace,
  328. [FromQuery] bool? requireNonAnamorphic,
  329. [FromQuery] int? transcodingMaxAudioChannels,
  330. [FromQuery] int? cpuCoreLimit,
  331. [FromQuery] string? liveStreamId,
  332. [FromQuery] bool? enableMpegtsM2TsMode,
  333. [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
  334. [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
  335. [FromQuery] string? transcodeReasons,
  336. [FromQuery] int? audioStreamIndex,
  337. [FromQuery] int? videoStreamIndex,
  338. [FromQuery] EncodingContext? context,
  339. [FromQuery] Dictionary<string, string> streamOptions,
  340. [FromQuery] bool enableAudioVbrEncoding = true)
  341. {
  342. var isHeadRequest = Request.Method == System.Net.WebRequestMethods.Http.Head;
  343. // CTS lifecycle is managed internally.
  344. var cancellationTokenSource = new CancellationTokenSource();
  345. var streamingRequest = new VideoRequestDto
  346. {
  347. Id = itemId,
  348. Container = container,
  349. Static = @static ?? false,
  350. Params = @params,
  351. Tag = tag,
  352. PlaySessionId = playSessionId,
  353. SegmentContainer = segmentContainer,
  354. SegmentLength = segmentLength,
  355. MinSegments = minSegments,
  356. MediaSourceId = mediaSourceId,
  357. DeviceId = deviceId,
  358. AudioCodec = audioCodec,
  359. EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
  360. AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
  361. AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
  362. BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
  363. AudioSampleRate = audioSampleRate,
  364. MaxAudioChannels = maxAudioChannels,
  365. AudioBitRate = audioBitRate,
  366. MaxAudioBitDepth = maxAudioBitDepth,
  367. AudioChannels = audioChannels,
  368. Profile = profile,
  369. Level = level,
  370. Framerate = framerate,
  371. MaxFramerate = maxFramerate,
  372. CopyTimestamps = copyTimestamps ?? false,
  373. StartTimeTicks = startTimeTicks,
  374. Width = width,
  375. Height = height,
  376. MaxWidth = maxWidth,
  377. MaxHeight = maxHeight,
  378. VideoBitRate = videoBitRate,
  379. SubtitleStreamIndex = subtitleStreamIndex,
  380. SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode,
  381. MaxRefFrames = maxRefFrames,
  382. MaxVideoBitDepth = maxVideoBitDepth,
  383. RequireAvc = requireAvc ?? false,
  384. DeInterlace = deInterlace ?? false,
  385. RequireNonAnamorphic = requireNonAnamorphic ?? false,
  386. TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
  387. CpuCoreLimit = cpuCoreLimit,
  388. LiveStreamId = liveStreamId,
  389. EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
  390. VideoCodec = videoCodec,
  391. SubtitleCodec = subtitleCodec,
  392. TranscodeReasons = transcodeReasons,
  393. AudioStreamIndex = audioStreamIndex,
  394. VideoStreamIndex = videoStreamIndex,
  395. Context = context ?? EncodingContext.Streaming,
  396. StreamOptions = streamOptions,
  397. EnableAudioVbrEncoding = enableAudioVbrEncoding
  398. };
  399. var state = await StreamingHelpers.GetStreamingState(
  400. streamingRequest,
  401. HttpContext,
  402. _mediaSourceManager,
  403. _userManager,
  404. _libraryManager,
  405. _serverConfigurationManager,
  406. _mediaEncoder,
  407. _encodingHelper,
  408. _transcodeManager,
  409. _transcodingJobType,
  410. cancellationTokenSource.Token)
  411. .ConfigureAwait(false);
  412. if (@static.HasValue && @static.Value && state.DirectStreamProvider is not null)
  413. {
  414. var liveStreamInfo = _mediaSourceManager.GetLiveStreamInfo(streamingRequest.LiveStreamId);
  415. if (liveStreamInfo is null)
  416. {
  417. return NotFound();
  418. }
  419. var liveStream = new ProgressiveFileStream(liveStreamInfo.GetStream());
  420. // TODO (moved from MediaBrowser.Api): Don't hardcode contentType
  421. return File(liveStream, MimeTypes.GetMimeType("file.ts"));
  422. }
  423. // Static remote stream
  424. if (@static.HasValue && @static.Value && state.InputProtocol == MediaProtocol.Http)
  425. {
  426. var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
  427. return await FileStreamResponseHelpers.GetStaticRemoteStreamResult(state, httpClient, HttpContext).ConfigureAwait(false);
  428. }
  429. if (@static.HasValue && @static.Value && state.InputProtocol != MediaProtocol.File)
  430. {
  431. return BadRequest($"Input protocol {state.InputProtocol} cannot be streamed statically");
  432. }
  433. // Static stream
  434. if (@static.HasValue && @static.Value && !(state.MediaSource.VideoType == VideoType.BluRay || state.MediaSource.VideoType == VideoType.Dvd))
  435. {
  436. var contentType = state.GetMimeType("." + state.OutputContainer, false) ?? state.GetMimeType(state.MediaPath);
  437. if (state.MediaSource.IsInfiniteStream)
  438. {
  439. var liveStream = new ProgressiveFileStream(state.MediaPath, null, _transcodeManager);
  440. return File(liveStream, contentType);
  441. }
  442. return FileStreamResponseHelpers.GetStaticFileResult(
  443. state.MediaPath,
  444. contentType);
  445. }
  446. // Need to start ffmpeg (because media can't be returned directly)
  447. var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
  448. var ffmpegCommandLineArguments = _encodingHelper.GetProgressiveVideoFullCommandLine(state, encodingOptions, EncoderPreset.superfast);
  449. return await FileStreamResponseHelpers.GetTranscodedFile(
  450. state,
  451. isHeadRequest,
  452. HttpContext,
  453. _transcodeManager,
  454. ffmpegCommandLineArguments,
  455. _transcodingJobType,
  456. cancellationTokenSource).ConfigureAwait(false);
  457. }
  458. /// <summary>
  459. /// Gets a video stream.
  460. /// </summary>
  461. /// <param name="itemId">The item id.</param>
  462. /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, mpg, avi, 3gp, wmv, wtv, m2ts, mov, iso, flv. </param>
  463. /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param>
  464. /// <param name="params">The streaming parameters.</param>
  465. /// <param name="tag">The tag.</param>
  466. /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
  467. /// <param name="playSessionId">The play session id.</param>
  468. /// <param name="segmentContainer">The segment container.</param>
  469. /// <param name="segmentLength">The segment length.</param>
  470. /// <param name="minSegments">The minimum number of segments.</param>
  471. /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
  472. /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
  473. /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension.</param>
  474. /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
  475. /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
  476. /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
  477. /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
  478. /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
  479. /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
  480. /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
  481. /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
  482. /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
  483. /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
  484. /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
  485. /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
  486. /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param>
  487. /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
  488. /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
  489. /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
  490. /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
  491. /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
  492. /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
  493. /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
  494. /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
  495. /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
  496. /// <param name="maxRefFrames">Optional.</param>
  497. /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
  498. /// <param name="requireAvc">Optional. Whether to require avc.</param>
  499. /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
  500. /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
  501. /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
  502. /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
  503. /// <param name="liveStreamId">The live stream id.</param>
  504. /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
  505. /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension.</param>
  506. /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
  507. /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
  508. /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
  509. /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
  510. /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
  511. /// <param name="streamOptions">Optional. The streaming options.</param>
  512. /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
  513. /// <response code="200">Video stream returned.</response>
  514. /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
  515. [HttpGet("{itemId}/stream.{container}")]
  516. [HttpHead("{itemId}/stream.{container}", Name = "HeadVideoStreamByContainer")]
  517. [ProducesResponseType(StatusCodes.Status200OK)]
  518. [ProducesVideoFile]
  519. public Task<ActionResult> GetVideoStreamByContainer(
  520. [FromRoute, Required] Guid itemId,
  521. [FromRoute, Required] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string container,
  522. [FromQuery] bool? @static,
  523. [FromQuery] string? @params,
  524. [FromQuery] string? tag,
  525. [FromQuery] string? deviceProfileId,
  526. [FromQuery] string? playSessionId,
  527. [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
  528. [FromQuery] int? segmentLength,
  529. [FromQuery] int? minSegments,
  530. [FromQuery] string? mediaSourceId,
  531. [FromQuery] string? deviceId,
  532. [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
  533. [FromQuery] bool? enableAutoStreamCopy,
  534. [FromQuery] bool? allowVideoStreamCopy,
  535. [FromQuery] bool? allowAudioStreamCopy,
  536. [FromQuery] bool? breakOnNonKeyFrames,
  537. [FromQuery] int? audioSampleRate,
  538. [FromQuery] int? maxAudioBitDepth,
  539. [FromQuery] int? audioBitRate,
  540. [FromQuery] int? audioChannels,
  541. [FromQuery] int? maxAudioChannels,
  542. [FromQuery] string? profile,
  543. [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
  544. [FromQuery] float? framerate,
  545. [FromQuery] float? maxFramerate,
  546. [FromQuery] bool? copyTimestamps,
  547. [FromQuery] long? startTimeTicks,
  548. [FromQuery] int? width,
  549. [FromQuery] int? height,
  550. [FromQuery] int? maxWidth,
  551. [FromQuery] int? maxHeight,
  552. [FromQuery] int? videoBitRate,
  553. [FromQuery] int? subtitleStreamIndex,
  554. [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
  555. [FromQuery] int? maxRefFrames,
  556. [FromQuery] int? maxVideoBitDepth,
  557. [FromQuery] bool? requireAvc,
  558. [FromQuery] bool? deInterlace,
  559. [FromQuery] bool? requireNonAnamorphic,
  560. [FromQuery] int? transcodingMaxAudioChannels,
  561. [FromQuery] int? cpuCoreLimit,
  562. [FromQuery] string? liveStreamId,
  563. [FromQuery] bool? enableMpegtsM2TsMode,
  564. [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
  565. [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
  566. [FromQuery] string? transcodeReasons,
  567. [FromQuery] int? audioStreamIndex,
  568. [FromQuery] int? videoStreamIndex,
  569. [FromQuery] EncodingContext? context,
  570. [FromQuery] Dictionary<string, string> streamOptions,
  571. [FromQuery] bool enableAudioVbrEncoding = true)
  572. {
  573. return GetVideoStream(
  574. itemId,
  575. container,
  576. @static,
  577. @params,
  578. tag,
  579. deviceProfileId,
  580. playSessionId,
  581. segmentContainer,
  582. segmentLength,
  583. minSegments,
  584. mediaSourceId,
  585. deviceId,
  586. audioCodec,
  587. enableAutoStreamCopy,
  588. allowVideoStreamCopy,
  589. allowAudioStreamCopy,
  590. breakOnNonKeyFrames,
  591. audioSampleRate,
  592. maxAudioBitDepth,
  593. audioBitRate,
  594. audioChannels,
  595. maxAudioChannels,
  596. profile,
  597. level,
  598. framerate,
  599. maxFramerate,
  600. copyTimestamps,
  601. startTimeTicks,
  602. width,
  603. height,
  604. maxWidth,
  605. maxHeight,
  606. videoBitRate,
  607. subtitleStreamIndex,
  608. subtitleMethod,
  609. maxRefFrames,
  610. maxVideoBitDepth,
  611. requireAvc,
  612. deInterlace,
  613. requireNonAnamorphic,
  614. transcodingMaxAudioChannels,
  615. cpuCoreLimit,
  616. liveStreamId,
  617. enableMpegtsM2TsMode,
  618. videoCodec,
  619. subtitleCodec,
  620. transcodeReasons,
  621. audioStreamIndex,
  622. videoStreamIndex,
  623. context,
  624. streamOptions,
  625. enableAudioVbrEncoding);
  626. }
  627. }