VideosController.cs 33 KB

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