VideosController.cs 33 KB

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