2020-08-08 19:21:32 +00:00
using System ;
2020-07-24 22:49:43 +00:00
using System.Collections.Generic ;
2020-08-06 14:17:45 +00:00
using System.ComponentModel.DataAnnotations ;
2020-06-21 14:00:16 +00:00
using System.Globalization ;
using System.Linq ;
2020-07-24 22:49:43 +00:00
using System.Net.Http ;
2020-06-21 14:00:16 +00:00
using System.Threading ;
2020-07-24 22:49:43 +00:00
using System.Threading.Tasks ;
2020-09-01 23:26:49 +00:00
using Jellyfin.Api.Attributes ;
2020-06-21 14:00:16 +00:00
using Jellyfin.Api.Constants ;
using Jellyfin.Api.Extensions ;
using Jellyfin.Api.Helpers ;
2020-11-17 03:29:46 +00:00
using Jellyfin.Api.ModelBinders ;
2020-07-24 22:49:43 +00:00
using Jellyfin.Api.Models.StreamingDtos ;
using MediaBrowser.Common.Configuration ;
2020-08-31 17:05:21 +00:00
using MediaBrowser.Common.Net ;
2020-07-24 22:49:43 +00:00
using MediaBrowser.Controller.Configuration ;
using MediaBrowser.Controller.Devices ;
using MediaBrowser.Controller.Dlna ;
2020-06-21 14:00:16 +00:00
using MediaBrowser.Controller.Dto ;
using MediaBrowser.Controller.Entities ;
using MediaBrowser.Controller.Library ;
2020-07-24 22:49:43 +00:00
using MediaBrowser.Controller.MediaEncoding ;
using MediaBrowser.Controller.Net ;
using MediaBrowser.Model.Dlna ;
2020-06-21 14:00:16 +00:00
using MediaBrowser.Model.Dto ;
using MediaBrowser.Model.Entities ;
2020-07-24 22:49:43 +00:00
using MediaBrowser.Model.MediaInfo ;
using MediaBrowser.Model.Net ;
2020-06-21 14:00:16 +00:00
using MediaBrowser.Model.Querying ;
using Microsoft.AspNetCore.Authorization ;
using Microsoft.AspNetCore.Http ;
using Microsoft.AspNetCore.Mvc ;
namespace Jellyfin.Api.Controllers
{
/// <summary>
/// The videos controller.
/// </summary>
public class VideosController : BaseJellyfinApiController
{
private readonly ILibraryManager _libraryManager ;
private readonly IUserManager _userManager ;
private readonly IDtoService _dtoService ;
2020-07-24 22:49:43 +00:00
private readonly IDlnaManager _dlnaManager ;
private readonly IAuthorizationContext _authContext ;
private readonly IMediaSourceManager _mediaSourceManager ;
private readonly IServerConfigurationManager _serverConfigurationManager ;
private readonly IMediaEncoder _mediaEncoder ;
private readonly IDeviceManager _deviceManager ;
private readonly TranscodingJobHelper _transcodingJobHelper ;
2020-07-25 23:21:40 +00:00
private readonly IHttpClientFactory _httpClientFactory ;
2021-04-20 21:03:36 +00:00
private readonly EncodingHelper _encodingHelper ;
2020-07-24 22:49:43 +00:00
private readonly TranscodingJobType _transcodingJobType = TranscodingJobType . Progressive ;
2020-06-21 14:00:16 +00:00
/// <summary>
/// Initializes a new instance of the <see cref="VideosController"/> class.
/// </summary>
/// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
/// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
/// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
2020-07-24 22:49:43 +00:00
/// <param name="dlnaManager">Instance of the <see cref="IDlnaManager"/> interface.</param>
/// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
/// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
/// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
/// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
/// <param name="deviceManager">Instance of the <see cref="IDeviceManager"/> interface.</param>
/// <param name="transcodingJobHelper">Instance of the <see cref="TranscodingJobHelper"/> class.</param>
2020-07-25 23:21:40 +00:00
/// <param name="httpClientFactory">Instance of the <see cref="IHttpClientFactory"/> interface.</param>
2021-04-20 21:03:36 +00:00
/// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
2020-06-21 14:00:16 +00:00
public VideosController (
ILibraryManager libraryManager ,
IUserManager userManager ,
2020-07-24 22:49:43 +00:00
IDtoService dtoService ,
IDlnaManager dlnaManager ,
IAuthorizationContext authContext ,
IMediaSourceManager mediaSourceManager ,
IServerConfigurationManager serverConfigurationManager ,
IMediaEncoder mediaEncoder ,
IDeviceManager deviceManager ,
TranscodingJobHelper transcodingJobHelper ,
2021-04-20 21:03:36 +00:00
IHttpClientFactory httpClientFactory ,
EncodingHelper encodingHelper )
2020-06-21 14:00:16 +00:00
{
_libraryManager = libraryManager ;
_userManager = userManager ;
_dtoService = dtoService ;
2020-07-24 22:49:43 +00:00
_dlnaManager = dlnaManager ;
_authContext = authContext ;
_mediaSourceManager = mediaSourceManager ;
_serverConfigurationManager = serverConfigurationManager ;
_mediaEncoder = mediaEncoder ;
_deviceManager = deviceManager ;
_transcodingJobHelper = transcodingJobHelper ;
2020-07-25 23:21:40 +00:00
_httpClientFactory = httpClientFactory ;
2021-04-20 21:03:36 +00:00
_encodingHelper = encodingHelper ;
2020-06-21 14:00:16 +00:00
}
/// <summary>
/// Gets additional parts for a video.
/// </summary>
/// <param name="itemId">The item id.</param>
/// <param name="userId">Optional. Filter by user id, and attach user data.</param>
/// <response code="200">Additional parts returned.</response>
/// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the parts.</returns>
[HttpGet("{itemId}/AdditionalParts")]
2020-06-22 13:44:11 +00:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-21 14:00:16 +00:00
[ProducesResponseType(StatusCodes.Status200OK)]
2020-09-06 15:07:27 +00:00
public ActionResult < QueryResult < BaseItemDto > > GetAdditionalPart ( [ FromRoute , Required ] Guid itemId , [ FromQuery ] Guid ? userId )
2020-06-21 14:00:16 +00:00
{
2020-07-07 15:10:51 +00:00
var user = userId . HasValue & & ! userId . Equals ( Guid . Empty )
? _userManager . GetUserById ( userId . Value )
: null ;
2020-06-21 14:00:16 +00:00
var item = itemId . Equals ( Guid . Empty )
? ( ! userId . Equals ( Guid . Empty )
? _libraryManager . GetUserRootFolder ( )
: _libraryManager . RootFolder )
: _libraryManager . GetItemById ( itemId ) ;
var dtoOptions = new DtoOptions ( ) ;
dtoOptions = dtoOptions . AddClientFields ( Request ) ;
BaseItemDto [ ] items ;
if ( item is Video video )
{
items = video . GetAdditionalParts ( )
. Select ( i = > _dtoService . GetBaseItemDto ( i , dtoOptions , user , video ) )
. ToArray ( ) ;
}
else
{
items = Array . Empty < BaseItemDto > ( ) ;
}
2022-01-20 15:46:17 +00:00
var result = new QueryResult < BaseItemDto > ( items ) ;
2020-06-21 14:00:16 +00:00
return result ;
}
/// <summary>
/// Removes alternate video sources.
/// </summary>
/// <param name="itemId">The item id.</param>
/// <response code="204">Alternate sources deleted.</response>
/// <response code="404">Video not found.</response>
/// <returns>A <see cref="NoContentResult"/> indicating success, or a <see cref="NotFoundResult"/> if the video doesn't exist.</returns>
[HttpDelete("{itemId}/AlternateSources")]
[Authorize(Policy = Policies.RequiresElevation)]
2020-09-01 23:26:49 +00:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
2020-06-21 14:00:16 +00:00
[ProducesResponseType(StatusCodes.Status404NotFound)]
2020-09-06 15:07:27 +00:00
public async Task < ActionResult > DeleteAlternateSources ( [ FromRoute , Required ] Guid itemId )
2020-06-21 14:00:16 +00:00
{
var video = ( Video ) _libraryManager . GetItemById ( itemId ) ;
if ( video = = null )
{
return NotFound ( "The video either does not exist or the id does not belong to a video." ) ;
}
2020-08-08 19:21:32 +00:00
if ( video . LinkedAlternateVersions . Length = = 0 )
{
video = ( Video ) _libraryManager . GetItemById ( video . PrimaryVersionId ) ;
}
2020-06-21 14:00:16 +00:00
foreach ( var link in video . GetLinkedAlternateVersions ( ) )
{
link . SetPrimaryVersionId ( null ) ;
link . LinkedAlternateVersions = Array . Empty < LinkedChild > ( ) ;
2020-08-21 20:01:19 +00:00
await link . UpdateToRepositoryAsync ( ItemUpdateType . MetadataEdit , CancellationToken . None ) . ConfigureAwait ( false ) ;
2020-06-21 14:00:16 +00:00
}
video . LinkedAlternateVersions = Array . Empty < LinkedChild > ( ) ;
video . SetPrimaryVersionId ( null ) ;
2020-08-21 20:01:19 +00:00
await video . UpdateToRepositoryAsync ( ItemUpdateType . MetadataEdit , CancellationToken . None ) . ConfigureAwait ( false ) ;
2020-06-21 14:00:16 +00:00
return NoContent ( ) ;
}
/// <summary>
/// Merges videos into a single record.
/// </summary>
2020-12-05 12:54:19 +00:00
/// <param name="ids">Item id list. This allows multiple, comma delimited.</param>
2020-06-21 14:00:16 +00:00
/// <response code="204">Videos merged.</response>
/// <response code="400">Supply at least 2 video ids.</response>
/// <returns>A <see cref="NoContentResult"/> indicating success, or a <see cref="BadRequestResult"/> if less than two ids were supplied.</returns>
[HttpPost("MergeVersions")]
[Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
2020-12-05 12:54:19 +00:00
public async Task < ActionResult > MergeVersions ( [ FromQuery , Required , ModelBinder ( typeof ( CommaDelimitedArrayModelBinder ) ) ] Guid [ ] ids )
2020-06-21 14:00:16 +00:00
{
2020-12-05 12:54:19 +00:00
var items = ids
2020-06-21 14:00:16 +00:00
. Select ( i = > _libraryManager . GetItemById ( i ) )
. OfType < Video > ( )
. OrderBy ( i = > i . Id )
. ToList ( ) ;
if ( items . Count < 2 )
{
return BadRequest ( "Please supply at least two videos to merge." ) ;
}
2021-03-05 18:57:48 +00:00
var primaryVersion = items . FirstOrDefault ( i = > i . MediaSourceCount > 1 & & string . IsNullOrEmpty ( i . PrimaryVersionId ) ) ;
2020-06-21 14:00:16 +00:00
if ( primaryVersion = = null )
{
primaryVersion = items
. OrderBy ( i = >
{
if ( i . Video3DFormat . HasValue | | i . VideoType ! = VideoType . VideoFile )
{
return 1 ;
}
return 0 ;
} )
. ThenByDescending ( i = > i . GetDefaultVideoStream ( ) ? . Width ? ? 0 )
. First ( ) ;
}
2020-08-10 18:33:11 +00:00
var alternateVersionsOfPrimary = primaryVersion . LinkedAlternateVersions . ToList ( ) ;
2020-06-21 14:00:16 +00:00
foreach ( var item in items . Where ( i = > i . Id ! = primaryVersion . Id ) )
{
item . SetPrimaryVersionId ( primaryVersion . Id . ToString ( "N" , CultureInfo . InvariantCulture ) ) ;
2020-08-21 20:01:19 +00:00
await item . UpdateToRepositoryAsync ( ItemUpdateType . MetadataEdit , CancellationToken . None ) . ConfigureAwait ( false ) ;
2020-06-21 14:00:16 +00:00
2020-08-10 18:33:11 +00:00
if ( ! alternateVersionsOfPrimary . Any ( i = > string . Equals ( i . Path , item . Path , StringComparison . OrdinalIgnoreCase ) ) )
2020-06-21 14:00:16 +00:00
{
2020-08-10 18:33:11 +00:00
alternateVersionsOfPrimary . Add ( new LinkedChild
{
Path = item . Path ,
ItemId = item . Id
} ) ;
}
2020-06-21 14:00:16 +00:00
foreach ( var linkedItem in item . LinkedAlternateVersions )
{
2020-08-10 18:33:11 +00:00
if ( ! alternateVersionsOfPrimary . Any ( i = > string . Equals ( i . Path , linkedItem . Path , StringComparison . OrdinalIgnoreCase ) ) )
2020-06-21 14:00:16 +00:00
{
2020-08-10 18:33:11 +00:00
alternateVersionsOfPrimary . Add ( linkedItem ) ;
2020-06-21 14:00:16 +00:00
}
}
if ( item . LinkedAlternateVersions . Length > 0 )
{
item . LinkedAlternateVersions = Array . Empty < LinkedChild > ( ) ;
2020-08-21 20:01:19 +00:00
await item . UpdateToRepositoryAsync ( ItemUpdateType . MetadataEdit , CancellationToken . None ) . ConfigureAwait ( false ) ;
2020-06-21 14:00:16 +00:00
}
}
2020-08-10 18:33:11 +00:00
primaryVersion . LinkedAlternateVersions = alternateVersionsOfPrimary . ToArray ( ) ;
2020-08-21 20:01:19 +00:00
await primaryVersion . UpdateToRepositoryAsync ( ItemUpdateType . MetadataEdit , CancellationToken . None ) . ConfigureAwait ( false ) ;
2020-06-21 14:00:16 +00:00
return NoContent ( ) ;
}
2020-07-24 22:49:43 +00:00
/// <summary>
/// Gets a video stream.
/// </summary>
/// <param name="itemId">The item id.</param>
/// <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>
/// <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>
/// <param name="params">The streaming parameters.</param>
/// <param name="tag">The tag.</param>
/// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
/// <param name="playSessionId">The play session id.</param>
/// <param name="segmentContainer">The segment container.</param>
2020-11-18 13:23:45 +00:00
/// <param name="segmentLength">The segment length.</param>
2020-07-24 22:49:43 +00:00
/// <param name="minSegments">The minimum number of segments.</param>
/// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
/// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
/// <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>
/// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
/// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
/// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
/// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
/// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
/// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
/// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
/// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
/// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
/// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
/// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
/// <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>
/// <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>
/// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
/// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
/// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
/// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
2021-07-08 18:53:56 +00:00
/// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
/// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
2020-07-24 22:49:43 +00:00
/// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
/// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
/// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
/// <param name="maxRefFrames">Optional.</param>
/// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
/// <param name="requireAvc">Optional. Whether to require avc.</param>
/// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
2020-11-18 13:23:45 +00:00
/// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
2020-07-24 22:49:43 +00:00
/// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
/// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
/// <param name="liveStreamId">The live stream id.</param>
/// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
2021-08-20 18:22:21 +00:00
/// <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>
2020-07-24 22:49:43 +00:00
/// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
2020-11-30 10:36:11 +00:00
/// <param name="transcodeReasons">Optional. The transcoding reason.</param>
2020-07-24 22:49:43 +00:00
/// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
/// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
/// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
/// <param name="streamOptions">Optional. The streaming options.</param>
2020-07-31 15:21:33 +00:00
/// <response code="200">Video stream returned.</response>
2020-07-24 22:49:43 +00:00
/// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
[HttpGet("{itemId}/stream")]
2020-08-03 20:38:51 +00:00
[HttpHead("{itemId}/stream", Name = "HeadVideoStream")]
2020-07-24 22:49:43 +00:00
[ProducesResponseType(StatusCodes.Status200OK)]
2020-09-01 23:26:49 +00:00
[ProducesVideoFile]
2020-07-24 22:49:43 +00:00
public async Task < ActionResult > GetVideoStream (
2020-09-06 15:07:27 +00:00
[FromRoute, Required] Guid itemId ,
2020-11-15 17:58:39 +00:00
[FromQuery] string? container ,
2020-07-24 22:49:43 +00:00
[FromQuery] bool? @static ,
[FromQuery] string? @params ,
[FromQuery] string? tag ,
[FromQuery] string? deviceProfileId ,
[FromQuery] string? playSessionId ,
[FromQuery] string? segmentContainer ,
[FromQuery] int? segmentLength ,
[FromQuery] int? minSegments ,
[FromQuery] string? mediaSourceId ,
[FromQuery] string? deviceId ,
[FromQuery] string? audioCodec ,
[FromQuery] bool? enableAutoStreamCopy ,
[FromQuery] bool? allowVideoStreamCopy ,
[FromQuery] bool? allowAudioStreamCopy ,
[FromQuery] bool? breakOnNonKeyFrames ,
[FromQuery] int? audioSampleRate ,
[FromQuery] int? maxAudioBitDepth ,
[FromQuery] int? audioBitRate ,
[FromQuery] int? audioChannels ,
[FromQuery] int? maxAudioChannels ,
[FromQuery] string? profile ,
[FromQuery] string? level ,
[FromQuery] float? framerate ,
[FromQuery] float? maxFramerate ,
[FromQuery] bool? copyTimestamps ,
[FromQuery] long? startTimeTicks ,
[FromQuery] int? width ,
[FromQuery] int? height ,
2021-07-08 18:53:56 +00:00
[FromQuery] int? maxWidth ,
[FromQuery] int? maxHeight ,
2020-07-24 22:49:43 +00:00
[FromQuery] int? videoBitRate ,
[FromQuery] int? subtitleStreamIndex ,
2021-03-05 01:25:52 +00:00
[FromQuery] SubtitleDeliveryMethod ? subtitleMethod ,
2020-07-24 22:49:43 +00:00
[FromQuery] int? maxRefFrames ,
[FromQuery] int? maxVideoBitDepth ,
[FromQuery] bool? requireAvc ,
[FromQuery] bool? deInterlace ,
[FromQuery] bool? requireNonAnamorphic ,
[FromQuery] int? transcodingMaxAudioChannels ,
[FromQuery] int? cpuCoreLimit ,
[FromQuery] string? liveStreamId ,
[FromQuery] bool? enableMpegtsM2TsMode ,
[FromQuery] string? videoCodec ,
[FromQuery] string? subtitleCodec ,
2020-11-30 10:36:11 +00:00
[FromQuery] string? transcodeReasons ,
2020-07-24 22:49:43 +00:00
[FromQuery] int? audioStreamIndex ,
[FromQuery] int? videoStreamIndex ,
2021-03-05 01:25:52 +00:00
[FromQuery] EncodingContext ? context ,
2020-07-24 22:49:43 +00:00
[FromQuery] Dictionary < string , string > streamOptions )
{
var isHeadRequest = Request . Method = = System . Net . WebRequestMethods . Http . Head ;
2021-06-04 12:36:58 +00:00
// CTS lifecycle is managed internally.
2020-07-27 19:42:40 +00:00
var cancellationTokenSource = new CancellationTokenSource ( ) ;
2020-07-30 12:29:06 +00:00
var streamingRequest = new VideoRequestDto
2020-07-24 22:49:43 +00:00
{
Id = itemId ,
Container = container ,
2021-03-22 19:53:55 +00:00
Static = @static ? ? false ,
2020-07-24 22:49:43 +00:00
Params = @params ,
Tag = tag ,
DeviceProfileId = deviceProfileId ,
PlaySessionId = playSessionId ,
SegmentContainer = segmentContainer ,
SegmentLength = segmentLength ,
MinSegments = minSegments ,
MediaSourceId = mediaSourceId ,
DeviceId = deviceId ,
AudioCodec = audioCodec ,
EnableAutoStreamCopy = enableAutoStreamCopy ? ? true ,
AllowAudioStreamCopy = allowAudioStreamCopy ? ? true ,
AllowVideoStreamCopy = allowVideoStreamCopy ? ? true ,
BreakOnNonKeyFrames = breakOnNonKeyFrames ? ? false ,
AudioSampleRate = audioSampleRate ,
MaxAudioChannels = maxAudioChannels ,
AudioBitRate = audioBitRate ,
MaxAudioBitDepth = maxAudioBitDepth ,
AudioChannels = audioChannels ,
Profile = profile ,
Level = level ,
Framerate = framerate ,
MaxFramerate = maxFramerate ,
2021-03-22 19:53:55 +00:00
CopyTimestamps = copyTimestamps ? ? false ,
2020-07-24 22:49:43 +00:00
StartTimeTicks = startTimeTicks ,
Width = width ,
Height = height ,
2021-07-08 18:53:56 +00:00
MaxWidth = maxWidth ,
MaxHeight = maxHeight ,
2020-07-24 22:49:43 +00:00
VideoBitRate = videoBitRate ,
SubtitleStreamIndex = subtitleStreamIndex ,
2021-03-05 01:25:52 +00:00
SubtitleMethod = subtitleMethod ? ? SubtitleDeliveryMethod . Encode ,
2020-07-24 22:49:43 +00:00
MaxRefFrames = maxRefFrames ,
MaxVideoBitDepth = maxVideoBitDepth ,
2021-03-22 19:53:55 +00:00
RequireAvc = requireAvc ? ? false ,
DeInterlace = deInterlace ? ? false ,
RequireNonAnamorphic = requireNonAnamorphic ? ? false ,
2020-07-24 22:49:43 +00:00
TranscodingMaxAudioChannels = transcodingMaxAudioChannels ,
CpuCoreLimit = cpuCoreLimit ,
LiveStreamId = liveStreamId ,
2021-03-22 19:53:55 +00:00
EnableMpegtsM2TsMode = enableMpegtsM2TsMode ? ? false ,
2020-07-24 22:49:43 +00:00
VideoCodec = videoCodec ,
SubtitleCodec = subtitleCodec ,
2020-11-30 10:36:11 +00:00
TranscodeReasons = transcodeReasons ,
2020-07-24 22:49:43 +00:00
AudioStreamIndex = audioStreamIndex ,
VideoStreamIndex = videoStreamIndex ,
2021-03-05 01:25:52 +00:00
Context = context ? ? EncodingContext . Streaming ,
2020-07-24 22:49:43 +00:00
StreamOptions = streamOptions
} ;
using var state = await StreamingHelpers . GetStreamingState (
streamingRequest ,
Request ,
_authContext ,
_mediaSourceManager ,
_userManager ,
_libraryManager ,
_serverConfigurationManager ,
_mediaEncoder ,
2021-04-20 21:03:36 +00:00
_encodingHelper ,
2020-07-24 22:49:43 +00:00
_dlnaManager ,
_deviceManager ,
_transcodingJobHelper ,
_transcodingJobType ,
cancellationTokenSource . Token )
. ConfigureAwait ( false ) ;
if ( @static . HasValue & & @static . Value & & state . DirectStreamProvider ! = null )
{
2021-11-15 13:33:50 +00:00
StreamingHelpers . AddDlnaHeaders ( state , Response . Headers , true , state . Request . StartTimeTicks , Request , _dlnaManager ) ;
2020-07-24 22:49:43 +00:00
2021-09-10 07:29:14 +00:00
var liveStreamInfo = _mediaSourceManager . GetLiveStreamInfo ( streamingRequest . LiveStreamId ) ;
2021-09-10 09:54:26 +00:00
if ( liveStreamInfo = = null )
{
return NotFound ( ) ;
}
2021-09-10 11:09:24 +00:00
2021-09-10 08:03:42 +00:00
var liveStream = new ProgressiveFileStream ( liveStreamInfo . GetStream ( ) ) ;
2020-07-24 22:49:43 +00:00
// TODO (moved from MediaBrowser.Api): Don't hardcode contentType
2021-10-03 03:43:05 +00:00
return File ( liveStream , MimeTypes . GetMimeType ( "file.ts" ) ) ;
2020-07-24 22:49:43 +00:00
}
// Static remote stream
if ( @static . HasValue & & @static . Value & & state . InputProtocol = = MediaProtocol . Http )
{
2021-11-15 13:33:50 +00:00
StreamingHelpers . AddDlnaHeaders ( state , Response . Headers , true , state . Request . StartTimeTicks , Request , _dlnaManager ) ;
2020-07-24 22:49:43 +00:00
2020-08-31 17:05:21 +00:00
var httpClient = _httpClientFactory . CreateClient ( NamedClient . Default ) ;
2020-08-17 21:54:51 +00:00
return await FileStreamResponseHelpers . GetStaticRemoteStreamResult ( state , isHeadRequest , httpClient , HttpContext ) . ConfigureAwait ( false ) ;
2020-07-24 22:49:43 +00:00
}
if ( @static . HasValue & & @static . Value & & state . InputProtocol ! = MediaProtocol . File )
{
return BadRequest ( $"Input protocol {state.InputProtocol} cannot be streamed statically" ) ;
}
var outputPath = state . OutputFilePath ;
var outputPathExists = System . IO . File . Exists ( outputPath ) ;
var transcodingJob = _transcodingJobHelper . GetTranscodingJob ( outputPath , TranscodingJobType . Progressive ) ;
var isTranscodeCached = outputPathExists & & transcodingJob ! = null ;
2021-11-15 13:33:50 +00:00
StreamingHelpers . AddDlnaHeaders ( state , Response . Headers , ( @static . HasValue & & @static . Value ) | | isTranscodeCached , state . Request . StartTimeTicks , Request , _dlnaManager ) ;
2020-07-24 22:49:43 +00:00
// Static stream
if ( @static . HasValue & & @static . Value )
{
var contentType = state . GetMimeType ( "." + state . OutputContainer , false ) ? ? state . GetMimeType ( state . MediaPath ) ;
if ( state . MediaSource . IsInfiniteStream )
{
2021-09-10 07:29:14 +00:00
var liveStream = new ProgressiveFileStream ( state . MediaPath , null , _transcodingJobHelper ) ;
return File ( liveStream , contentType ) ;
2020-07-24 22:49:43 +00:00
}
return FileStreamResponseHelpers . GetStaticFileResult (
state . MediaPath ,
contentType ,
isHeadRequest ,
2020-08-10 13:53:32 +00:00
HttpContext ) ;
2020-07-24 22:49:43 +00:00
}
// Need to start ffmpeg (because media can't be returned directly)
var encodingOptions = _serverConfigurationManager . GetEncodingOptions ( ) ;
2021-04-20 21:03:36 +00:00
var ffmpegCommandLineArguments = _encodingHelper . GetProgressiveVideoFullCommandLine ( state , encodingOptions , outputPath , "superfast" ) ;
2020-07-24 22:49:43 +00:00
return await FileStreamResponseHelpers . GetTranscodedFile (
state ,
isHeadRequest ,
2020-08-10 13:53:32 +00:00
HttpContext ,
2020-07-24 22:49:43 +00:00
_transcodingJobHelper ,
ffmpegCommandLineArguments ,
_transcodingJobType ,
cancellationTokenSource ) . ConfigureAwait ( false ) ;
}
2020-11-15 17:58:39 +00:00
/// <summary>
/// Gets a video stream.
/// </summary>
/// <param name="itemId">The item id.</param>
/// <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>
/// <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>
/// <param name="params">The streaming parameters.</param>
/// <param name="tag">The tag.</param>
/// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
/// <param name="playSessionId">The play session id.</param>
/// <param name="segmentContainer">The segment container.</param>
2021-04-30 13:07:27 +00:00
/// <param name="segmentLength">The segment length.</param>
2020-11-15 17:58:39 +00:00
/// <param name="minSegments">The minimum number of segments.</param>
/// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
/// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
/// <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>
/// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param>
/// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
/// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
/// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
/// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
/// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
/// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
/// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
/// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param>
/// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param>
/// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
/// <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>
/// <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>
/// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param>
/// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
/// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
/// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
2021-07-08 18:53:56 +00:00
/// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
/// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
2020-11-15 17:58:39 +00:00
/// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param>
/// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param>
/// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
/// <param name="maxRefFrames">Optional.</param>
/// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
/// <param name="requireAvc">Optional. Whether to require avc.</param>
/// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
2021-04-30 13:07:27 +00:00
/// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
2020-11-15 17:58:39 +00:00
/// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
/// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
/// <param name="liveStreamId">The live stream id.</param>
/// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
2021-08-20 18:22:21 +00:00
/// <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>
2020-11-15 17:58:39 +00:00
/// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
2020-11-30 10:36:11 +00:00
/// <param name="transcodeReasons">Optional. The transcoding reason.</param>
2020-11-15 17:58:39 +00:00
/// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param>
/// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param>
/// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
/// <param name="streamOptions">Optional. The streaming options.</param>
/// <response code="200">Video stream returned.</response>
/// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
2021-04-30 13:07:27 +00:00
[HttpGet("{itemId}/stream.{container}")]
[HttpHead("{itemId}/stream.{container}", Name = "HeadVideoStreamByContainer")]
2020-11-15 17:58:39 +00:00
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesVideoFile]
public Task < ActionResult > GetVideoStreamByContainer (
[FromRoute, Required] Guid itemId ,
[FromRoute, Required] string container ,
[FromQuery] bool? @static ,
[FromQuery] string? @params ,
[FromQuery] string? tag ,
[FromQuery] string? deviceProfileId ,
[FromQuery] string? playSessionId ,
[FromQuery] string? segmentContainer ,
[FromQuery] int? segmentLength ,
[FromQuery] int? minSegments ,
[FromQuery] string? mediaSourceId ,
[FromQuery] string? deviceId ,
[FromQuery] string? audioCodec ,
[FromQuery] bool? enableAutoStreamCopy ,
[FromQuery] bool? allowVideoStreamCopy ,
[FromQuery] bool? allowAudioStreamCopy ,
[FromQuery] bool? breakOnNonKeyFrames ,
[FromQuery] int? audioSampleRate ,
[FromQuery] int? maxAudioBitDepth ,
[FromQuery] int? audioBitRate ,
[FromQuery] int? audioChannels ,
[FromQuery] int? maxAudioChannels ,
[FromQuery] string? profile ,
[FromQuery] string? level ,
[FromQuery] float? framerate ,
[FromQuery] float? maxFramerate ,
[FromQuery] bool? copyTimestamps ,
[FromQuery] long? startTimeTicks ,
[FromQuery] int? width ,
[FromQuery] int? height ,
2021-07-08 18:53:56 +00:00
[FromQuery] int? maxWidth ,
[FromQuery] int? maxHeight ,
2020-11-15 17:58:39 +00:00
[FromQuery] int? videoBitRate ,
[FromQuery] int? subtitleStreamIndex ,
2021-03-05 01:25:52 +00:00
[FromQuery] SubtitleDeliveryMethod ? subtitleMethod ,
2020-11-15 17:58:39 +00:00
[FromQuery] int? maxRefFrames ,
[FromQuery] int? maxVideoBitDepth ,
[FromQuery] bool? requireAvc ,
[FromQuery] bool? deInterlace ,
[FromQuery] bool? requireNonAnamorphic ,
[FromQuery] int? transcodingMaxAudioChannels ,
[FromQuery] int? cpuCoreLimit ,
[FromQuery] string? liveStreamId ,
[FromQuery] bool? enableMpegtsM2TsMode ,
[FromQuery] string? videoCodec ,
[FromQuery] string? subtitleCodec ,
2020-11-30 10:36:11 +00:00
[FromQuery] string? transcodeReasons ,
2020-11-15 17:58:39 +00:00
[FromQuery] int? audioStreamIndex ,
[FromQuery] int? videoStreamIndex ,
2021-03-05 01:25:52 +00:00
[FromQuery] EncodingContext ? context ,
2020-11-15 17:58:39 +00:00
[FromQuery] Dictionary < string , string > streamOptions )
{
return GetVideoStream (
itemId ,
container ,
@static ,
@params ,
tag ,
deviceProfileId ,
playSessionId ,
segmentContainer ,
segmentLength ,
minSegments ,
mediaSourceId ,
deviceId ,
audioCodec ,
enableAutoStreamCopy ,
allowVideoStreamCopy ,
allowAudioStreamCopy ,
breakOnNonKeyFrames ,
audioSampleRate ,
maxAudioBitDepth ,
audioBitRate ,
audioChannels ,
maxAudioChannels ,
profile ,
level ,
framerate ,
maxFramerate ,
copyTimestamps ,
startTimeTicks ,
width ,
height ,
2021-07-08 18:53:56 +00:00
maxWidth ,
maxHeight ,
2020-11-15 17:58:39 +00:00
videoBitRate ,
subtitleStreamIndex ,
subtitleMethod ,
maxRefFrames ,
maxVideoBitDepth ,
requireAvc ,
deInterlace ,
requireNonAnamorphic ,
transcodingMaxAudioChannels ,
cpuCoreLimit ,
liveStreamId ,
enableMpegtsM2TsMode ,
videoCodec ,
subtitleCodec ,
2020-11-30 10:36:11 +00:00
transcodeReasons ,
2020-11-15 17:58:39 +00:00
audioStreamIndex ,
videoStreamIndex ,
context ,
streamOptions ) ;
}
2020-06-21 14:00:16 +00:00
}
}