2021-05-07 00:39:20 +02:00
#nullable disable
2020-08-22 21:56:24 +02:00
#pragma warning disable CS1591
2019-01-06 21:50:43 +01:00
using System ;
2018-12-28 00:27:57 +01:00
using System.Collections.Generic ;
using System.Globalization ;
using System.IO ;
using System.Linq ;
2019-09-01 18:39:23 +02:00
using System.Text ;
2020-11-07 18:39:32 +01:00
using System.Text.RegularExpressions ;
2019-01-13 02:06:59 +01:00
using System.Threading ;
2020-05-13 04:10:35 +02:00
using Jellyfin.Data.Enums ;
2022-01-08 15:31:45 +01:00
using Jellyfin.Extensions ;
2022-02-06 14:02:01 +01:00
using MediaBrowser.Common.Configuration ;
2022-06-06 17:29:39 +02:00
using MediaBrowser.Controller.Extensions ;
2018-12-28 00:27:57 +01:00
using MediaBrowser.Model.Configuration ;
using MediaBrowser.Model.Dlna ;
using MediaBrowser.Model.Dto ;
using MediaBrowser.Model.Entities ;
using MediaBrowser.Model.MediaInfo ;
2022-06-06 17:29:39 +02:00
using Microsoft.Extensions.Configuration ;
2018-12-28 00:27:57 +01:00
namespace MediaBrowser.Controller.MediaEncoding
{
2023-05-22 22:48:09 +02:00
public partial class EncodingHelper
2018-12-28 00:27:57 +01:00
{
2021-12-24 22:18:24 +01:00
private const string QsvAlias = "qs" ;
private const string VaapiAlias = "va" ;
private const string D3d11vaAlias = "dx11" ;
private const string VideotoolboxAlias = "vt" ;
private const string OpenclAlias = "ocl" ;
private const string CudaAlias = "cu" ;
2022-10-16 17:08:59 +02:00
private const string DrmAlias = "dr" ;
private const string VulkanAlias = "vk" ;
2022-02-06 14:02:01 +01:00
private readonly IApplicationPaths _appPaths ;
2018-12-28 00:27:57 +01:00
private readonly IMediaEncoder _mediaEncoder ;
private readonly ISubtitleEncoder _subtitleEncoder ;
2022-06-06 17:29:39 +02:00
private readonly IConfiguration _config ;
2022-10-16 17:08:59 +02:00
private readonly Version _minKernelVersionAmdVkFmtModifier = new Version ( 5 , 15 ) ;
2023-01-22 20:05:00 +01:00
// i915 hang was fixed by linux 6.2 (3f882f2)
private readonly Version _minKerneli915Hang = new Version ( 5 , 18 ) ;
private readonly Version _maxKerneli915Hang = new Version ( 6 , 1 , 3 ) ;
private readonly Version _minFixedKernel60i915Hang = new Version ( 6 , 0 , 18 ) ;
2019-09-01 18:39:23 +02:00
2023-03-10 01:38:15 +01:00
private readonly Version _minFFmpegImplictHwaccel = new Version ( 6 , 0 ) ;
private readonly Version _minFFmpegHwaUnsafeOutput = new Version ( 6 , 0 ) ;
2023-06-13 16:53:35 +02:00
private readonly Version _minFFmpegOclCuTonemapMode = new Version ( 5 , 1 , 3 ) ;
2023-06-19 21:49:26 +02:00
private readonly Version _minFFmpegSvtAv1Params = new Version ( 5 , 1 ) ;
2023-03-10 01:38:15 +01:00
2021-12-01 17:49:50 +01:00
private static readonly string [ ] _videoProfilesH264 = new [ ]
2019-09-01 18:39:23 +02:00
{
"ConstrainedBaseline" ,
"Baseline" ,
"Extended" ,
"Main" ,
"High" ,
"ProgressiveHigh" ,
2021-12-01 17:49:50 +01:00
"ConstrainedHigh" ,
"High10"
2019-09-01 18:39:23 +02:00
} ;
2018-12-28 00:27:57 +01:00
2021-12-01 17:49:50 +01:00
private static readonly string [ ] _videoProfilesH265 = new [ ]
{
"Main" ,
"Main10"
} ;
2023-06-19 21:49:26 +02:00
private static readonly string [ ] _videoProfilesAv1 = new [ ]
{
"Main" ,
"High" ,
"Professional" ,
} ;
2023-02-04 19:52:35 +01:00
private static readonly HashSet < string > _mp4ContainerNames = new ( StringComparer . OrdinalIgnoreCase )
{
"mp4" ,
"m4a" ,
"m4p" ,
"m4b" ,
"m4r" ,
"m4v" ,
} ;
2023-02-24 16:06:19 +01:00
// Set max transcoding channels for encoders that can't handle more than a set amount of channels
// AAC, FLAC, ALAC, libopus, libvorbis encoders all support at least 8 channels
private static readonly Dictionary < string , int > _audioTranscodeChannelLookup = new ( StringComparer . OrdinalIgnoreCase )
{
{ "wmav2" , 2 } ,
{ "libmp3lame" , 2 } ,
{ "libfdk_aac" , 6 } ,
{ "aac_at" , 6 } ,
{ "ac3" , 6 } ,
{ "eac3" , 6 } ,
2023-02-24 16:53:08 +01:00
{ "dca" , 6 } ,
2023-02-24 16:06:19 +01:00
{ "mlp" , 6 } ,
{ "truehd" , 6 } ,
} ;
2023-03-02 20:57:59 +01:00
public static readonly string [ ] LosslessAudioCodecs = new string [ ]
{
"alac" ,
"ape" ,
"flac" ,
"mlp" ,
"truehd" ,
"wavpack"
} ;
2019-10-26 22:53:53 +02:00
public EncodingHelper (
2022-02-06 14:02:01 +01:00
IApplicationPaths appPaths ,
2019-10-26 22:53:53 +02:00
IMediaEncoder mediaEncoder ,
2022-06-06 17:29:39 +02:00
ISubtitleEncoder subtitleEncoder ,
IConfiguration config )
2018-12-28 00:27:57 +01:00
{
2022-02-06 14:02:01 +01:00
_appPaths = appPaths ;
2018-12-28 00:27:57 +01:00
_mediaEncoder = mediaEncoder ;
_subtitleEncoder = subtitleEncoder ;
2022-06-06 17:29:39 +02:00
_config = config ;
2018-12-28 00:27:57 +01:00
}
2023-05-22 22:48:09 +02:00
[GeneratedRegex(@"\s+")]
private static partial Regex WhiteSpaceRegex ( ) ;
2018-12-28 00:27:57 +01:00
public string GetH264Encoder ( EncodingJobInfo state , EncodingOptions encodingOptions )
2023-06-19 21:49:26 +02:00
= > GetH26xOrAv1Encoder ( "libx264" , "h264" , state , encodingOptions ) ;
2018-12-28 00:27:57 +01:00
2019-06-02 00:03:48 +02:00
public string GetH265Encoder ( EncodingJobInfo state , EncodingOptions encodingOptions )
2023-06-19 21:49:26 +02:00
= > GetH26xOrAv1Encoder ( "libx265" , "hevc" , state , encodingOptions ) ;
public string GetAv1Encoder ( EncodingJobInfo state , EncodingOptions encodingOptions )
= > GetH26xOrAv1Encoder ( "libsvtav1" , "av1" , state , encodingOptions ) ;
2019-06-02 00:03:48 +02:00
2023-06-19 21:49:26 +02:00
private string GetH26xOrAv1Encoder ( string defaultEncoder , string hwEncoder , EncodingJobInfo state , EncodingOptions encodingOptions )
2019-06-02 00:03:48 +02:00
{
2018-12-28 00:27:57 +01:00
// Only use alternative encoders for video files.
// When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
2020-11-13 21:06:24 +01:00
// Since transcoding of folder rips is experimental anyway, it's not worth adding additional variables such as this.
2018-12-28 00:27:57 +01:00
if ( state . VideoType = = VideoType . VideoFile )
{
var hwType = encodingOptions . HardwareAccelerationType ;
2019-01-13 02:06:59 +01:00
var codecMap = new Dictionary < string , string > ( StringComparer . OrdinalIgnoreCase )
2018-12-28 00:27:57 +01:00
{
2020-10-12 19:22:33 +02:00
{ "amf" , hwEncoder + "_amf" } ,
2021-12-01 17:49:50 +01:00
{ "nvenc" , hwEncoder + "_nvenc" } ,
{ "qsv" , hwEncoder + "_qsv" } ,
2020-10-12 19:22:33 +02:00
{ "vaapi" , hwEncoder + "_vaapi" } ,
2021-12-01 17:49:50 +01:00
{ "videotoolbox" , hwEncoder + "_videotoolbox" } ,
{ "v4l2m2m" , hwEncoder + "_v4l2m2m" } ,
2019-01-13 02:06:59 +01:00
} ;
2018-12-28 00:27:57 +01:00
2019-01-13 02:06:59 +01:00
if ( ! string . IsNullOrEmpty ( hwType )
2019-09-01 18:39:23 +02:00
& & encodingOptions . EnableHardwareEncoding
2023-04-06 18:38:23 +02:00
& & codecMap . TryGetValue ( hwType , out var preferredEncoder )
& & _mediaEncoder . SupportsEncoder ( preferredEncoder ) )
2018-12-28 00:27:57 +01:00
{
2023-04-06 18:38:23 +02:00
return preferredEncoder ;
2018-12-28 00:27:57 +01:00
}
}
return defaultEncoder ;
}
private bool IsVaapiSupported ( EncodingJobInfo state )
{
2019-09-01 18:39:23 +02:00
// vaapi will throw an error with this input
// [vaapi @ 0x7faed8000960] No VAAPI support for codec mpeg4 profile -99.
2021-12-01 17:49:50 +01:00
if ( string . Equals ( state . VideoStream ? . Codec , "mpeg4" , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
return false ;
2018-12-28 00:27:57 +01:00
}
2019-09-01 18:39:23 +02:00
2020-05-26 00:12:54 +02:00
return _mediaEncoder . SupportsHwaccel ( "vaapi" ) ;
2018-12-28 00:27:57 +01:00
}
2021-12-01 17:49:50 +01:00
private bool IsVaapiFullSupported ( )
2021-01-24 20:40:34 +01:00
{
2023-06-12 19:13:48 +02:00
return _mediaEncoder . SupportsHwaccel ( "drm" )
& & _mediaEncoder . SupportsHwaccel ( "vaapi" )
2021-12-01 17:49:50 +01:00
& & _mediaEncoder . SupportsFilter ( "scale_vaapi" )
& & _mediaEncoder . SupportsFilter ( "deinterlace_vaapi" )
& & _mediaEncoder . SupportsFilter ( "tonemap_vaapi" )
2022-06-17 18:01:37 +02:00
& & _mediaEncoder . SupportsFilter ( "procamp_vaapi" )
2021-12-01 17:49:50 +01:00
& & _mediaEncoder . SupportsFilterWithOption ( FilterOptionType . OverlayVaapiFrameSync )
& & _mediaEncoder . SupportsFilter ( "hwupload_vaapi" ) ;
2021-01-24 20:40:34 +01:00
}
2021-12-01 17:49:50 +01:00
private bool IsOpenclFullSupported ( )
2020-11-24 15:09:13 +01:00
{
2021-12-01 17:49:50 +01:00
return _mediaEncoder . SupportsHwaccel ( "opencl" )
& & _mediaEncoder . SupportsFilter ( "scale_opencl" )
& & _mediaEncoder . SupportsFilterWithOption ( FilterOptionType . TonemapOpenclBt2390 )
& & _mediaEncoder . SupportsFilterWithOption ( FilterOptionType . OverlayOpenclFrameSync ) ;
}
2021-07-24 18:52:16 +02:00
2021-12-01 17:49:50 +01:00
private bool IsCudaFullSupported ( )
{
return _mediaEncoder . SupportsHwaccel ( "cuda" )
& & _mediaEncoder . SupportsFilterWithOption ( FilterOptionType . ScaleCudaFormat )
& & _mediaEncoder . SupportsFilter ( "yadif_cuda" )
& & _mediaEncoder . SupportsFilterWithOption ( FilterOptionType . TonemapCudaName )
& & _mediaEncoder . SupportsFilter ( "overlay_cuda" )
& & _mediaEncoder . SupportsFilter ( "hwupload_cuda" ) ;
2021-07-24 18:52:16 +02:00
}
2022-10-16 17:08:59 +02:00
private bool IsVulkanFullSupported ( )
{
return _mediaEncoder . SupportsHwaccel ( "vulkan" )
& & _mediaEncoder . SupportsFilter ( "libplacebo" )
& & _mediaEncoder . SupportsFilter ( "scale_vulkan" )
& & _mediaEncoder . SupportsFilterWithOption ( FilterOptionType . OverlayVulkanFrameSync ) ;
}
2021-12-01 17:49:50 +01:00
private bool IsHwTonemapAvailable ( EncodingJobInfo state , EncodingOptions options )
2021-07-24 18:52:16 +02:00
{
2022-12-05 15:00:20 +01:00
if ( state . VideoStream is null
2022-06-06 17:29:39 +02:00
| | ! options . EnableTonemapping
| | GetVideoColorBitDepth ( state ) ! = 10 )
2021-07-24 18:52:16 +02:00
{
return false ;
}
2022-06-27 02:55:36 +02:00
if ( string . Equals ( state . VideoStream . Codec , "hevc" , StringComparison . OrdinalIgnoreCase )
2023-06-15 13:28:01 +02:00
& & state . VideoStream . VideoRange = = VideoRange . HDR
& & state . VideoStream . VideoRangeType = = VideoRangeType . DOVI )
2022-06-06 17:29:39 +02:00
{
// Only native SW decoder and HW accelerator can parse dovi rpu.
var vidDecoder = GetHardwareVideoDecoder ( state , options ) ? ? string . Empty ;
var isSwDecoder = string . IsNullOrEmpty ( vidDecoder ) ;
var isNvdecDecoder = vidDecoder . Contains ( "cuda" , StringComparison . OrdinalIgnoreCase ) ;
var isVaapiDecoder = vidDecoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
var isD3d11vaDecoder = vidDecoder . Contains ( "d3d11va" , StringComparison . OrdinalIgnoreCase ) ;
return isSwDecoder | | isNvdecDecoder | | isVaapiDecoder | | isD3d11vaDecoder ;
}
2023-06-15 13:28:01 +02:00
return state . VideoStream . VideoRange = = VideoRange . HDR
& & ( state . VideoStream . VideoRangeType = = VideoRangeType . HDR10
| | state . VideoStream . VideoRangeType = = VideoRangeType . HLG ) ;
2020-11-24 15:09:13 +01:00
}
2022-10-16 17:08:59 +02:00
private bool IsVulkanHwTonemapAvailable ( EncodingJobInfo state , EncodingOptions options )
{
2022-12-05 15:00:20 +01:00
if ( state . VideoStream is null )
2022-10-16 17:08:59 +02:00
{
return false ;
}
// libplacebo has partial Dolby Vision to SDR tonemapping support.
return options . EnableTonemapping
2023-06-15 13:28:01 +02:00
& & state . VideoStream . VideoRange = = VideoRange . HDR
2022-10-16 17:08:59 +02:00
& & GetVideoColorBitDepth ( state ) = = 10 ;
}
2021-12-01 17:49:50 +01:00
private bool IsVaapiVppTonemapAvailable ( EncodingJobInfo state , EncodingOptions options )
2021-01-25 20:45:56 +01:00
{
2022-12-05 15:00:20 +01:00
if ( state . VideoStream is null
2022-06-27 02:55:36 +02:00
| | ! options . EnableVppTonemapping
| | GetVideoColorBitDepth ( state ) ! = 10 )
2021-02-17 03:14:17 +01:00
{
return false ;
}
2021-01-29 10:53:42 +01:00
// Native VPP tonemapping may come to QSV in the future.
2021-12-01 17:49:50 +01:00
2023-06-15 13:28:01 +02:00
return state . VideoStream . VideoRange = = VideoRange . HDR
& & state . VideoStream . VideoRangeType = = VideoRangeType . HDR10 ;
2021-01-25 20:45:56 +01:00
}
2018-12-28 00:27:57 +01:00
/// <summary>
2020-06-16 00:37:52 +02:00
/// Gets the name of the output video codec.
2018-12-28 00:27:57 +01:00
/// </summary>
2022-08-15 12:48:34 +02:00
/// <param name="state">Encoding state.</param>
2021-08-10 23:29:48 +02:00
/// <param name="encodingOptions">Encoding options.</param>
/// <returns>Encoder string.</returns>
2018-12-28 00:27:57 +01:00
public string GetVideoEncoder ( EncodingJobInfo state , EncodingOptions encodingOptions )
{
var codec = state . OutputVideoCodec ;
if ( ! string . IsNullOrEmpty ( codec ) )
{
2023-06-19 21:49:26 +02:00
if ( string . Equals ( codec , "av1" , StringComparison . OrdinalIgnoreCase ) )
{
return GetAv1Encoder ( state , encodingOptions ) ;
}
2019-09-01 18:39:23 +02:00
if ( string . Equals ( codec , "h265" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( codec , "hevc" , StringComparison . OrdinalIgnoreCase ) )
2019-06-02 00:03:48 +02:00
{
return GetH265Encoder ( state , encodingOptions ) ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( codec , "h264" , StringComparison . OrdinalIgnoreCase ) )
{
return GetH264Encoder ( state , encodingOptions ) ;
}
2019-09-01 18:39:23 +02:00
2021-08-20 20:22:21 +02:00
if ( string . Equals ( codec , "vp8" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( codec , "vpx" , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
return "libvpx" ;
}
2019-09-01 18:39:23 +02:00
2021-08-20 20:22:21 +02:00
if ( string . Equals ( codec , "vp9" , StringComparison . OrdinalIgnoreCase ) )
{
return "libvpx-vp9" ;
}
2018-12-28 00:27:57 +01:00
if ( string . Equals ( codec , "wmv" , StringComparison . OrdinalIgnoreCase ) )
{
return "wmv2" ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( codec , "theora" , StringComparison . OrdinalIgnoreCase ) )
{
return "libtheora" ;
}
2019-01-27 12:03:43 +01:00
return codec . ToLowerInvariant ( ) ;
2018-12-28 00:27:57 +01:00
}
return "copy" ;
}
/// <summary>
/// Gets the user agent param.
/// </summary>
/// <param name="state">The state.</param>
/// <returns>System.String.</returns>
public string GetUserAgentParam ( EncodingJobInfo state )
{
2019-09-08 21:07:29 +02:00
if ( state . RemoteHttpHeaders . TryGetValue ( "User-Agent" , out string useragent ) )
2018-12-28 00:27:57 +01:00
{
return "-user_agent \"" + useragent + "\"" ;
}
return string . Empty ;
}
2022-07-19 08:30:27 +02:00
/// <summary>
/// Gets the referer param.
/// </summary>
/// <param name="state">The state.</param>
/// <returns>System.String.</returns>
public string GetRefererParam ( EncodingJobInfo state )
{
if ( state . RemoteHttpHeaders . TryGetValue ( "Referer" , out string referer ) )
{
return "-referer \"" + referer + "\"" ;
}
return string . Empty ;
}
2019-10-26 22:53:53 +02:00
public static string GetInputFormat ( string container )
2018-12-28 00:27:57 +01:00
{
if ( string . IsNullOrEmpty ( container ) )
{
return null ;
}
container = container . Replace ( "mkv" , "matroska" , StringComparison . OrdinalIgnoreCase ) ;
if ( string . Equals ( container , "ts" , StringComparison . OrdinalIgnoreCase ) )
{
return "mpegts" ;
}
// For these need to find out the ffmpeg names
if ( string . Equals ( container , "m2ts" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( container , "wmv" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( container , "mts" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( container , "vob" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( container , "mpg" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( container , "mpeg" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( container , "rec" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( container , "dvr-ms" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( container , "ogm" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( container , "divx" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( container , "tp" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( container , "rmvb" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( container , "rtp" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2020-11-18 14:46:14 +01:00
// Seeing reported failures here, not sure yet if this is related to specifying input format
2018-12-28 00:27:57 +01:00
if ( string . Equals ( container , "m4v" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
// obviously don't do this for strm files
if ( string . Equals ( container , "strm" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2021-03-25 11:45:27 +01:00
// ISO files don't have an ffmpeg format
if ( string . Equals ( container , "iso" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2018-12-28 00:27:57 +01:00
return container ;
}
2021-08-10 23:29:48 +02:00
/// <summary>
/// Gets decoder from a codec.
/// </summary>
/// <param name="codec">Codec to use.</param>
/// <returns>Decoder string.</returns>
2018-12-28 00:27:57 +01:00
public string GetDecoderFromCodec ( string codec )
{
// For these need to find out the ffmpeg names
if ( string . Equals ( codec , "mp2" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( codec , "aac_latm" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( codec , "eac3" , StringComparison . OrdinalIgnoreCase ) )
{
return null ;
}
if ( _mediaEncoder . SupportsDecoder ( codec ) )
{
return codec ;
}
return null ;
}
/// <summary>
2020-06-16 00:37:52 +02:00
/// Infers the audio codec based on the url.
2018-12-28 00:27:57 +01:00
/// </summary>
2021-08-10 23:29:48 +02:00
/// <param name="container">Container to use.</param>
/// <returns>Codec string.</returns>
2018-12-28 00:27:57 +01:00
public string InferAudioCodec ( string container )
{
var ext = "." + ( container ? ? string . Empty ) ;
if ( string . Equals ( ext , ".mp3" , StringComparison . OrdinalIgnoreCase ) )
{
return "mp3" ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( ext , ".aac" , StringComparison . OrdinalIgnoreCase ) )
{
return "aac" ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( ext , ".wma" , StringComparison . OrdinalIgnoreCase ) )
{
return "wma" ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( ext , ".ogg" , StringComparison . OrdinalIgnoreCase ) )
{
return "vorbis" ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( ext , ".oga" , StringComparison . OrdinalIgnoreCase ) )
{
return "vorbis" ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( ext , ".ogv" , StringComparison . OrdinalIgnoreCase ) )
{
return "vorbis" ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( ext , ".webm" , StringComparison . OrdinalIgnoreCase ) )
{
return "vorbis" ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( ext , ".webma" , StringComparison . OrdinalIgnoreCase ) )
{
return "vorbis" ;
}
return "copy" ;
}
/// <summary>
/// Infers the video codec.
/// </summary>
/// <param name="url">The URL.</param>
/// <returns>System.Nullable{VideoCodecs}.</returns>
public string InferVideoCodec ( string url )
{
var ext = Path . GetExtension ( url ) ;
if ( string . Equals ( ext , ".asf" , StringComparison . OrdinalIgnoreCase ) )
{
return "wmv" ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( ext , ".webm" , StringComparison . OrdinalIgnoreCase ) )
{
2021-08-20 20:22:21 +02:00
// TODO: this may not always mean VP8, as the codec ages
return "vp8" ;
2018-12-28 00:27:57 +01:00
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( ext , ".ogg" , StringComparison . OrdinalIgnoreCase ) | | string . Equals ( ext , ".ogv" , StringComparison . OrdinalIgnoreCase ) )
{
return "theora" ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( ext , ".m3u8" , StringComparison . OrdinalIgnoreCase ) | | string . Equals ( ext , ".ts" , StringComparison . OrdinalIgnoreCase ) )
{
return "h264" ;
}
return "copy" ;
}
2021-12-01 17:49:50 +01:00
public int GetVideoProfileScore ( string videoCodec , string videoProfile )
2018-12-28 00:27:57 +01:00
{
// strip spaces because they may be stripped out on the query string
2021-12-01 17:49:50 +01:00
string profile = videoProfile . Replace ( " " , string . Empty , StringComparison . Ordinal ) ;
if ( string . Equals ( "h264" , videoCodec , StringComparison . OrdinalIgnoreCase ) )
{
return Array . FindIndex ( _videoProfilesH264 , x = > string . Equals ( x , profile , StringComparison . OrdinalIgnoreCase ) ) ;
}
2023-04-06 19:38:34 +02:00
if ( string . Equals ( "hevc" , videoCodec , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
return Array . FindIndex ( _videoProfilesH265 , x = > string . Equals ( x , profile , StringComparison . OrdinalIgnoreCase ) ) ;
}
2023-06-19 21:49:26 +02:00
if ( string . Equals ( "av1" , videoCodec , StringComparison . OrdinalIgnoreCase ) )
{
return Array . FindIndex ( _videoProfilesAv1 , x = > string . Equals ( x , profile , StringComparison . OrdinalIgnoreCase ) ) ;
}
2021-12-01 17:49:50 +01:00
return - 1 ;
2018-12-28 00:27:57 +01:00
}
public string GetInputPathArgument ( EncodingJobInfo state )
{
2023-02-18 14:42:35 +01:00
return state . MediaSource . VideoType switch
2023-02-03 20:03:55 +01:00
{
2023-02-18 14:42:35 +01:00
VideoType . Dvd = > _mediaEncoder . GetInputArgument ( _mediaEncoder . GetPrimaryPlaylistVobFiles ( state . MediaPath , null ) . ToList ( ) , state . MediaSource ) ,
VideoType . BluRay = > _mediaEncoder . GetInputArgument ( _mediaEncoder . GetPrimaryPlaylistM2tsFiles ( state . MediaPath ) . ToList ( ) , state . MediaSource ) ,
_ = > _mediaEncoder . GetInputArgument ( state . MediaPath , state . MediaSource )
} ;
2018-12-28 00:27:57 +01:00
}
/// <summary>
/// Gets the audio encoder.
/// </summary>
/// <param name="state">The state.</param>
/// <returns>System.String.</returns>
public string GetAudioEncoder ( EncodingJobInfo state )
{
var codec = state . OutputAudioCodec ;
if ( string . Equals ( codec , "aac" , StringComparison . OrdinalIgnoreCase ) )
{
2023-02-08 23:42:17 +01:00
// Use Apple's aac encoder if available as it provides best audio quality
if ( _mediaEncoder . SupportsEncoder ( "aac_at" ) )
{
return "aac_at" ;
}
2020-03-31 18:22:10 +02:00
// Use libfdk_aac for better audio quality if using custom build of FFmpeg which has fdk_aac support
2020-03-30 09:53:49 +02:00
if ( _mediaEncoder . SupportsEncoder ( "libfdk_aac" ) )
{
return "libfdk_aac" ;
}
2020-04-01 18:48:43 +02:00
2020-04-01 01:48:29 +02:00
return "aac" ;
2018-12-28 00:27:57 +01:00
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( codec , "mp3" , StringComparison . OrdinalIgnoreCase ) )
{
return "libmp3lame" ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( codec , "vorbis" , StringComparison . OrdinalIgnoreCase ) )
{
return "libvorbis" ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( codec , "wma" , StringComparison . OrdinalIgnoreCase ) )
{
return "wmav2" ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( string . Equals ( codec , "opus" , StringComparison . OrdinalIgnoreCase ) )
{
return "libopus" ;
2020-11-13 21:06:24 +01:00
}
if ( string . Equals ( codec , "flac" , StringComparison . OrdinalIgnoreCase ) )
{
2022-06-06 17:29:39 +02:00
return "flac" ;
2018-12-28 00:27:57 +01:00
}
2023-02-24 15:04:52 +01:00
if ( string . Equals ( codec , "dts" , StringComparison . OrdinalIgnoreCase ) )
{
return "dca" ;
}
2019-01-27 12:03:43 +01:00
return codec . ToLowerInvariant ( ) ;
2018-12-28 00:27:57 +01:00
}
2021-12-24 09:50:40 +01:00
private string GetVideoToolboxDeviceArgs ( string alias )
2021-12-01 17:49:50 +01:00
{
2021-12-24 09:50:40 +01:00
alias ? ? = VideotoolboxAlias ;
2021-12-01 17:49:50 +01:00
// device selection in vt is not supported.
return " -init_hw_device videotoolbox=" + alias ;
}
2021-12-24 09:50:40 +01:00
private string GetCudaDeviceArgs ( int deviceIndex , string alias )
2021-12-01 17:49:50 +01:00
{
2021-12-24 09:50:40 +01:00
alias ? ? = CudaAlias ;
2021-12-01 17:49:50 +01:00
deviceIndex = deviceIndex > = 0
? deviceIndex
: 0 ;
return string . Format (
CultureInfo . InvariantCulture ,
" -init_hw_device cuda={0}:{1}" ,
2021-12-24 09:50:40 +01:00
alias ,
deviceIndex ) ;
2021-12-01 17:49:50 +01:00
}
2023-03-04 17:22:43 +01:00
private string GetVulkanDeviceArgs ( int deviceIndex , string deviceName , string srcDeviceAlias , string alias )
{
alias ? ? = VulkanAlias ;
deviceIndex = deviceIndex > = 0
? deviceIndex
: 0 ;
var vendorOpts = string . IsNullOrEmpty ( deviceName )
? ":" + deviceIndex
: ":" + "\"" + deviceName + "\"" ;
var options = string . IsNullOrEmpty ( srcDeviceAlias )
? vendorOpts
: "@" + srcDeviceAlias ;
return string . Format (
CultureInfo . InvariantCulture ,
" -init_hw_device vulkan={0}{1}" ,
alias ,
options ) ;
}
2021-12-24 09:50:40 +01:00
private string GetOpenclDeviceArgs ( int deviceIndex , string deviceVendorName , string srcDeviceAlias , string alias )
2021-12-01 17:49:50 +01:00
{
2021-12-24 09:50:40 +01:00
alias ? ? = OpenclAlias ;
2021-12-01 17:49:50 +01:00
deviceIndex = deviceIndex > = 0
? deviceIndex
: 0 ;
2021-12-24 09:50:40 +01:00
var vendorOpts = string . IsNullOrEmpty ( deviceVendorName )
? ":0.0"
: ":." + deviceIndex + ",device_vendor=\"" + deviceVendorName + "\"" ;
var options = string . IsNullOrEmpty ( srcDeviceAlias )
? vendorOpts
: "@" + srcDeviceAlias ;
2021-12-01 17:49:50 +01:00
return string . Format (
CultureInfo . InvariantCulture ,
" -init_hw_device opencl={0}{1}" ,
2021-12-24 09:50:40 +01:00
alias ,
options ) ;
2021-12-01 17:49:50 +01:00
}
2021-12-24 09:50:40 +01:00
private string GetD3d11vaDeviceArgs ( int deviceIndex , string deviceVendorId , string alias )
2021-12-01 17:49:50 +01:00
{
2021-12-24 09:50:40 +01:00
alias ? ? = D3d11vaAlias ;
2021-12-01 17:49:50 +01:00
deviceIndex = deviceIndex > = 0 ? deviceIndex : 0 ;
2021-12-24 09:50:40 +01:00
var options = string . IsNullOrEmpty ( deviceVendorId )
? deviceIndex . ToString ( CultureInfo . InvariantCulture )
: ",vendor=" + deviceVendorId ;
2021-12-01 17:49:50 +01:00
return string . Format (
CultureInfo . InvariantCulture ,
" -init_hw_device d3d11va={0}:{1}" ,
2021-12-24 09:50:40 +01:00
alias ,
options ) ;
2021-12-01 17:49:50 +01:00
}
2023-06-12 19:13:48 +02:00
private string GetVaapiDeviceArgs ( string renderNodePath , string driver , string kernelDriver , string srcDeviceAlias , string alias )
2021-12-01 17:49:50 +01:00
{
2021-12-24 09:50:40 +01:00
alias ? ? = VaapiAlias ;
2021-12-01 17:49:50 +01:00
renderNodePath = renderNodePath ? ? "/dev/dri/renderD128" ;
2023-06-12 19:13:48 +02:00
var driverOpts = string . IsNullOrEmpty ( driver )
? ":" + renderNodePath
: ":,driver=" + driver + ( string . IsNullOrEmpty ( kernelDriver ) ? string . Empty : ",kernel_driver=" + kernelDriver ) ;
var options = string . IsNullOrEmpty ( srcDeviceAlias )
? driverOpts
: "@" + srcDeviceAlias ;
2021-12-01 17:49:50 +01:00
return string . Format (
CultureInfo . InvariantCulture ,
2023-06-12 19:13:48 +02:00
" -init_hw_device vaapi={0}{1}" ,
2021-12-24 09:50:40 +01:00
alias ,
options ) ;
2021-12-01 17:49:50 +01:00
}
2023-06-12 19:13:48 +02:00
private string GetDrmDeviceArgs ( string renderNodePath , string alias )
{
alias ? ? = DrmAlias ;
renderNodePath = renderNodePath ? ? "/dev/dri/renderD128" ;
return string . Format (
CultureInfo . InvariantCulture ,
" -init_hw_device drm={0}:{1}" ,
alias ,
renderNodePath ) ;
}
2021-12-24 09:50:40 +01:00
private string GetQsvDeviceArgs ( string alias )
2021-12-01 17:49:50 +01:00
{
2021-12-24 09:50:40 +01:00
var arg = " -init_hw_device qsv=" + ( alias ? ? QsvAlias ) ;
if ( OperatingSystem . IsLinux ( ) )
2021-12-01 17:49:50 +01:00
{
// derive qsv from vaapi device
2023-06-12 19:13:48 +02:00
return GetVaapiDeviceArgs ( null , "iHD" , "i915" , null , VaapiAlias ) + arg + "@" + VaapiAlias ;
2021-12-01 17:49:50 +01:00
}
2021-12-24 09:50:40 +01:00
if ( OperatingSystem . IsWindows ( ) )
2021-12-01 17:49:50 +01:00
{
// derive qsv from d3d11va device
2021-12-24 09:50:40 +01:00
return GetD3d11vaDeviceArgs ( 0 , "0x8086" , D3d11vaAlias ) + arg + "@" + D3d11vaAlias ;
2021-12-01 17:49:50 +01:00
}
2021-12-24 09:50:40 +01:00
return null ;
2021-12-01 17:49:50 +01:00
}
2021-12-24 09:50:40 +01:00
private string GetFilterHwDeviceArgs ( string alias )
2021-12-01 17:49:50 +01:00
{
2021-12-24 09:50:40 +01:00
return string . IsNullOrEmpty ( alias )
? string . Empty
: " -filter_hw_device " + alias ;
2021-12-01 17:49:50 +01:00
}
public string GetGraphicalSubCanvasSize ( EncodingJobInfo state )
{
2023-06-13 16:55:15 +02:00
// DVBSUB and DVDSUB use the fixed canvas size 720x576
2022-12-05 15:01:13 +01:00
if ( state . SubtitleStream is not null
2021-12-01 17:49:50 +01:00
& & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode
2023-06-13 16:55:15 +02:00
& & ! state . SubtitleStream . IsTextSubtitleStream
& & ! string . Equals ( state . SubtitleStream . Codec , "DVBSUB" , StringComparison . OrdinalIgnoreCase )
& & ! string . Equals ( state . SubtitleStream . Codec , "DVDSUB" , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
var inW = state . VideoStream ? . Width ;
var inH = state . VideoStream ? . Height ;
var reqW = state . BaseRequest . Width ;
var reqH = state . BaseRequest . Height ;
var reqMaxW = state . BaseRequest . MaxWidth ;
var reqMaxH = state . BaseRequest . MaxHeight ;
2021-12-24 09:50:40 +01:00
// setup a relative small canvas_size for overlay_qsv/vaapi to reduce transfer overhead
2021-12-01 17:49:50 +01:00
var ( overlayW , overlayH ) = GetFixedOutputSize ( inW , inH , reqW , reqH , reqMaxW , 1080 ) ;
if ( overlayW . HasValue & & overlayH . HasValue )
{
return string . Format (
CultureInfo . InvariantCulture ,
" -canvas_size {0}x{1}" ,
overlayW . Value ,
overlayH . Value ) ;
}
}
return string . Empty ;
}
2018-12-28 00:27:57 +01:00
/// <summary>
2021-12-01 17:49:50 +01:00
/// Gets the input video hwaccel argument.
2018-12-28 00:27:57 +01:00
/// </summary>
2021-08-10 23:29:48 +02:00
/// <param name="state">Encoding state.</param>
2021-08-13 09:01:06 +02:00
/// <param name="options">Encoding options.</param>
2021-12-01 17:49:50 +01:00
/// <returns>Input video hwaccel arguments.</returns>
public string GetInputVideoHwaccelArgs ( EncodingJobInfo state , EncodingOptions options )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
if ( ! state . IsVideoRequest )
{
2021-12-24 09:50:40 +01:00
return string . Empty ;
2021-12-01 17:49:50 +01:00
}
var vidEncoder = GetVideoEncoder ( state , options ) ? ? string . Empty ;
if ( IsCopyCodec ( vidEncoder ) )
{
2021-12-24 09:50:40 +01:00
return string . Empty ;
2021-12-01 17:49:50 +01:00
}
var args = new StringBuilder ( ) ;
2021-07-24 18:52:16 +02:00
var isWindows = OperatingSystem . IsWindows ( ) ;
var isLinux = OperatingSystem . IsLinux ( ) ;
var isMacOS = OperatingSystem . IsMacOS ( ) ;
2021-12-01 17:49:50 +01:00
var optHwaccelType = options . HardwareAccelerationType ;
var vidDecoder = GetHardwareVideoDecoder ( state , options ) ? ? string . Empty ;
var isHwTonemapAvailable = IsHwTonemapAvailable ( state , options ) ;
if ( string . Equals ( optHwaccelType , "vaapi" , StringComparison . OrdinalIgnoreCase ) )
{
if ( ! isLinux | | ! _mediaEncoder . SupportsHwaccel ( "vaapi" ) )
{
return string . Empty ;
}
var isVaapiDecoder = vidDecoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
var isVaapiEncoder = vidEncoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
if ( ! isVaapiDecoder & & ! isVaapiEncoder )
{
return string . Empty ;
}
2022-03-04 18:32:06 +01:00
if ( _mediaEncoder . IsVaapiDeviceInteliHD )
{
2023-06-12 19:13:48 +02:00
args . Append ( GetVaapiDeviceArgs ( null , "iHD" , null , null , VaapiAlias ) ) ;
2022-03-04 18:32:06 +01:00
}
else if ( _mediaEncoder . IsVaapiDeviceInteli965 )
{
2022-06-23 15:33:14 +02:00
// Only override i965 since it has lower priority than iHD in libva lookup.
Environment . SetEnvironmentVariable ( "LIBVA_DRIVER_NAME" , "i965" ) ;
Environment . SetEnvironmentVariable ( "LIBVA_DRIVER_NAME_JELLYFIN" , "i965" ) ;
2023-06-12 19:13:48 +02:00
args . Append ( GetVaapiDeviceArgs ( null , "i965" , null , null , VaapiAlias ) ) ;
2022-03-04 18:32:06 +01:00
}
2023-06-12 19:13:48 +02:00
var filterDevArgs = string . Empty ;
2023-04-02 11:30:22 +02:00
var doOclTonemap = isHwTonemapAvailable & & IsOpenclFullSupported ( ) ;
2021-12-01 17:49:50 +01:00
2023-04-02 11:30:22 +02:00
if ( _mediaEncoder . IsVaapiDeviceInteliHD | | _mediaEncoder . IsVaapiDeviceInteli965 )
2021-12-01 17:49:50 +01:00
{
2023-04-02 11:30:22 +02:00
if ( doOclTonemap & & ! isVaapiDecoder )
2020-07-17 13:32:15 +02:00
{
2023-04-02 11:30:22 +02:00
args . Append ( GetOpenclDeviceArgs ( 0 , null , VaapiAlias , OpenclAlias ) ) ;
filterDevArgs = GetFilterHwDeviceArgs ( OpenclAlias ) ;
2020-07-17 13:32:15 +02:00
}
2023-04-02 11:30:22 +02:00
}
else if ( _mediaEncoder . IsVaapiDeviceAmd )
{
if ( IsVulkanFullSupported ( )
& & _mediaEncoder . IsVaapiDeviceSupportVulkanFmtModifier
& & Environment . OSVersion . Version > = _minKernelVersionAmdVkFmtModifier )
2021-12-01 17:49:50 +01:00
{
2023-06-12 19:13:48 +02:00
args . Append ( GetDrmDeviceArgs ( options . VaapiDevice , DrmAlias ) ) ;
args . Append ( GetVaapiDeviceArgs ( null , null , null , DrmAlias , VaapiAlias ) ) ;
args . Append ( GetVulkanDeviceArgs ( 0 , null , DrmAlias , VulkanAlias ) ) ;
2023-04-02 11:30:22 +02:00
// libplacebo wants an explicitly set vulkan filter device.
filterDevArgs = GetFilterHwDeviceArgs ( VulkanAlias ) ;
2021-12-01 17:49:50 +01:00
}
2023-06-12 19:13:48 +02:00
else
2020-07-17 13:32:15 +02:00
{
2023-06-12 19:13:48 +02:00
args . Append ( GetVaapiDeviceArgs ( options . VaapiDevice , null , null , null , VaapiAlias ) ) ;
filterDevArgs = GetFilterHwDeviceArgs ( VaapiAlias ) ;
if ( doOclTonemap )
{
// ROCm/ROCr OpenCL runtime
args . Append ( GetOpenclDeviceArgs ( 0 , "Advanced Micro Devices" , null , OpenclAlias ) ) ;
filterDevArgs = GetFilterHwDeviceArgs ( OpenclAlias ) ;
}
2020-07-17 13:32:15 +02:00
}
2021-12-01 17:49:50 +01:00
}
2023-04-02 11:30:22 +02:00
else if ( doOclTonemap )
{
args . Append ( GetOpenclDeviceArgs ( 0 , null , null , OpenclAlias ) ) ;
filterDevArgs = GetFilterHwDeviceArgs ( OpenclAlias ) ;
}
2021-03-22 17:59:57 +01:00
2021-12-24 09:50:40 +01:00
args . Append ( filterDevArgs ) ;
2021-12-01 17:49:50 +01:00
}
else if ( string . Equals ( optHwaccelType , "qsv" , StringComparison . OrdinalIgnoreCase ) )
{
if ( ( ! isLinux & & ! isWindows ) | | ! _mediaEncoder . SupportsHwaccel ( "qsv" ) )
{
return string . Empty ;
2020-04-08 18:15:01 +02:00
}
2018-12-28 00:27:57 +01:00
2021-12-01 17:49:50 +01:00
var isD3d11vaDecoder = vidDecoder . Contains ( "d3d11va" , StringComparison . OrdinalIgnoreCase ) ;
var isVaapiDecoder = vidDecoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
var isQsvDecoder = vidDecoder . Contains ( "qsv" , StringComparison . OrdinalIgnoreCase ) ;
var isQsvEncoder = vidEncoder . Contains ( "qsv" , StringComparison . OrdinalIgnoreCase ) ;
var isHwDecoder = isQsvDecoder | | isVaapiDecoder | | isD3d11vaDecoder ;
if ( ! isHwDecoder & & ! isQsvEncoder )
2019-12-05 09:50:47 +01:00
{
2021-12-01 17:49:50 +01:00
return string . Empty ;
}
2020-07-17 13:32:15 +02:00
2021-12-24 09:50:40 +01:00
args . Append ( GetQsvDeviceArgs ( QsvAlias ) ) ;
var filterDevArgs = GetFilterHwDeviceArgs ( QsvAlias ) ;
2021-12-01 17:49:50 +01:00
// child device used by qsv.
if ( _mediaEncoder . SupportsHwaccel ( "vaapi" ) | | _mediaEncoder . SupportsHwaccel ( "d3d11va" ) )
{
if ( isHwTonemapAvailable & & IsOpenclFullSupported ( ) )
2019-12-05 09:50:47 +01:00
{
2021-12-24 09:50:40 +01:00
var srcAlias = isLinux ? VaapiAlias : D3d11vaAlias ;
args . Append ( GetOpenclDeviceArgs ( 0 , null , srcAlias , OpenclAlias ) ) ;
2021-12-01 17:49:50 +01:00
if ( ! isHwDecoder )
2020-03-20 20:29:33 +01:00
{
2021-12-24 09:50:40 +01:00
filterDevArgs = GetFilterHwDeviceArgs ( OpenclAlias ) ;
2020-03-20 20:29:33 +01:00
}
2021-12-01 17:49:50 +01:00
}
}
2020-09-28 22:04:31 +02:00
2021-12-24 09:50:40 +01:00
args . Append ( filterDevArgs ) ;
2021-12-01 17:49:50 +01:00
}
else if ( string . Equals ( optHwaccelType , "nvenc" , StringComparison . OrdinalIgnoreCase ) )
{
if ( ( ! isLinux & & ! isWindows ) | | ! IsCudaFullSupported ( ) )
{
return string . Empty ;
}
2021-01-29 10:53:42 +01:00
2021-12-01 17:49:50 +01:00
var isCuvidDecoder = vidDecoder . Contains ( "cuvid" , StringComparison . OrdinalIgnoreCase ) ;
var isNvdecDecoder = vidDecoder . Contains ( "cuda" , StringComparison . OrdinalIgnoreCase ) ;
var isNvencEncoder = vidEncoder . Contains ( "nvenc" , StringComparison . OrdinalIgnoreCase ) ;
var isHwDecoder = isNvdecDecoder | | isCuvidDecoder ;
if ( ! isHwDecoder & & ! isNvencEncoder )
{
return string . Empty ;
}
2021-03-22 17:59:57 +01:00
2021-12-24 09:50:40 +01:00
args . Append ( GetCudaDeviceArgs ( 0 , CudaAlias ) )
. Append ( GetFilterHwDeviceArgs ( CudaAlias ) ) ;
2021-12-01 17:49:50 +01:00
}
else if ( string . Equals ( optHwaccelType , "amf" , StringComparison . OrdinalIgnoreCase ) )
{
if ( ! isWindows | | ! _mediaEncoder . SupportsHwaccel ( "d3d11va" ) )
{
return string . Empty ;
2019-12-05 09:50:47 +01:00
}
2020-07-24 18:57:34 +02:00
2021-12-01 17:49:50 +01:00
var isD3d11vaDecoder = vidDecoder . Contains ( "d3d11va" , StringComparison . OrdinalIgnoreCase ) ;
var isAmfEncoder = vidEncoder . Contains ( "amf" , StringComparison . OrdinalIgnoreCase ) ;
if ( ! isD3d11vaDecoder & & ! isAmfEncoder )
2021-01-24 20:40:34 +01:00
{
2021-12-01 17:49:50 +01:00
return string . Empty ;
2021-01-24 20:40:34 +01:00
}
2021-12-01 17:49:50 +01:00
// no dxva video processor hw filter.
2021-12-24 09:50:40 +01:00
args . Append ( GetD3d11vaDeviceArgs ( 0 , "0x1002" , D3d11vaAlias ) ) ;
2021-12-01 17:49:50 +01:00
var filterDevArgs = string . Empty ;
if ( IsOpenclFullSupported ( ) )
2020-07-24 18:57:34 +02:00
{
2021-12-24 09:50:40 +01:00
args . Append ( GetOpenclDeviceArgs ( 0 , null , D3d11vaAlias , OpenclAlias ) ) ;
filterDevArgs = GetFilterHwDeviceArgs ( OpenclAlias ) ;
2020-07-27 08:11:05 +02:00
}
2020-07-27 07:57:40 +02:00
2021-12-24 09:50:40 +01:00
args . Append ( filterDevArgs ) ;
2021-12-01 17:49:50 +01:00
}
else if ( string . Equals ( optHwaccelType , "videotoolbox" , StringComparison . OrdinalIgnoreCase ) )
{
if ( ! isMacOS | | ! _mediaEncoder . SupportsHwaccel ( "videotoolbox" ) )
2020-07-24 18:57:34 +02:00
{
2021-12-01 17:49:50 +01:00
return string . Empty ;
2020-07-27 08:11:05 +02:00
}
2020-07-27 07:57:40 +02:00
2021-12-01 17:49:50 +01:00
var isVideotoolboxDecoder = vidDecoder . Contains ( "videotoolbox" , StringComparison . OrdinalIgnoreCase ) ;
var isVideotoolboxEncoder = vidEncoder . Contains ( "videotoolbox" , StringComparison . OrdinalIgnoreCase ) ;
if ( ! isVideotoolboxDecoder & & ! isVideotoolboxEncoder )
2020-07-26 17:47:29 +02:00
{
2021-12-01 17:49:50 +01:00
return string . Empty ;
2020-07-24 18:57:34 +02:00
}
2021-12-01 17:49:50 +01:00
// no videotoolbox hw filter.
2021-12-24 09:50:40 +01:00
args . Append ( GetVideoToolboxDeviceArgs ( VideotoolboxAlias ) ) ;
2019-12-05 09:50:47 +01:00
}
2019-12-04 09:16:19 +01:00
2021-12-01 17:49:50 +01:00
if ( ! string . IsNullOrEmpty ( vidDecoder ) )
{
args . Append ( vidDecoder ) ;
}
// hw transpose filters should be added manually.
args . Append ( " -autorotate 0" ) ;
return args . ToString ( ) . Trim ( ) ;
}
/// <summary>
/// Gets the input argument.
/// </summary>
/// <param name="state">Encoding state.</param>
/// <param name="options">Encoding options.</param>
2022-03-09 14:28:58 +01:00
/// <param name="segmentContainer">Segment Container.</param>
2021-12-01 17:49:50 +01:00
/// <returns>Input arguments.</returns>
2022-03-09 14:28:58 +01:00
public string GetInputArgument ( EncodingJobInfo state , EncodingOptions options , string segmentContainer )
2021-12-01 17:49:50 +01:00
{
var arg = new StringBuilder ( ) ;
var inputVidHwaccelArgs = GetInputVideoHwaccelArgs ( state , options ) ;
if ( ! string . IsNullOrEmpty ( inputVidHwaccelArgs ) )
{
arg . Append ( inputVidHwaccelArgs ) ;
}
var canvasArgs = GetGraphicalSubCanvasSize ( state ) ;
if ( ! string . IsNullOrEmpty ( canvasArgs ) )
{
arg . Append ( canvasArgs ) ;
}
2023-02-04 00:08:51 +01:00
if ( state . MediaSource . VideoType = = VideoType . Dvd | | state . MediaSource . VideoType = = VideoType . BluRay )
{
2023-02-05 17:24:13 +01:00
var tmpConcatPath = Path . Join ( options . TranscodingTempPath , state . MediaSource . Id + ".concat" ) ;
2023-02-04 00:08:51 +01:00
_mediaEncoder . GenerateConcatConfig ( state . MediaSource , tmpConcatPath ) ;
2023-02-18 14:42:35 +01:00
arg . Append ( " -f concat -safe 0 -i " )
. Append ( tmpConcatPath ) ;
2023-02-04 00:08:51 +01:00
}
else
{
arg . Append ( " -i " )
. Append ( GetInputPathArgument ( state ) ) ;
}
2018-12-28 00:27:57 +01:00
2021-12-01 17:49:50 +01:00
// sub2video for external graphical subtitles
2022-12-05 15:01:13 +01:00
if ( state . SubtitleStream is not null
2019-09-01 18:39:23 +02:00
& & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode
2021-12-01 17:49:50 +01:00
& & ! state . SubtitleStream . IsTextSubtitleStream
& & state . SubtitleStream . IsExternal )
2019-09-01 18:39:23 +02:00
{
var subtitlePath = state . SubtitleStream . Path ;
2022-12-30 16:24:06 +01:00
var subtitleExtension = Path . GetExtension ( subtitlePath ) ;
2018-12-28 00:27:57 +01:00
2022-12-30 16:24:06 +01:00
if ( string . Equals ( subtitleExtension , ".sub" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( subtitleExtension , ".sup" , StringComparison . OrdinalIgnoreCase ) )
2019-09-01 18:39:23 +02:00
{
var idxFile = Path . ChangeExtension ( subtitlePath , ".idx" ) ;
if ( File . Exists ( idxFile ) )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
subtitlePath = idxFile ;
2018-12-28 00:27:57 +01:00
}
}
2019-09-01 18:39:23 +02:00
2021-12-01 17:49:50 +01:00
// Also seek the external subtitles stream.
2022-03-09 14:28:58 +01:00
var seekSubParam = GetFastSeekCommandLineParameter ( state , options , segmentContainer ) ;
2021-12-01 17:49:50 +01:00
if ( ! string . IsNullOrEmpty ( seekSubParam ) )
{
arg . Append ( ' ' ) . Append ( seekSubParam ) ;
}
if ( ! string . IsNullOrEmpty ( canvasArgs ) )
{
arg . Append ( canvasArgs ) ;
}
arg . Append ( " -i file:\"" ) . Append ( subtitlePath ) . Append ( '\"' ) ;
2018-12-28 00:27:57 +01:00
}
2022-12-05 15:01:13 +01:00
if ( state . AudioStream is not null & & state . AudioStream . IsExternal )
2021-11-27 12:10:57 +01:00
{
2022-01-09 06:49:40 +01:00
// Also seek the external audio stream.
2022-03-09 14:28:58 +01:00
var seekAudioParam = GetFastSeekCommandLineParameter ( state , options , segmentContainer ) ;
2022-01-09 06:49:40 +01:00
if ( ! string . IsNullOrEmpty ( seekAudioParam ) )
{
arg . Append ( ' ' ) . Append ( seekAudioParam ) ;
}
2021-12-03 19:18:43 +01:00
arg . Append ( " -i \"" ) . Append ( state . AudioStream . Path ) . Append ( '"' ) ;
2021-11-27 12:10:57 +01:00
}
2022-08-01 20:25:45 +02:00
// Disable auto inserted SW scaler for HW decoders in case of changed resolution.
var isSwDecoder = string . IsNullOrEmpty ( GetHardwareVideoDecoder ( state , options ) ) ;
2022-11-30 21:00:39 +01:00
if ( ! isSwDecoder & & _mediaEncoder . EncoderVersion > = new Version ( 4 , 4 ) )
2022-08-01 20:25:45 +02:00
{
arg . Append ( " -autoscale 0" ) ;
}
2019-09-01 18:39:23 +02:00
return arg . ToString ( ) ;
2018-12-28 00:27:57 +01:00
}
/// <summary>
/// Determines whether the specified stream is H264.
/// </summary>
/// <param name="stream">The stream.</param>
/// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
2020-11-19 15:46:02 +01:00
public static bool IsH264 ( MediaStream stream )
2018-12-28 00:27:57 +01:00
{
var codec = stream . Codec ? ? string . Empty ;
2019-09-01 18:39:23 +02:00
return codec . IndexOf ( "264" , StringComparison . OrdinalIgnoreCase ) ! = - 1
| | codec . IndexOf ( "avc" , StringComparison . OrdinalIgnoreCase ) ! = - 1 ;
2018-12-28 00:27:57 +01:00
}
2020-11-19 15:46:02 +01:00
public static bool IsH265 ( MediaStream stream )
2019-06-02 00:03:48 +02:00
{
var codec = stream . Codec ? ? string . Empty ;
2019-09-01 18:39:23 +02:00
return codec . IndexOf ( "265" , StringComparison . OrdinalIgnoreCase ) ! = - 1
| | codec . IndexOf ( "hevc" , StringComparison . OrdinalIgnoreCase ) ! = - 1 ;
2019-06-02 00:03:48 +02:00
}
2020-11-19 15:46:02 +01:00
public static bool IsAAC ( MediaStream stream )
2020-11-14 07:22:15 +01:00
{
var codec = stream . Codec ? ? string . Empty ;
return codec . IndexOf ( "aac" , StringComparison . OrdinalIgnoreCase ) ! = - 1 ;
}
2020-11-19 15:46:02 +01:00
public static string GetBitStreamArgs ( MediaStream stream )
2019-06-02 00:03:48 +02:00
{
2020-11-14 11:19:41 +01:00
// TODO This is auto inserted into the mpegts mux so it might not be needed.
2020-11-14 07:22:15 +01:00
// https://www.ffmpeg.org/ffmpeg-bitstream-filters.html#h264_005fmp4toannexb
2019-06-02 00:03:48 +02:00
if ( IsH264 ( stream ) )
{
return "-bsf:v h264_mp4toannexb" ;
}
2023-04-06 19:38:34 +02:00
if ( IsH265 ( stream ) )
2019-06-02 00:03:48 +02:00
{
return "-bsf:v hevc_mp4toannexb" ;
}
2023-04-06 19:38:34 +02:00
if ( IsAAC ( stream ) )
2020-11-14 07:22:15 +01:00
{
2020-11-14 11:19:41 +01:00
// Convert adts header(mpegts) to asc header(mp4).
2020-11-14 07:22:15 +01:00
return "-bsf:a aac_adtstoasc" ;
}
2023-04-06 19:38:34 +02:00
return null ;
2019-06-02 00:03:48 +02:00
}
2020-11-19 15:46:02 +01:00
public static string GetAudioBitStreamArguments ( EncodingJobInfo state , string segmentContainer , string mediaSourceContainer )
{
var bitStreamArgs = string . Empty ;
var segmentFormat = GetSegmentFileExtension ( segmentContainer ) . TrimStart ( '.' ) ;
// Apply aac_adtstoasc bitstream filter when media source is in mpegts.
if ( string . Equals ( segmentFormat , "mp4" , StringComparison . OrdinalIgnoreCase )
& & ( string . Equals ( mediaSourceContainer , "mpegts" , StringComparison . OrdinalIgnoreCase )
2022-03-25 15:12:56 +01:00
| | string . Equals ( mediaSourceContainer , "aac" , StringComparison . OrdinalIgnoreCase )
2020-11-19 15:46:02 +01:00
| | string . Equals ( mediaSourceContainer , "hls" , StringComparison . OrdinalIgnoreCase ) ) )
{
bitStreamArgs = GetBitStreamArgs ( state . AudioStream ) ;
bitStreamArgs = string . IsNullOrEmpty ( bitStreamArgs ) ? string . Empty : " " + bitStreamArgs ;
}
return bitStreamArgs ;
}
public static string GetSegmentFileExtension ( string segmentContainer )
{
if ( ! string . IsNullOrWhiteSpace ( segmentContainer ) )
{
return "." + segmentContainer ;
}
return ".ts" ;
}
2018-12-28 00:27:57 +01:00
public string GetVideoBitrateParam ( EncodingJobInfo state , string videoCodec )
{
2022-12-05 15:00:20 +01:00
if ( state . OutputVideoBitrate is null )
2018-12-28 00:27:57 +01:00
{
2021-08-20 20:22:21 +02:00
return string . Empty ;
}
2018-12-28 00:27:57 +01:00
2021-08-20 20:22:21 +02:00
int bitrate = state . OutputVideoBitrate . Value ;
2018-12-28 00:27:57 +01:00
2021-08-20 20:22:21 +02:00
// Currently use the same buffer size for all encoders
int bufsize = bitrate * 2 ;
2018-12-28 00:27:57 +01:00
2021-08-20 20:22:21 +02:00
if ( string . Equals ( videoCodec , "libvpx" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoCodec , "libvpx-vp9" , StringComparison . OrdinalIgnoreCase ) )
{
// When crf is used with vpx, b:v becomes a max rate
// https://trac.ffmpeg.org/wiki/Encode/VP8
// https://trac.ffmpeg.org/wiki/Encode/VP9
return FormattableString . Invariant ( $" -maxrate:v {bitrate} -bufsize:v {bufsize} -b:v {bitrate}" ) ;
2018-12-28 00:27:57 +01:00
}
2021-08-20 20:22:21 +02:00
if ( string . Equals ( videoCodec , "msmpeg4" , StringComparison . OrdinalIgnoreCase ) )
{
return FormattableString . Invariant ( $" -b:v {bitrate}" ) ;
}
2023-06-19 21:49:26 +02:00
if ( string . Equals ( videoCodec , "libsvtav1" , StringComparison . OrdinalIgnoreCase ) )
{
return FormattableString . Invariant ( $" -b:v {bitrate} -bufsize {bufsize}" ) ;
}
2021-08-20 20:22:21 +02:00
if ( string . Equals ( videoCodec , "libx264" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoCodec , "libx265" , StringComparison . OrdinalIgnoreCase ) )
{
return FormattableString . Invariant ( $" -maxrate {bitrate} -bufsize {bufsize}" ) ;
}
2021-12-01 17:49:50 +01:00
if ( string . Equals ( videoCodec , "h264_amf" , StringComparison . OrdinalIgnoreCase )
2023-06-19 21:49:26 +02:00
| | string . Equals ( videoCodec , "hevc_amf" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoCodec , "av1_amf" , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
2022-06-06 17:29:39 +02:00
// Override the too high default qmin 18 in transcoding preset
return FormattableString . Invariant ( $" -rc cbr -qmin 0 -qmax 32 -b:v {bitrate} -maxrate {bitrate} -bufsize {bufsize}" ) ;
2021-12-01 17:49:50 +01:00
}
if ( string . Equals ( videoCodec , "h264_vaapi" , StringComparison . OrdinalIgnoreCase )
2023-06-19 21:49:26 +02:00
| | string . Equals ( videoCodec , "hevc_vaapi" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoCodec , "av1_vaapi" , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
// VBR in i965 driver may result in pixelated output.
2021-12-24 09:50:40 +01:00
if ( _mediaEncoder . IsVaapiDeviceInteli965 )
2021-12-01 17:49:50 +01:00
{
return FormattableString . Invariant ( $" -rc_mode CBR -b:v {bitrate} -maxrate {bitrate} -bufsize {bufsize}" ) ;
}
2023-04-06 19:38:34 +02:00
return FormattableString . Invariant ( $" -rc_mode VBR -b:v {bitrate} -maxrate {bitrate} -bufsize {bufsize}" ) ;
2021-12-01 17:49:50 +01:00
}
2021-08-20 20:22:21 +02:00
return FormattableString . Invariant ( $" -b:v {bitrate} -maxrate {bitrate} -bufsize {bufsize}" ) ;
2018-12-28 00:27:57 +01:00
}
2020-11-07 18:39:32 +01:00
public static string NormalizeTranscodingLevel ( EncodingJobInfo state , string level )
2018-12-28 00:27:57 +01:00
{
2023-02-19 16:52:29 +01:00
if ( double . TryParse ( level , CultureInfo . InvariantCulture , out double requestLevel ) )
2018-12-28 00:27:57 +01:00
{
2023-06-19 21:49:26 +02:00
if ( string . Equals ( state . ActualOutputVideoCodec , "av1" , StringComparison . OrdinalIgnoreCase ) )
{
// Transcode to level 5.3 (15) and lower for maximum compatibility.
// https://en.wikipedia.org/wiki/AV1#Levels
if ( requestLevel < 0 | | requestLevel > = 15 )
{
return "15" ;
}
}
else if ( string . Equals ( state . ActualOutputVideoCodec , "hevc" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( state . ActualOutputVideoCodec , "h265" , StringComparison . OrdinalIgnoreCase ) )
2020-11-07 18:39:32 +01:00
{
2020-11-11 03:03:53 +01:00
// Transcode to level 5.0 and lower for maximum compatibility.
// Level 5.0 is suitable for up to 4k 30fps hevc encoding, otherwise let the encoder to handle it.
2020-11-08 10:01:58 +01:00
// https://en.wikipedia.org/wiki/High_Efficiency_Video_Coding_tiers_and_levels
2020-11-11 03:03:53 +01:00
// MaxLumaSampleRate = 3840*2160*30 = 248832000 < 267386880.
2023-06-19 21:49:26 +02:00
if ( requestLevel < 0 | | requestLevel > = 150 )
2020-11-07 18:39:32 +01:00
{
return "150" ;
}
}
else if ( string . Equals ( state . ActualOutputVideoCodec , "h264" , StringComparison . OrdinalIgnoreCase ) )
{
2022-04-23 00:40:53 +02:00
// Transcode to level 5.1 and lower for maximum compatibility.
// h264 4k 30fps requires at least level 5.1 otherwise it will break on safari fmp4.
// https://en.wikipedia.org/wiki/Advanced_Video_Coding#Levels
2023-06-19 21:49:26 +02:00
if ( requestLevel < 0 | | requestLevel > = 51 )
2020-11-07 18:39:32 +01:00
{
2022-04-23 00:40:53 +02:00
return "51" ;
2020-11-07 18:39:32 +01:00
}
}
2018-12-28 00:27:57 +01:00
}
return level ;
}
/// <summary>
/// Gets the text subtitle param.
/// </summary>
/// <param name="state">The state.</param>
2021-12-01 17:49:50 +01:00
/// <param name="enableAlpha">Enable alpha processing.</param>
/// <param name="enableSub2video">Enable sub2video mode.</param>
2018-12-28 00:27:57 +01:00
/// <returns>System.String.</returns>
2021-12-01 17:49:50 +01:00
public string GetTextSubtitlesFilter ( EncodingJobInfo state , bool enableAlpha , bool enableSub2video )
2018-12-28 00:27:57 +01:00
{
var seconds = Math . Round ( TimeSpan . FromTicks ( state . StartTimeTicks ? ? 0 ) . TotalSeconds ) ;
// hls always copies timestamps
var setPtsParam = state . CopyTimestamps | | state . TranscodingType ! = TranscodingJobType . Progressive
? string . Empty
2019-09-01 18:39:23 +02:00
: string . Format ( CultureInfo . InvariantCulture , ",setpts=PTS -{0}/TB" , seconds ) ;
2018-12-28 00:27:57 +01:00
2021-12-24 09:50:40 +01:00
var alphaParam = enableAlpha ? ":alpha=1" : string . Empty ;
var sub2videoParam = enableSub2video ? ":sub2video=1" : string . Empty ;
2021-12-01 17:49:50 +01:00
2022-02-06 14:02:01 +01:00
var fontPath = Path . Combine ( _appPaths . CachePath , "attachments" , state . MediaSource . Id ) ;
var fontParam = string . Format (
CultureInfo . InvariantCulture ,
2022-03-01 15:41:54 +01:00
":fontsdir='{0}'" ,
2022-02-06 14:02:01 +01:00
_mediaEncoder . EscapeSubtitleFilterPath ( fontPath ) ) ;
2019-01-13 02:06:59 +01:00
if ( state . SubtitleStream . IsExternal )
{
var charsetParam = string . Empty ;
if ( ! string . IsNullOrEmpty ( state . SubtitleStream . Language ) )
{
2019-10-26 22:53:53 +02:00
var charenc = _subtitleEncoder . GetSubtitleFileCharacterSet (
2022-08-14 03:46:33 +02:00
state . SubtitleStream ,
state . SubtitleStream . Language ,
state . MediaSource ,
CancellationToken . None ) . GetAwaiter ( ) . GetResult ( ) ;
2019-01-13 02:06:59 +01:00
if ( ! string . IsNullOrEmpty ( charenc ) )
{
charsetParam = ":charenc=" + charenc ;
}
}
// TODO: Perhaps also use original_size=1920x800 ??
2019-07-29 00:43:57 +02:00
return string . Format (
CultureInfo . InvariantCulture ,
2022-02-06 14:02:01 +01:00
"subtitles=f='{0}'{1}{2}{3}{4}{5}" ,
2022-08-14 03:46:33 +02:00
_mediaEncoder . EscapeSubtitleFilterPath ( state . SubtitleStream . Path ) ,
2019-01-13 02:06:59 +01:00
charsetParam ,
2021-12-01 17:49:50 +01:00
alphaParam ,
sub2videoParam ,
2022-02-06 14:02:01 +01:00
fontParam ,
2019-01-13 02:06:59 +01:00
setPtsParam ) ;
}
2018-12-28 00:27:57 +01:00
var mediaPath = state . MediaPath ? ? string . Empty ;
2019-07-29 00:43:57 +02:00
return string . Format (
CultureInfo . InvariantCulture ,
2022-03-01 15:41:54 +01:00
"subtitles=f='{0}':si={1}{2}{3}{4}{5}" ,
2018-12-28 00:27:57 +01:00
_mediaEncoder . EscapeSubtitleFilterPath ( mediaPath ) ,
2021-09-26 16:14:36 +02:00
state . InternalSubtitleStreamOffset . ToString ( CultureInfo . InvariantCulture ) ,
2021-12-01 17:49:50 +01:00
alphaParam ,
sub2videoParam ,
2022-02-06 14:02:01 +01:00
fontParam ,
2019-01-13 02:06:59 +01:00
// fallbackFontParam,
2018-12-28 00:27:57 +01:00
setPtsParam ) ;
}
public double? GetFramerateParam ( EncodingJobInfo state )
{
var request = state . BaseRequest ;
if ( request . Framerate . HasValue )
{
return request . Framerate . Value ;
}
var maxrate = request . MaxFramerate ;
2022-12-05 15:01:13 +01:00
if ( maxrate . HasValue & & state . VideoStream is not null )
2018-12-28 00:27:57 +01:00
{
var contentRate = state . VideoStream . AverageFrameRate ? ? state . VideoStream . RealFrameRate ;
if ( contentRate . HasValue & & contentRate . Value > maxrate . Value )
{
return maxrate ;
}
}
return null ;
}
2020-11-19 15:46:02 +01:00
public string GetHlsVideoKeyFrameArguments (
EncodingJobInfo state ,
string codec ,
int segmentLength ,
bool isEventPlaylist ,
int? startNumber )
{
var args = string . Empty ;
var gopArg = string . Empty ;
2022-11-15 11:32:58 +01:00
var keyFrameArg = string . Format (
CultureInfo . InvariantCulture ,
" -force_key_frames:0 \"expr:gte(t,n_forced*{0})\"" ,
segmentLength ) ;
2020-11-19 15:46:02 +01:00
var framerate = state . VideoStream ? . RealFrameRate ;
if ( framerate . HasValue )
{
// This is to make sure keyframe interval is limited to our segment,
// as forcing keyframes is not enough.
// Example: we encoded half of desired length, then codec detected
// scene cut and inserted a keyframe; next forced keyframe would
// be created outside of segment, which breaks seeking.
gopArg = string . Format (
CultureInfo . InvariantCulture ,
2022-06-06 17:29:39 +02:00
" -g:v:0 {0} -keyint_min:v:0 {0}" ,
2020-11-19 15:46:02 +01:00
Math . Ceiling ( segmentLength * framerate . Value ) ) ;
}
// Unable to force key frames using these encoders, set key frames by GOP.
if ( string . Equals ( codec , "h264_qsv" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( codec , "h264_nvenc" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( codec , "h264_amf" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( codec , "hevc_qsv" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( codec , "hevc_nvenc" , StringComparison . OrdinalIgnoreCase )
2023-06-19 21:49:26 +02:00
| | string . Equals ( codec , "av1_qsv" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( codec , "av1_nvenc" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( codec , "av1_amf" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( codec , "libsvtav1" , StringComparison . OrdinalIgnoreCase ) )
2020-11-19 15:46:02 +01:00
{
args + = gopArg ;
}
else if ( string . Equals ( codec , "libx264" , StringComparison . OrdinalIgnoreCase )
2020-11-20 08:06:28 +01:00
| | string . Equals ( codec , "libx265" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( codec , "h264_vaapi" , StringComparison . OrdinalIgnoreCase )
2023-06-19 21:49:26 +02:00
| | string . Equals ( codec , "hevc_vaapi" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( codec , "av1_vaapi" , StringComparison . OrdinalIgnoreCase ) )
2020-11-19 15:46:02 +01:00
{
2021-12-01 17:49:50 +01:00
args + = keyFrameArg ;
2022-06-06 17:29:39 +02:00
// prevent the libx264 from post processing to break the set keyframe.
if ( string . Equals ( codec , "libx264" , StringComparison . OrdinalIgnoreCase ) )
{
args + = " -sc_threshold:v:0 0" ;
}
2020-11-19 15:46:02 +01:00
}
else
{
2021-12-01 17:49:50 +01:00
args + = keyFrameArg + gopArg ;
2020-11-19 15:46:02 +01:00
}
2023-07-29 14:52:58 +02:00
// global_header produced by AMD HEVC VA-API encoder causes non-playable fMP4 on iOS
if ( string . Equals ( codec , "hevc_vaapi" , StringComparison . OrdinalIgnoreCase )
2023-07-02 07:41:17 +02:00
& & _mediaEncoder . IsVaapiDeviceAmd )
{
args + = " -flags:v -global_header" ;
}
2020-11-19 15:46:02 +01:00
return args ;
}
2018-12-28 00:27:57 +01:00
/// <summary>
2020-06-16 00:37:52 +02:00
/// Gets the video bitrate to specify on the command line.
2018-12-28 00:27:57 +01:00
/// </summary>
2021-08-10 23:29:48 +02:00
/// <param name="state">Encoding state.</param>
/// <param name="videoEncoder">Video encoder to use.</param>
/// <param name="encodingOptions">Encoding options.</param>
/// <param name="defaultPreset">Default present to use for encoding.</param>
/// <returns>Video bitrate.</returns>
2019-06-02 00:03:48 +02:00
public string GetVideoQualityParam ( EncodingJobInfo state , string videoEncoder , EncodingOptions encodingOptions , string defaultPreset )
2018-12-28 00:27:57 +01:00
{
var param = string . Empty ;
2021-12-01 17:49:50 +01:00
// Tutorials: Enable Intel GuC / HuC firmware loading for Low Power Encoding.
2023-04-16 19:10:14 +02:00
// https://01.org/group/43/downloads/firmware
2021-12-01 17:49:50 +01:00
// https://wiki.archlinux.org/title/intel_graphics#Enable_GuC_/_HuC_firmware_loading
// Intel Low Power Encoding can save unnecessary CPU-GPU synchronization,
// which will reduce overhead in performance intensive tasks such as 4k transcoding and tonemapping.
var intelLowPowerHwEncoding = false ;
2023-01-22 20:05:00 +01:00
// Workaround for linux 5.18 to 6.1.3 i915 hang at cost of performance.
2022-08-01 20:25:43 +02:00
// https://github.com/intel/media-driver/issues/1456
var enableWaFori915Hang = false ;
2021-12-01 17:49:50 +01:00
if ( string . Equals ( encodingOptions . HardwareAccelerationType , "vaapi" , StringComparison . OrdinalIgnoreCase ) )
{
2021-12-24 09:50:40 +01:00
var isIntelVaapiDriver = _mediaEncoder . IsVaapiDeviceInteliHD | | _mediaEncoder . IsVaapiDeviceInteli965 ;
2021-12-01 17:49:50 +01:00
if ( string . Equals ( videoEncoder , "h264_vaapi" , StringComparison . OrdinalIgnoreCase ) )
{
intelLowPowerHwEncoding = encodingOptions . EnableIntelLowPowerH264HwEncoder & & isIntelVaapiDriver ;
}
else if ( string . Equals ( videoEncoder , "hevc_vaapi" , StringComparison . OrdinalIgnoreCase ) )
{
intelLowPowerHwEncoding = encodingOptions . EnableIntelLowPowerHevcHwEncoder & & isIntelVaapiDriver ;
}
}
else if ( string . Equals ( encodingOptions . HardwareAccelerationType , "qsv" , StringComparison . OrdinalIgnoreCase ) )
{
2023-01-22 20:05:00 +01:00
if ( OperatingSystem . IsLinux ( ) )
2022-08-01 20:25:43 +02:00
{
2023-01-22 20:05:00 +01:00
var ver = Environment . OSVersion . Version ;
var isFixedKernel60 = ver . Major = = 6 & & ver . Minor = = 0 & & ver > = _minFixedKernel60i915Hang ;
var isUnaffectedKernel = ver < _minKerneli915Hang | | ver > _maxKerneli915Hang ;
if ( ! ( isUnaffectedKernel | | isFixedKernel60 ) )
{
var vidDecoder = GetHardwareVideoDecoder ( state , encodingOptions ) ? ? string . Empty ;
var isIntelDecoder = vidDecoder . Contains ( "qsv" , StringComparison . OrdinalIgnoreCase )
| | vidDecoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
var doOclTonemap = _mediaEncoder . SupportsHwaccel ( "qsv" )
& & IsVaapiSupported ( state )
& & IsOpenclFullSupported ( )
& & ! IsVaapiVppTonemapAvailable ( state , encodingOptions )
& & IsHwTonemapAvailable ( state , encodingOptions ) ;
enableWaFori915Hang = isIntelDecoder & & doOclTonemap ;
}
2022-08-01 20:25:43 +02:00
}
2021-12-01 17:49:50 +01:00
if ( string . Equals ( videoEncoder , "h264_qsv" , StringComparison . OrdinalIgnoreCase ) )
{
intelLowPowerHwEncoding = encodingOptions . EnableIntelLowPowerH264HwEncoder ;
}
else if ( string . Equals ( videoEncoder , "hevc_qsv" , StringComparison . OrdinalIgnoreCase ) )
{
intelLowPowerHwEncoding = encodingOptions . EnableIntelLowPowerHevcHwEncoder ;
2020-11-19 15:46:02 +01:00
}
2022-08-01 20:25:43 +02:00
else
{
enableWaFori915Hang = false ;
}
2020-11-19 15:46:02 +01:00
}
2021-12-01 17:49:50 +01:00
if ( intelLowPowerHwEncoding )
{
param + = " -low_power 1" ;
}
2022-08-01 20:25:43 +02:00
if ( enableWaFori915Hang )
{
param + = " -async_depth 1" ;
}
2022-01-07 05:49:13 +01:00
var isVc1 = string . Equals ( state . VideoStream ? . Codec , "vc1" , StringComparison . OrdinalIgnoreCase ) ;
2019-06-02 00:03:48 +02:00
var isLibX265 = string . Equals ( videoEncoder , "libx265" , StringComparison . OrdinalIgnoreCase ) ;
2018-12-28 00:27:57 +01:00
2019-06-02 00:03:48 +02:00
if ( string . Equals ( videoEncoder , "libx264" , StringComparison . OrdinalIgnoreCase ) | | isLibX265 )
2018-12-28 00:27:57 +01:00
{
2019-06-02 00:03:48 +02:00
if ( ! string . IsNullOrEmpty ( encodingOptions . EncoderPreset ) )
2018-12-28 00:27:57 +01:00
{
2020-11-19 15:46:02 +01:00
param + = " -preset " + encodingOptions . EncoderPreset ;
2018-12-28 00:27:57 +01:00
}
else
{
2020-11-19 15:46:02 +01:00
param + = " -preset " + defaultPreset ;
2018-12-28 00:27:57 +01:00
}
2019-06-02 00:03:48 +02:00
int encodeCrf = encodingOptions . H264Crf ;
if ( isLibX265 )
2018-12-28 00:27:57 +01:00
{
2019-06-02 00:03:48 +02:00
encodeCrf = encodingOptions . H265Crf ;
}
2019-09-01 18:39:23 +02:00
2019-06-02 00:03:48 +02:00
if ( encodeCrf > = 0 & & encodeCrf < = 51 )
{
param + = " -crf " + encodeCrf . ToString ( CultureInfo . InvariantCulture ) ;
2018-12-28 00:27:57 +01:00
}
else
{
2019-06-02 00:03:48 +02:00
string defaultCrf = "23" ;
if ( isLibX265 )
{
defaultCrf = "28" ;
}
2019-09-01 18:39:23 +02:00
2019-06-02 00:03:48 +02:00
param + = " -crf " + defaultCrf ;
2018-12-28 00:27:57 +01:00
}
}
2023-06-19 21:49:26 +02:00
else if ( string . Equals ( videoEncoder , "libsvtav1" , StringComparison . OrdinalIgnoreCase ) )
{
// Default to use the recommended preset 10.
// Omit presets < 5, which are too slow for on the fly encoding.
// https://gitlab.com/AOMediaCodec/SVT-AV1/-/blob/master/Docs/Ffmpeg.md
param + = encodingOptions . EncoderPreset switch
{
"veryslow" = > " -preset 5" ,
"slower" = > " -preset 6" ,
"slow" = > " -preset 7" ,
"medium" = > " -preset 8" ,
"fast" = > " -preset 9" ,
"faster" = > " -preset 10" ,
"veryfast" = > " -preset 11" ,
"superfast" = > " -preset 12" ,
"ultrafast" = > " -preset 13" ,
_ = > " -preset 10"
} ;
}
else if ( string . Equals ( videoEncoder , "h264_vaapi" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoEncoder , "hevc_vaapi" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoEncoder , "av1_vaapi" , StringComparison . OrdinalIgnoreCase ) )
{
// -compression_level is not reliable on AMD.
if ( _mediaEncoder . IsVaapiDeviceInteliHD )
{
param + = encodingOptions . EncoderPreset switch
{
"veryslow" = > " -compression_level 1" ,
"slower" = > " -compression_level 2" ,
"slow" = > " -compression_level 3" ,
"medium" = > " -compression_level 4" ,
"fast" = > " -compression_level 5" ,
"faster" = > " -compression_level 6" ,
"veryfast" = > " -compression_level 7" ,
"superfast" = > " -compression_level 7" ,
"ultrafast" = > " -compression_level 7" ,
_ = > string . Empty
} ;
}
}
2020-11-07 18:39:32 +01:00
else if ( string . Equals ( videoEncoder , "h264_qsv" , StringComparison . OrdinalIgnoreCase ) // h264 (h264_qsv)
2023-06-19 21:49:26 +02:00
| | string . Equals ( videoEncoder , "hevc_qsv" , StringComparison . OrdinalIgnoreCase ) // hevc (hevc_qsv)
| | string . Equals ( videoEncoder , "av1_qsv" , StringComparison . OrdinalIgnoreCase ) ) // av1 (av1_qsv)
2018-12-28 00:27:57 +01:00
{
2023-06-19 21:49:26 +02:00
string [ ] valid_presets = { "veryslow" , "slower" , "slow" , "medium" , "fast" , "faster" , "veryfast" } ;
2018-12-28 00:27:57 +01:00
2023-06-19 21:49:26 +02:00
if ( valid_presets . Contains ( encodingOptions . EncoderPreset , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
2020-11-19 15:46:02 +01:00
param + = " -preset " + encodingOptions . EncoderPreset ;
2018-12-28 00:27:57 +01:00
}
else
{
2023-06-19 21:49:26 +02:00
param + = " -preset veryfast" ;
2018-12-28 00:27:57 +01:00
}
2022-10-29 04:39:01 +02:00
// Only h264_qsv has look_ahead option
if ( string . Equals ( videoEncoder , "h264_qsv" , StringComparison . OrdinalIgnoreCase ) )
{
param + = " -look_ahead 0" ;
}
2018-12-28 00:27:57 +01:00
}
2019-09-01 18:39:23 +02:00
else if ( string . Equals ( videoEncoder , "h264_nvenc" , StringComparison . OrdinalIgnoreCase ) // h264 (h264_nvenc)
2023-06-19 21:49:26 +02:00
| | string . Equals ( videoEncoder , "hevc_nvenc" , StringComparison . OrdinalIgnoreCase ) // hevc (hevc_nvenc)
| | string . Equals ( videoEncoder , "av1_nvenc" , StringComparison . OrdinalIgnoreCase ) ) // av1 (av1_nvenc)
2018-12-28 00:27:57 +01:00
{
2019-06-02 00:03:48 +02:00
switch ( encodingOptions . EncoderPreset )
2018-12-28 00:27:57 +01:00
{
case "veryslow" :
2022-02-28 16:05:08 +01:00
param + = " -preset p7" ;
2018-12-28 00:27:57 +01:00
break ;
2023-06-13 16:44:06 +02:00
case "slower" :
2022-02-28 16:05:08 +01:00
param + = " -preset p6" ;
break ;
2023-06-13 16:44:06 +02:00
case "slow" :
2022-02-28 16:05:08 +01:00
param + = " -preset p5" ;
2018-12-28 00:27:57 +01:00
break ;
case "medium" :
2022-02-28 16:05:08 +01:00
param + = " -preset p4" ;
2018-12-28 00:27:57 +01:00
break ;
case "fast" :
2022-02-28 16:05:08 +01:00
param + = " -preset p3" ;
break ;
2018-12-28 00:27:57 +01:00
case "faster" :
2022-02-28 16:05:08 +01:00
param + = " -preset p2" ;
break ;
2018-12-28 00:27:57 +01:00
case "veryfast" :
case "superfast" :
case "ultrafast" :
2022-02-28 16:05:08 +01:00
param + = " -preset p1" ;
2018-12-28 00:27:57 +01:00
break ;
default :
2022-10-29 04:39:01 +02:00
param + = " -preset p1" ;
2018-12-28 00:27:57 +01:00
break ;
}
}
2020-11-07 18:39:32 +01:00
else if ( string . Equals ( videoEncoder , "h264_amf" , StringComparison . OrdinalIgnoreCase ) // h264 (h264_amf)
2023-06-19 21:49:26 +02:00
| | string . Equals ( videoEncoder , "hevc_amf" , StringComparison . OrdinalIgnoreCase ) // hevc (hevc_amf)
| | string . Equals ( videoEncoder , "av1_amf" , StringComparison . OrdinalIgnoreCase ) ) // av1 (av1_amf)
2020-07-16 15:09:04 +02:00
{
switch ( encodingOptions . EncoderPreset )
{
case "veryslow" :
case "slower" :
2023-06-13 16:44:06 +02:00
case "slow" :
2020-11-19 15:46:02 +01:00
param + = " -quality quality" ;
2020-07-16 15:09:04 +02:00
break ;
case "medium" :
2020-11-19 15:46:02 +01:00
param + = " -quality balanced" ;
2020-07-16 15:09:04 +02:00
break ;
case "fast" :
case "faster" :
case "veryfast" :
case "superfast" :
case "ultrafast" :
2020-11-19 15:46:02 +01:00
param + = " -quality speed" ;
2020-07-16 15:09:04 +02:00
break ;
default :
2020-11-19 15:46:02 +01:00
param + = " -quality speed" ;
2020-07-16 15:09:04 +02:00
break ;
}
2020-10-03 11:53:10 +02:00
2023-06-19 21:49:26 +02:00
if ( string . Equals ( videoEncoder , "hevc_amf" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoEncoder , "av1_amf" , StringComparison . OrdinalIgnoreCase ) )
{
param + = " -header_insertion_mode gop" ;
}
2020-11-07 18:39:32 +01:00
if ( string . Equals ( videoEncoder , "hevc_amf" , StringComparison . OrdinalIgnoreCase ) )
{
2023-06-19 21:49:26 +02:00
param + = " -gops_per_idr 1" ;
2020-11-07 18:39:32 +01:00
}
2020-07-16 15:09:04 +02:00
}
2021-08-20 20:22:21 +02:00
else if ( string . Equals ( videoEncoder , "libvpx" , StringComparison . OrdinalIgnoreCase ) ) // vp8
2018-12-28 00:27:57 +01:00
{
// Values 0-3, 0 being highest quality but slower
var profileScore = 0 ;
string crf ;
var qmin = "0" ;
var qmax = "50" ;
crf = "10" ;
if ( isVc1 )
{
profileScore + + ;
}
// Max of 2
profileScore = Math . Min ( profileScore , 2 ) ;
// http://www.webmproject.org/docs/encoder-parameters/
2021-06-06 17:16:41 +02:00
param + = string . Format (
CultureInfo . InvariantCulture ,
" -speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}" ,
2021-09-26 16:14:36 +02:00
profileScore . ToString ( CultureInfo . InvariantCulture ) ,
2018-12-28 00:27:57 +01:00
crf ,
qmin ,
qmax ) ;
}
2021-08-20 20:22:21 +02:00
else if ( string . Equals ( videoEncoder , "libvpx-vp9" , StringComparison . OrdinalIgnoreCase ) ) // vp9
{
// When `-deadline` is set to `good` or `best`, `-cpu-used` ranges from 0-5.
// When `-deadline` is set to `realtime`, `-cpu-used` ranges from 0-15.
// Resources:
// * https://trac.ffmpeg.org/wiki/Encode/VP9
// * https://superuser.com/questions/1586934
// * https://developers.google.com/media/vp9
param + = encodingOptions . EncoderPreset switch
{
"veryslow" = > " -deadline best -cpu-used 0" ,
"slower" = > " -deadline best -cpu-used 2" ,
"slow" = > " -deadline best -cpu-used 3" ,
"medium" = > " -deadline good -cpu-used 0" ,
"fast" = > " -deadline good -cpu-used 1" ,
"faster" = > " -deadline good -cpu-used 2" ,
"veryfast" = > " -deadline good -cpu-used 3" ,
"superfast" = > " -deadline good -cpu-used 4" ,
"ultrafast" = > " -deadline good -cpu-used 5" ,
_ = > " -deadline good -cpu-used 1"
} ;
// TODO: until VP9 gets its own CRF setting, base CRF on H.265.
int h265Crf = encodingOptions . H265Crf ;
int defaultVp9Crf = 31 ;
if ( h265Crf > = 0 & & h265Crf < = 51 )
{
// This conversion factor is chosen to match the default CRF for H.265 to the
// recommended 1080p CRF from Google. The factor also maps the logarithmic CRF
// scale of x265 [0, 51] to that of VP9 [0, 63] relatively well.
// Resources:
// * https://developers.google.com/media/vp9/settings/vod
const float H265ToVp9CrfConversionFactor = 1.12F ;
var vp9Crf = Convert . ToInt32 ( h265Crf * H265ToVp9CrfConversionFactor ) ;
// Encoder allows for CRF values in the range [0, 63].
vp9Crf = Math . Clamp ( vp9Crf , 0 , 63 ) ;
param + = FormattableString . Invariant ( $" -crf {vp9Crf}" ) ;
}
else
{
param + = FormattableString . Invariant ( $" -crf {defaultVp9Crf}" ) ;
}
param + = " -row-mt 1 -profile 1" ;
}
2018-12-28 00:27:57 +01:00
else if ( string . Equals ( videoEncoder , "mpeg4" , StringComparison . OrdinalIgnoreCase ) )
{
2020-11-19 15:46:02 +01:00
param + = " -mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2" ;
2018-12-28 00:27:57 +01:00
}
2019-09-01 18:39:23 +02:00
else if ( string . Equals ( videoEncoder , "wmv2" , StringComparison . OrdinalIgnoreCase ) ) // asf/wmv
2018-12-28 00:27:57 +01:00
{
2020-11-19 15:46:02 +01:00
param + = " -qmin 2" ;
2018-12-28 00:27:57 +01:00
}
else if ( string . Equals ( videoEncoder , "msmpeg4" , StringComparison . OrdinalIgnoreCase ) )
{
2020-11-19 15:46:02 +01:00
param + = " -mbd 2" ;
2018-12-28 00:27:57 +01:00
}
param + = GetVideoBitrateParam ( state , videoEncoder ) ;
var framerate = GetFramerateParam ( state ) ;
if ( framerate . HasValue )
{
2021-09-26 16:14:36 +02:00
param + = string . Format ( CultureInfo . InvariantCulture , " -r {0}" , framerate . Value . ToString ( CultureInfo . InvariantCulture ) ) ;
2018-12-28 00:27:57 +01:00
}
var targetVideoCodec = state . ActualOutputVideoCodec ;
2020-11-07 18:39:32 +01:00
if ( string . Equals ( targetVideoCodec , "h265" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( targetVideoCodec , "hevc" , StringComparison . OrdinalIgnoreCase ) )
{
targetVideoCodec = "hevc" ;
}
2018-12-28 00:27:57 +01:00
2020-12-18 18:47:31 +01:00
var profile = state . GetRequestedProfiles ( targetVideoCodec ) . FirstOrDefault ( ) ? ? string . Empty ;
2023-05-22 22:48:09 +02:00
profile = WhiteSpaceRegex ( ) . Replace ( profile , string . Empty ) ;
2020-11-07 18:39:32 +01:00
2020-12-17 16:33:44 +01:00
// We only transcode to HEVC 8-bit for now, force Main Profile.
2020-12-23 18:32:23 +01:00
if ( profile . Contains ( "main10" , StringComparison . OrdinalIgnoreCase )
| | profile . Contains ( "mainstill" , StringComparison . OrdinalIgnoreCase ) )
2020-12-17 16:33:44 +01:00
{
profile = "main" ;
}
// Extended Profile is not supported by any known h264 encoders, force Main Profile.
if ( profile . Contains ( "extended" , StringComparison . OrdinalIgnoreCase ) )
{
profile = "main" ;
}
2020-11-11 03:03:53 +01:00
// Only libx264 support encoding H264 High 10 Profile, otherwise force High Profile.
2020-11-07 18:39:32 +01:00
if ( ! string . Equals ( videoEncoder , "libx264" , StringComparison . OrdinalIgnoreCase )
2020-12-23 18:32:23 +01:00
& & profile . Contains ( "high10" , StringComparison . OrdinalIgnoreCase ) )
2020-11-07 18:39:32 +01:00
{
profile = "high" ;
}
2018-12-16 17:36:08 +01:00
2023-06-19 21:49:26 +02:00
// We only need Main profile of AV1 encoders.
if ( videoEncoder . Contains ( "av1" , StringComparison . OrdinalIgnoreCase )
& & ( profile . Contains ( "high" , StringComparison . OrdinalIgnoreCase )
| | profile . Contains ( "professional" , StringComparison . OrdinalIgnoreCase ) ) )
{
profile = "main" ;
}
2020-11-07 18:39:32 +01:00
// h264_vaapi does not support Baseline profile, force Constrained Baseline in this case,
2020-11-11 03:03:53 +01:00
// which is compatible (and ugly).
2019-09-01 18:39:23 +02:00
if ( string . Equals ( videoEncoder , "h264_vaapi" , StringComparison . OrdinalIgnoreCase )
2020-12-17 16:33:44 +01:00
& & profile . Contains ( "baseline" , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
profile = "constrained_baseline" ;
2018-12-28 00:27:57 +01:00
}
2018-12-16 17:36:08 +01:00
2020-11-11 03:03:53 +01:00
// libx264, h264_qsv and h264_nvenc does not support Constrained Baseline profile, force Baseline in this case.
2020-11-07 18:39:32 +01:00
if ( ( string . Equals ( videoEncoder , "libx264" , StringComparison . OrdinalIgnoreCase )
2020-11-20 08:06:28 +01:00
| | string . Equals ( videoEncoder , "h264_qsv" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoEncoder , "h264_nvenc" , StringComparison . OrdinalIgnoreCase ) )
2020-12-17 16:33:44 +01:00
& & profile . Contains ( "baseline" , StringComparison . OrdinalIgnoreCase ) )
2020-11-07 18:39:32 +01:00
{
profile = "baseline" ;
}
2020-12-17 16:33:44 +01:00
// libx264, h264_qsv, h264_nvenc and h264_vaapi does not support Constrained High profile, force High in this case.
if ( ( string . Equals ( videoEncoder , "libx264" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoEncoder , "h264_qsv" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoEncoder , "h264_nvenc" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoEncoder , "h264_vaapi" , StringComparison . OrdinalIgnoreCase ) )
& & profile . Contains ( "high" , StringComparison . OrdinalIgnoreCase ) )
{
profile = "high" ;
}
2020-12-23 18:32:23 +01:00
if ( string . Equals ( videoEncoder , "h264_amf" , StringComparison . OrdinalIgnoreCase )
2021-05-16 12:40:28 +02:00
& & profile . Contains ( "baseline" , StringComparison . OrdinalIgnoreCase ) )
2020-12-23 18:32:23 +01:00
{
profile = "constrained_baseline" ;
}
if ( string . Equals ( videoEncoder , "h264_amf" , StringComparison . OrdinalIgnoreCase )
& & profile . Contains ( "constrainedhigh" , StringComparison . OrdinalIgnoreCase ) )
{
profile = "constrained_high" ;
}
2018-12-16 17:36:08 +01:00
if ( ! string . IsNullOrEmpty ( profile ) )
2018-12-28 00:27:57 +01:00
{
2022-03-05 14:47:59 +01:00
if ( ! string . Equals ( videoEncoder , "h264_v4l2m2m" , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
2020-11-19 15:46:02 +01:00
param + = " -profile:v:0 " + profile ;
2018-12-28 00:27:57 +01:00
}
}
var level = state . GetRequestedLevel ( targetVideoCodec ) ;
if ( ! string . IsNullOrEmpty ( level ) )
{
2020-11-07 18:39:32 +01:00
level = NormalizeTranscodingLevel ( state , level ) ;
2018-12-28 00:27:57 +01:00
2021-12-01 17:49:50 +01:00
// libx264, QSV, AMF can adjust the given level to match the output.
2019-09-01 18:39:23 +02:00
if ( string . Equals ( videoEncoder , "h264_qsv" , StringComparison . OrdinalIgnoreCase )
2020-11-07 18:39:32 +01:00
| | string . Equals ( videoEncoder , "libx264" , StringComparison . OrdinalIgnoreCase ) )
{
param + = " -level " + level ;
}
else if ( string . Equals ( videoEncoder , "hevc_qsv" , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
2020-11-11 03:03:53 +01:00
// hevc_qsv use -level 51 instead of -level 153.
2023-02-19 16:52:29 +01:00
if ( double . TryParse ( level , CultureInfo . InvariantCulture , out double hevcLevel ) )
2018-12-28 00:27:57 +01:00
{
2021-06-06 17:16:41 +02:00
param + = " -level " + ( hevcLevel / 3 ) ;
2018-12-28 00:27:57 +01:00
}
}
2023-06-19 21:49:26 +02:00
else if ( string . Equals ( videoEncoder , "av1_qsv" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoEncoder , "libsvtav1" , StringComparison . OrdinalIgnoreCase ) )
{
// libsvtav1 and av1_qsv use -level 60 instead of -level 16
// https://aomedia.org/av1/specification/annex-a/
if ( int . TryParse ( level , NumberStyles . Any , CultureInfo . InvariantCulture , out int av1Level ) )
{
var x = 2 + ( av1Level > > 2 ) ;
var y = av1Level & 3 ;
var res = ( x * 10 ) + y ;
param + = " -level " + res ;
}
}
2020-11-07 18:39:32 +01:00
else if ( string . Equals ( videoEncoder , "h264_amf" , StringComparison . OrdinalIgnoreCase )
2023-06-19 21:49:26 +02:00
| | string . Equals ( videoEncoder , "hevc_amf" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoEncoder , "av1_amf" , StringComparison . OrdinalIgnoreCase ) )
2020-11-07 18:39:32 +01:00
{
param + = " -level " + level ;
}
2019-09-01 18:39:23 +02:00
else if ( string . Equals ( videoEncoder , "h264_nvenc" , StringComparison . OrdinalIgnoreCase )
2021-12-24 09:50:40 +01:00
| | string . Equals ( videoEncoder , "hevc_nvenc" , StringComparison . OrdinalIgnoreCase )
2023-06-19 21:49:26 +02:00
| | string . Equals ( videoEncoder , "av1_nvenc" , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
2020-11-07 18:39:32 +01:00
// level option may cause NVENC to fail.
// NVENC cannot adjust the given level, just throw an error.
2023-06-19 21:49:26 +02:00
}
else if ( string . Equals ( videoEncoder , "h264_vaapi" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoEncoder , "hevc_vaapi" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoEncoder , "av1_vaapi" , StringComparison . OrdinalIgnoreCase ) )
{
2021-12-01 17:49:50 +01:00
// level option may cause corrupted frames on AMD VAAPI.
2023-06-19 21:49:26 +02:00
if ( _mediaEncoder . IsVaapiDeviceInteliHD | | _mediaEncoder . IsVaapiDeviceInteli965 )
{
param + = " -level " + level ;
}
2021-12-01 17:49:50 +01:00
}
2022-03-05 14:47:59 +01:00
else if ( ! string . Equals ( videoEncoder , "libx265" , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
param + = " -level " + level ;
}
}
if ( string . Equals ( videoEncoder , "libx264" , StringComparison . OrdinalIgnoreCase ) )
{
param + = " -x264opts:0 subme=0:me_range=4:rc_lookahead=10:me=dia:no_chroma_me:8x8dct=0:partitions=none" ;
}
2019-06-02 00:03:48 +02:00
if ( string . Equals ( videoEncoder , "libx265" , StringComparison . OrdinalIgnoreCase ) )
{
2020-11-11 03:03:53 +01:00
// libx265 only accept level option in -x265-params.
// level option may cause libx265 to fail.
// libx265 cannot adjust the given level, just throw an error.
// TODO: set fine tuned params.
2020-11-07 18:39:32 +01:00
param + = " -x265-params:0 no-info=1" ;
2019-06-02 00:03:48 +02:00
}
2023-06-19 21:49:26 +02:00
if ( string . Equals ( videoEncoder , "libsvtav1" , StringComparison . OrdinalIgnoreCase )
& & _mediaEncoder . EncoderVersion > = _minFFmpegSvtAv1Params )
{
param + = " -svtav1-params:0 rc=1:tune=0:film-grain=0:enable-overlays=1:enable-tf=0" ;
}
2018-12-28 00:27:57 +01:00
return param ;
}
public bool CanStreamCopyVideo ( EncodingJobInfo state , MediaStream videoStream )
{
var request = state . BaseRequest ;
if ( ! request . AllowVideoStreamCopy )
{
return false ;
}
2019-09-01 18:39:23 +02:00
if ( videoStream . IsInterlaced
& & state . DeInterlace ( videoStream . Codec , false ) )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
return false ;
2018-12-28 00:27:57 +01:00
}
if ( videoStream . IsAnamorphic ? ? false )
{
if ( request . RequireNonAnamorphic )
{
return false ;
}
}
// Can't stream copy if we're burning in subtitles
2019-09-01 18:39:23 +02:00
if ( request . SubtitleStreamIndex . HasValue
2022-07-21 01:29:06 +02:00
& & request . SubtitleStreamIndex . Value > = 0
2019-09-01 18:39:23 +02:00
& & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
return false ;
2018-12-28 00:27:57 +01:00
}
2019-09-01 18:39:23 +02:00
if ( string . Equals ( "h264" , videoStream . Codec , StringComparison . OrdinalIgnoreCase )
& & videoStream . IsAVC . HasValue
& & ! videoStream . IsAVC . Value
& & request . RequireAvc )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
return false ;
2018-12-28 00:27:57 +01:00
}
// Source and target codecs must match
2019-09-01 18:39:23 +02:00
if ( string . IsNullOrEmpty ( videoStream . Codec )
2022-02-21 13:54:13 +01:00
| | ( state . SupportedVideoCodecs . Length ! = 0
& & ! state . SupportedVideoCodecs . Contains ( videoStream . Codec , StringComparison . OrdinalIgnoreCase ) ) )
2018-12-28 00:27:57 +01:00
{
return false ;
}
var requestedProfiles = state . GetRequestedProfiles ( videoStream . Codec ) ;
// If client is requesting a specific video profile, it must match the source
if ( requestedProfiles . Length > 0 )
{
if ( string . IsNullOrEmpty ( videoStream . Profile ) )
{
2020-06-14 11:11:11 +02:00
// return false;
2018-12-28 00:27:57 +01:00
}
var requestedProfile = requestedProfiles [ 0 ] ;
// strip spaces because they may be stripped out on the query string as well
2021-02-13 00:39:18 +01:00
if ( ! string . IsNullOrEmpty ( videoStream . Profile )
2022-01-08 15:31:45 +01:00
& & ! requestedProfiles . Contains ( videoStream . Profile . Replace ( " " , string . Empty , StringComparison . Ordinal ) , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
var currentScore = GetVideoProfileScore ( videoStream . Codec , videoStream . Profile ) ;
var requestedScore = GetVideoProfileScore ( videoStream . Codec , requestedProfile ) ;
2018-12-28 00:27:57 +01:00
if ( currentScore = = - 1 | | currentScore > requestedScore )
{
return false ;
}
}
}
2022-06-17 18:01:06 +02:00
var requestedRangeTypes = state . GetRequestedRangeTypes ( videoStream . Codec ) ;
2022-07-21 01:29:06 +02:00
if ( requestedRangeTypes . Length > 0 )
2022-06-17 18:01:06 +02:00
{
2023-06-15 13:28:01 +02:00
if ( videoStream . VideoRangeType = = VideoRangeType . Unknown )
2022-06-17 18:01:06 +02:00
{
return false ;
}
2023-06-15 13:28:01 +02:00
if ( ! requestedRangeTypes . Contains ( videoStream . VideoRangeType . ToString ( ) , StringComparison . OrdinalIgnoreCase ) )
2022-06-17 18:01:06 +02:00
{
return false ;
}
}
2018-12-28 00:27:57 +01:00
// Video width must fall within requested value
2019-09-01 18:39:23 +02:00
if ( request . MaxWidth . HasValue
& & ( ! videoStream . Width . HasValue | | videoStream . Width . Value > request . MaxWidth . Value ) )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
return false ;
2018-12-28 00:27:57 +01:00
}
// Video height must fall within requested value
2019-09-01 18:39:23 +02:00
if ( request . MaxHeight . HasValue
& & ( ! videoStream . Height . HasValue | | videoStream . Height . Value > request . MaxHeight . Value ) )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
return false ;
2018-12-28 00:27:57 +01:00
}
// Video framerate must fall within requested value
var requestedFramerate = request . MaxFramerate ? ? request . Framerate ;
if ( requestedFramerate . HasValue )
{
var videoFrameRate = videoStream . AverageFrameRate ? ? videoStream . RealFrameRate ;
if ( ! videoFrameRate . HasValue | | videoFrameRate . Value > requestedFramerate . Value )
{
return false ;
}
}
// Video bitrate must fall within requested value
2019-09-01 18:39:23 +02:00
if ( request . VideoBitRate . HasValue
& & ( ! videoStream . BitRate . HasValue | | videoStream . BitRate . Value > request . VideoBitRate . Value ) )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
return false ;
2018-12-28 00:27:57 +01:00
}
var maxBitDepth = state . GetRequestedVideoBitDepth ( videoStream . Codec ) ;
if ( maxBitDepth . HasValue )
{
if ( videoStream . BitDepth . HasValue & & videoStream . BitDepth . Value > maxBitDepth . Value )
{
return false ;
}
}
var maxRefFrames = state . GetRequestedMaxRefFrames ( videoStream . Codec ) ;
2019-09-01 18:39:23 +02:00
if ( maxRefFrames . HasValue
& & videoStream . RefFrames . HasValue & & videoStream . RefFrames . Value > maxRefFrames . Value )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
return false ;
2018-12-28 00:27:57 +01:00
}
// If a specific level was requested, the source must match or be less than
var level = state . GetRequestedLevel ( videoStream . Codec ) ;
2023-02-19 16:52:29 +01:00
if ( double . TryParse ( level , CultureInfo . InvariantCulture , out var requestLevel ) )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
if ( ! videoStream . Level . HasValue )
2018-12-28 00:27:57 +01:00
{
2020-06-14 11:11:11 +02:00
// return false;
2019-09-01 18:39:23 +02:00
}
2018-12-28 00:27:57 +01:00
2019-09-01 18:39:23 +02:00
if ( videoStream . Level . HasValue & & videoStream . Level . Value > requestLevel )
{
return false ;
2018-12-28 00:27:57 +01:00
}
}
2019-09-01 18:39:23 +02:00
if ( string . Equals ( state . InputContainer , "avi" , StringComparison . OrdinalIgnoreCase )
& & string . Equals ( videoStream . Codec , "h264" , StringComparison . OrdinalIgnoreCase )
& & ! ( videoStream . IsAVC ? ? false ) )
2018-12-28 00:27:57 +01:00
{
// see Coach S01E01 - Kelly and the Professor(0).avi
return false ;
}
2022-01-24 00:49:14 +01:00
return true ;
2018-12-28 00:27:57 +01:00
}
2019-09-01 18:39:23 +02:00
public bool CanStreamCopyAudio ( EncodingJobInfo state , MediaStream audioStream , IEnumerable < string > supportedAudioCodecs )
2018-12-28 00:27:57 +01:00
{
var request = state . BaseRequest ;
if ( ! request . AllowAudioStreamCopy )
{
return false ;
}
var maxBitDepth = state . GetRequestedAudioBitDepth ( audioStream . Codec ) ;
2019-09-01 18:39:23 +02:00
if ( maxBitDepth . HasValue
& & audioStream . BitDepth . HasValue
& & audioStream . BitDepth . Value > maxBitDepth . Value )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
return false ;
2018-12-28 00:27:57 +01:00
}
// Source and target codecs must match
2019-09-01 18:39:23 +02:00
if ( string . IsNullOrEmpty ( audioStream . Codec )
2022-01-08 15:31:45 +01:00
| | ! supportedAudioCodecs . Contains ( audioStream . Codec , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
return false ;
}
// Channels must fall within requested value
var channels = state . GetRequestedAudioChannels ( audioStream . Codec ) ;
if ( channels . HasValue )
{
if ( ! audioStream . Channels . HasValue | | audioStream . Channels . Value < = 0 )
{
return false ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( audioStream . Channels . Value > channels . Value )
{
return false ;
}
}
// Sample rate must fall within requested value
if ( request . AudioSampleRate . HasValue )
{
if ( ! audioStream . SampleRate . HasValue | | audioStream . SampleRate . Value < = 0 )
{
return false ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( audioStream . SampleRate . Value > request . AudioSampleRate . Value )
{
return false ;
}
}
2023-03-17 11:49:07 +01:00
// Audio bitrate must fall within requested value
2022-01-24 00:49:14 +01:00
if ( request . AudioBitRate . HasValue
2023-03-17 11:49:07 +01:00
& & audioStream . BitRate . HasValue
2022-01-24 00:49:14 +01:00
& & audioStream . BitRate . Value > request . AudioBitRate . Value )
2018-12-28 00:27:57 +01:00
{
2022-01-24 00:49:14 +01:00
return false ;
2018-12-28 00:27:57 +01:00
}
return request . EnableAutoStreamCopy ;
}
2022-06-15 23:27:07 +02:00
public int GetVideoBitrateParamValue ( BaseEncodingJobOptions request , MediaStream videoStream , string outputVideoCodec )
2018-12-28 00:27:57 +01:00
{
var bitrate = request . VideoBitRate ;
2022-12-05 15:01:13 +01:00
if ( videoStream is not null )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
var isUpscaling = request . Height . HasValue
& & videoStream . Height . HasValue
& & request . Height . Value > videoStream . Height . Value
& & request . Width . HasValue
& & videoStream . Width . HasValue
& & request . Width . Value > videoStream . Width . Value ;
2019-01-13 02:06:59 +01:00
2019-05-11 17:19:20 +02:00
// Don't allow bitrate increases unless upscaling
2019-09-01 18:39:23 +02:00
if ( ! isUpscaling & & bitrate . HasValue & & videoStream . BitRate . HasValue )
2019-05-11 17:19:20 +02:00
{
2019-09-01 18:39:23 +02:00
bitrate = GetMinBitrate ( videoStream . BitRate . Value , bitrate . Value ) ;
2018-12-28 00:27:57 +01:00
}
2019-05-11 17:19:20 +02:00
2019-10-17 11:31:11 +02:00
if ( bitrate . HasValue )
2019-05-11 17:19:20 +02:00
{
2019-10-17 11:31:11 +02:00
var inputVideoCodec = videoStream . Codec ;
bitrate = ScaleBitrate ( bitrate . Value , inputVideoCodec , outputVideoCodec ) ;
// If a max bitrate was requested, don't let the scaled bitrate exceed it
if ( request . VideoBitRate . HasValue )
{
bitrate = Math . Min ( bitrate . Value , request . VideoBitRate . Value ) ;
}
2019-05-11 17:19:20 +02:00
}
}
2022-08-15 12:48:34 +02:00
// Cap the max target bitrate to intMax/2 to satisfy the bufsize=bitrate*2.
2022-06-15 23:27:07 +02:00
return Math . Min ( bitrate ? ? 0 , int . MaxValue / 2 ) ;
2019-05-11 17:19:20 +02:00
}
private int GetMinBitrate ( int sourceBitrate , int requestedBitrate )
{
2019-06-21 01:44:27 +02:00
// these values were chosen from testing to improve low bitrate streams
2019-05-11 17:19:20 +02:00
if ( sourceBitrate < = 2000000 )
{
sourceBitrate = Convert . ToInt32 ( sourceBitrate * 2.5 ) ;
}
else if ( sourceBitrate < = 3000000 )
{
2019-09-01 18:39:23 +02:00
sourceBitrate * = 2 ;
2019-05-11 17:19:20 +02:00
}
var bitrate = Math . Min ( sourceBitrate , requestedBitrate ) ;
2019-01-13 02:06:59 +01:00
return bitrate ;
}
2018-12-28 00:27:57 +01:00
2019-01-13 02:06:59 +01:00
private static double GetVideoBitrateScaleFactor ( string codec )
{
2023-03-14 23:21:01 +01:00
// hevc & vp9 - 40% more efficient than h.264
2019-09-01 18:39:23 +02:00
if ( string . Equals ( codec , "h265" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( codec , "hevc" , StringComparison . OrdinalIgnoreCase )
2023-03-14 23:21:01 +01:00
| | string . Equals ( codec , "vp9" , StringComparison . OrdinalIgnoreCase ) )
2019-01-13 02:06:59 +01:00
{
2020-11-11 10:08:50 +01:00
return . 6 ;
2018-12-28 00:27:57 +01:00
}
2019-09-01 18:39:23 +02:00
2023-03-14 23:21:01 +01:00
// av1 - 50% more efficient than h.264
if ( string . Equals ( codec , "av1" , StringComparison . OrdinalIgnoreCase ) )
{
return . 5 ;
}
2019-01-13 02:06:59 +01:00
return 1 ;
2018-12-28 00:27:57 +01:00
}
2019-01-13 02:06:59 +01:00
private static int ScaleBitrate ( int bitrate , string inputVideoCodec , string outputVideoCodec )
2018-12-28 00:27:57 +01:00
{
2019-01-13 02:06:59 +01:00
var inputScaleFactor = GetVideoBitrateScaleFactor ( inputVideoCodec ) ;
var outputScaleFactor = GetVideoBitrateScaleFactor ( outputVideoCodec ) ;
2023-03-14 23:21:01 +01:00
// Don't scale the real bitrate lower than the requested bitrate
2023-05-07 21:20:44 +02:00
var scaleFactor = Math . Max ( outputScaleFactor / inputScaleFactor , 1 ) ;
2019-01-13 02:06:59 +01:00
if ( bitrate < = 500000 )
{
scaleFactor = Math . Max ( scaleFactor , 4 ) ;
}
else if ( bitrate < = 1000000 )
{
scaleFactor = Math . Max ( scaleFactor , 3 ) ;
}
else if ( bitrate < = 2000000 )
2018-12-28 00:27:57 +01:00
{
2019-01-13 02:06:59 +01:00
scaleFactor = Math . Max ( scaleFactor , 2.5 ) ;
2018-12-28 00:27:57 +01:00
}
2019-01-13 02:06:59 +01:00
else if ( bitrate < = 3000000 )
2018-12-28 00:27:57 +01:00
{
2019-01-13 02:06:59 +01:00
scaleFactor = Math . Max ( scaleFactor , 2 ) ;
2018-12-28 00:27:57 +01:00
}
2019-09-01 18:39:23 +02:00
return Convert . ToInt32 ( scaleFactor * bitrate ) ;
2018-12-28 00:27:57 +01:00
}
2022-07-12 15:54:17 +02:00
public int? GetAudioBitrateParam ( BaseEncodingJobOptions request , MediaStream audioStream , int? outputAudioChannels )
2018-12-28 00:27:57 +01:00
{
2022-07-12 15:54:17 +02:00
return GetAudioBitrateParam ( request . AudioBitRate , request . AudioCodec , audioStream , outputAudioChannels ) ;
2018-12-28 00:27:57 +01:00
}
2022-07-12 15:54:17 +02:00
public int? GetAudioBitrateParam ( int? audioBitRate , string audioCodec , MediaStream audioStream , int? outputAudioChannels )
2020-07-12 11:14:38 +02:00
{
2022-12-05 15:00:20 +01:00
if ( audioStream is null )
2020-10-28 15:27:08 +01:00
{
return null ;
}
2022-07-12 15:54:17 +02:00
var inputChannels = audioStream . Channels ? ? 0 ;
var outputChannels = outputAudioChannels ? ? 0 ;
2023-02-27 16:03:12 +01:00
var bitrate = audioBitRate ? ? int . MaxValue ;
2022-07-12 15:54:17 +02:00
2023-02-24 15:21:22 +01:00
if ( string . IsNullOrEmpty ( audioCodec )
2022-07-12 15:54:17 +02:00
| | string . Equals ( audioCodec , "aac" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( audioCodec , "mp3" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( audioCodec , "opus" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( audioCodec , "vorbis" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( audioCodec , "ac3" , StringComparison . OrdinalIgnoreCase )
2023-02-24 15:21:22 +01:00
| | string . Equals ( audioCodec , "eac3" , StringComparison . OrdinalIgnoreCase ) )
2020-07-12 11:14:38 +02:00
{
2022-07-12 15:54:17 +02:00
return ( inputChannels , outputChannels ) switch
{
2023-02-24 15:21:22 +01:00
( > = 6 , > = 6 or 0 ) = > Math . Min ( 640000 , bitrate ) ,
( > 0 , > 0 ) = > Math . Min ( outputChannels * 128000 , bitrate ) ,
( > 0 , _ ) = > Math . Min ( inputChannels * 128000 , bitrate ) ,
( _ , _ ) = > Math . Min ( 384000 , bitrate )
2022-07-12 15:54:17 +02:00
} ;
2020-07-12 11:14:38 +02:00
}
2023-02-24 15:21:22 +01:00
if ( string . Equals ( audioCodec , "dts" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( audioCodec , "dca" , StringComparison . OrdinalIgnoreCase ) )
2020-11-11 10:08:50 +01:00
{
2023-02-24 15:21:22 +01:00
return ( inputChannels , outputChannels ) switch
2020-11-11 10:08:50 +01:00
{
2023-02-24 15:21:22 +01:00
( > = 6 , > = 6 or 0 ) = > Math . Min ( 768000 , bitrate ) ,
( > 0 , > 0 ) = > Math . Min ( outputChannels * 136000 , bitrate ) ,
( > 0 , _ ) = > Math . Min ( inputChannels * 136000 , bitrate ) ,
( _ , _ ) = > Math . Min ( 672000 , bitrate )
} ;
}
2020-11-11 10:08:50 +01:00
2020-10-28 15:27:08 +01:00
// Empty bitrate area is not allow on iOS
2023-02-24 15:21:22 +01:00
// Default audio bitrate to 128K per channel if we don't have codec specific defaults
2020-10-28 15:27:08 +01:00
// https://ffmpeg.org/ffmpeg-codecs.html#toc-Codec-Options
2023-03-02 20:57:59 +01:00
return 128000 * ( outputAudioChannels ? ? audioStream . Channels ? ? 2 ) ;
2020-07-12 11:14:38 +02:00
}
2020-11-11 10:08:50 +01:00
2022-11-07 00:15:04 +01:00
public string GetAudioVbrModeParam ( string encoder , int bitratePerChannel )
{
2023-02-27 16:03:12 +01:00
if ( string . Equals ( encoder , "libfdk_aac" , StringComparison . OrdinalIgnoreCase ) )
2022-11-07 00:15:04 +01:00
{
return " -vbr:a " + bitratePerChannel switch
2020-11-11 10:08:50 +01:00
{
2022-11-07 00:15:04 +01:00
< 32000 = > "1" ,
< 48000 = > "2" ,
< 64000 = > "3" ,
< 96000 = > "4" ,
_ = > "5"
} ;
}
2020-11-11 10:08:50 +01:00
2023-02-27 16:03:12 +01:00
if ( string . Equals ( encoder , "libmp3lame" , StringComparison . OrdinalIgnoreCase ) )
2022-11-07 00:15:04 +01:00
{
return " -qscale:a " + bitratePerChannel switch
{
< 48000 = > "8" ,
< 64000 = > "6" ,
< 88000 = > "4" ,
< 112000 = > "2" ,
_ = > "0"
} ;
2020-11-11 10:08:50 +01:00
}
2023-02-27 16:03:12 +01:00
if ( string . Equals ( encoder , "libvorbis" , StringComparison . OrdinalIgnoreCase ) )
2022-11-07 00:15:04 +01:00
{
return " -qscale:a " + bitratePerChannel switch
{
< 40000 = > "0" ,
< 56000 = > "2" ,
< 80000 = > "4" ,
< 112000 = > "6" ,
_ = > "8"
} ;
}
return null ;
2020-07-12 11:14:38 +02:00
}
2021-07-10 18:09:02 +02:00
public string GetAudioFilterParam ( EncodingJobInfo state , EncodingOptions encodingOptions )
2018-12-28 00:27:57 +01:00
{
var channels = state . OutputAudioChannels ;
var filters = new List < string > ( ) ;
2019-09-01 18:39:23 +02:00
if ( channels . HasValue
2023-01-02 22:26:54 +01:00
& & channels . Value = = 2
2022-12-05 15:01:13 +01:00
& & state . AudioStream is not null
2019-09-01 18:39:23 +02:00
& & state . AudioStream . Channels . HasValue
2023-01-02 22:26:54 +01:00
& & state . AudioStream . Channels . Value > 5 )
2018-12-28 00:27:57 +01:00
{
2023-01-02 22:26:54 +01:00
switch ( encodingOptions . DownMixStereoAlgorithm )
{
case DownMixStereoAlgorithms . Dave750 :
filters . Add ( "volume=4.25" ) ;
filters . Add ( "pan=stereo|c0=0.5*c2+0.707*c0+0.707*c4+0.5*c3|c1=0.5*c2+0.707*c1+0.707*c5+0.5*c3" ) ;
break ;
case DownMixStereoAlgorithms . NightmodeDialogue :
filters . Add ( "pan=stereo|c0=c2+0.30*c0+0.30*c4|c1=c2+0.30*c1+0.30*c5" ) ;
break ;
case DownMixStereoAlgorithms . None :
default :
if ( ! encodingOptions . DownMixAudioBoost . Equals ( 1 ) )
{
filters . Add ( "volume=" + encodingOptions . DownMixAudioBoost . ToString ( CultureInfo . InvariantCulture ) ) ;
}
break ;
}
2018-12-28 00:27:57 +01:00
}
var isCopyingTimestamps = state . CopyTimestamps | | state . TranscodingType ! = TranscodingJobType . Progressive ;
2022-12-05 15:01:13 +01:00
if ( state . SubtitleStream is not null & & state . SubtitleStream . IsTextSubtitleStream & & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode & & ! isCopyingTimestamps )
2018-12-28 00:27:57 +01:00
{
var seconds = TimeSpan . FromTicks ( state . StartTimeTicks ? ? 0 ) . TotalSeconds ;
2019-09-01 18:39:23 +02:00
filters . Add (
string . Format (
CultureInfo . InvariantCulture ,
"asetpts=PTS-{0}/TB" ,
Math . Round ( seconds ) ) ) ;
2018-12-28 00:27:57 +01:00
}
if ( filters . Count > 0 )
{
2021-02-13 00:39:18 +01:00
return " -af \"" + string . Join ( ',' , filters ) + "\"" ;
2018-12-28 00:27:57 +01:00
}
return string . Empty ;
}
/// <summary>
2020-06-16 00:37:52 +02:00
/// Gets the number of audio channels to specify on the command line.
2018-12-28 00:27:57 +01:00
/// </summary>
2019-01-06 21:50:43 +01:00
/// <param name="state">The state.</param>
2018-12-28 00:27:57 +01:00
/// <param name="audioStream">The audio stream.</param>
/// <param name="outputAudioCodec">The output audio codec.</param>
/// <returns>System.Nullable{System.Int32}.</returns>
public int? GetNumAudioChannelsParam ( EncodingJobInfo state , MediaStream audioStream , string outputAudioCodec )
{
2022-12-05 15:00:20 +01:00
if ( audioStream is null )
2020-11-11 12:04:58 +01:00
{
return null ;
}
2018-12-28 00:27:57 +01:00
var request = state . BaseRequest ;
2023-02-06 06:40:49 +01:00
var codec = outputAudioCodec ? ? string . Empty ;
2018-12-28 00:27:57 +01:00
2023-02-06 06:40:49 +01:00
int? resultChannels = state . GetRequestedAudioChannels ( codec ) ;
2018-12-28 00:27:57 +01:00
2023-02-06 06:40:49 +01:00
var inputChannels = audioStream . Channels ;
2018-12-28 00:27:57 +01:00
2023-02-06 06:40:49 +01:00
if ( inputChannels > 0 )
2018-12-28 00:27:57 +01:00
{
2023-02-06 06:40:49 +01:00
resultChannels = inputChannels < resultChannels ? inputChannels : resultChannels ? ? inputChannels ;
2018-12-28 00:27:57 +01:00
}
2020-07-15 06:58:36 +02:00
var isTranscodingAudio = ! IsCopyCodec ( codec ) ;
2018-12-28 00:27:57 +01:00
if ( isTranscodingAudio )
{
2023-02-24 16:06:19 +01:00
var audioEncoder = GetAudioEncoder ( state ) ;
if ( ! _audioTranscodeChannelLookup . TryGetValue ( audioEncoder , out var transcoderChannelLimit ) )
{
// Set default max transcoding channels to 8 to prevent encoding errors due to asking for too many channels.
transcoderChannelLimit = 8 ;
}
2018-12-28 00:27:57 +01:00
2023-02-06 06:40:49 +01:00
// Set resultChannels to minimum between resultChannels, TranscodingMaxAudioChannels, transcoderChannelLimit
resultChannels = transcoderChannelLimit < resultChannels ? transcoderChannelLimit : resultChannels ? ? transcoderChannelLimit ;
2018-12-28 00:27:57 +01:00
2023-02-06 06:40:49 +01:00
if ( request . TranscodingMaxAudioChannels < resultChannels )
{
resultChannels = request . TranscodingMaxAudioChannels ;
}
2019-09-01 18:39:23 +02:00
2023-02-06 06:40:49 +01:00
// Avoid transcoding to audio channels other than 1ch, 2ch, 6ch (5.1 layout) and 8ch (7.1 layout).
// https://developer.apple.com/documentation/http_live_streaming/hls_authoring_specification_for_apple_devices
if ( state . TranscodingType ! = TranscodingJobType . Progressive
& & ( ( resultChannels > 2 & & resultChannels < 6 ) | | resultChannels = = 7 ) )
{
resultChannels = 2 ;
}
2018-12-28 00:27:57 +01:00
}
2023-02-06 06:40:49 +01:00
return resultChannels ;
2018-12-28 00:27:57 +01:00
}
/// <summary>
/// Enforces the resolution limit.
/// </summary>
/// <param name="state">The state.</param>
public void EnforceResolutionLimit ( EncodingJobInfo state )
{
var videoRequest = state . BaseRequest ;
// Switch the incoming params to be ceilings rather than fixed values
videoRequest . MaxWidth = videoRequest . MaxWidth ? ? videoRequest . Width ;
videoRequest . MaxHeight = videoRequest . MaxHeight ? ? videoRequest . Height ;
videoRequest . Width = null ;
videoRequest . Height = null ;
}
/// <summary>
/// Gets the fast seek command line parameter.
/// </summary>
2021-12-01 17:49:50 +01:00
/// <param name="state">The state.</param>
/// <param name="options">The options.</param>
2022-03-09 14:28:58 +01:00
/// <param name="segmentContainer">Segment Container.</param>
2018-12-28 00:27:57 +01:00
/// <returns>System.String.</returns>
/// <value>The fast seek command line parameter.</value>
2022-03-09 14:28:58 +01:00
public string GetFastSeekCommandLineParameter ( EncodingJobInfo state , EncodingOptions options , string segmentContainer )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
var time = state . BaseRequest . StartTimeTicks ? ? 0 ;
var seekParam = string . Empty ;
2018-12-28 00:27:57 +01:00
if ( time > 0 )
{
2021-12-01 17:49:50 +01:00
seekParam + = string . Format ( CultureInfo . InvariantCulture , "-ss {0}" , _mediaEncoder . GetTimeParameter ( time ) ) ;
if ( state . IsVideoRequest )
{
var outputVideoCodec = GetVideoEncoder ( state , options ) ;
2022-03-09 14:28:58 +01:00
var segmentFormat = GetSegmentFileExtension ( segmentContainer ) . TrimStart ( '.' ) ;
2021-12-01 17:49:50 +01:00
// Important: If this is ever re-enabled, make sure not to use it with wtv because it breaks seeking
2022-03-09 14:28:58 +01:00
// Disable -noaccurate_seek on mpegts container due to the timestamps issue on some clients,
// but it's still required for fMP4 container otherwise the audio can't be synced to the video.
2021-12-01 17:49:50 +01:00
if ( ! string . Equals ( state . InputContainer , "wtv" , StringComparison . OrdinalIgnoreCase )
2022-03-09 14:28:58 +01:00
& & ! string . Equals ( segmentFormat , "ts" , StringComparison . OrdinalIgnoreCase )
2021-12-01 17:49:50 +01:00
& & state . TranscodingType ! = TranscodingJobType . Progressive
& & ! state . EnableBreakOnNonKeyFrames ( outputVideoCodec )
& & ( state . BaseRequest . StartTimeTicks ? ? 0 ) > 0 )
{
seekParam + = " -noaccurate_seek" ;
}
}
2018-12-28 00:27:57 +01:00
}
2021-12-01 17:49:50 +01:00
return seekParam ;
2018-12-28 00:27:57 +01:00
}
/// <summary>
/// Gets the map args.
/// </summary>
/// <param name="state">The state.</param>
/// <returns>System.String.</returns>
public string GetMapArgs ( EncodingJobInfo state )
{
// If we don't have known media info
// If input is video, use -sn to drop subtitles
// Otherwise just return empty
2022-12-05 15:00:20 +01:00
if ( state . VideoStream is null & & state . AudioStream is null )
2018-12-28 00:27:57 +01:00
{
return state . IsInputVideo ? "-sn" : string . Empty ;
}
2022-05-04 16:20:48 +02:00
// We have media info, but we don't know the stream index
2022-12-05 15:01:13 +01:00
if ( state . VideoStream is not null & & state . VideoStream . Index = = - 1 )
2018-12-28 00:27:57 +01:00
{
return "-sn" ;
}
2022-05-04 16:20:48 +02:00
// We have media info, but we don't know the stream index
2022-12-05 15:01:13 +01:00
if ( state . AudioStream is not null & & state . AudioStream . Index = = - 1 )
2018-12-28 00:27:57 +01:00
{
return state . IsInputVideo ? "-sn" : string . Empty ;
}
var args = string . Empty ;
2022-12-05 15:01:13 +01:00
if ( state . VideoStream is not null )
2018-12-28 00:27:57 +01:00
{
2022-05-04 16:20:48 +02:00
int videoStreamIndex = FindIndex ( state . MediaSource . MediaStreams , state . VideoStream ) ;
2019-09-01 18:39:23 +02:00
args + = string . Format (
CultureInfo . InvariantCulture ,
"-map 0:{0}" ,
2022-05-04 16:20:48 +02:00
videoStreamIndex ) ;
2018-12-28 00:27:57 +01:00
}
else
{
// No known video stream
args + = "-vn" ;
}
2022-12-05 15:01:13 +01:00
if ( state . AudioStream is not null )
2018-12-28 00:27:57 +01:00
{
2022-05-04 16:20:48 +02:00
int audioStreamIndex = FindIndex ( state . MediaSource . MediaStreams , state . AudioStream ) ;
2021-11-22 21:47:52 +01:00
if ( state . AudioStream . IsExternal )
{
2022-12-05 15:01:13 +01:00
bool hasExternalGraphicsSubs = state . SubtitleStream is not null
2022-06-15 23:27:07 +02:00
& & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode
& & state . SubtitleStream . IsExternal
& & ! state . SubtitleStream . IsTextSubtitleStream ;
2022-04-12 21:41:21 +02:00
int externalAudioMapIndex = hasExternalGraphicsSubs ? 2 : 1 ;
2021-11-27 12:10:57 +01:00
args + = string . Format (
CultureInfo . InvariantCulture ,
" -map {0}:{1}" ,
externalAudioMapIndex ,
2022-05-04 16:20:48 +02:00
audioStreamIndex ) ;
2021-11-22 21:47:52 +01:00
}
else
{
args + = string . Format (
CultureInfo . InvariantCulture ,
" -map 0:{0}" ,
2022-05-04 16:20:48 +02:00
audioStreamIndex ) ;
2021-11-22 21:47:52 +01:00
}
2018-12-28 00:27:57 +01:00
}
else
{
args + = " -map -0:a" ;
}
var subtitleMethod = state . SubtitleDeliveryMethod ;
2022-12-05 15:00:20 +01:00
if ( state . SubtitleStream is null | | subtitleMethod = = SubtitleDeliveryMethod . Hls )
2018-12-28 00:27:57 +01:00
{
args + = " -map -0:s" ;
}
else if ( subtitleMethod = = SubtitleDeliveryMethod . Embed )
{
2022-05-04 16:20:48 +02:00
int subtitleStreamIndex = FindIndex ( state . MediaSource . MediaStreams , state . SubtitleStream ) ;
2019-09-01 18:39:23 +02:00
args + = string . Format (
CultureInfo . InvariantCulture ,
" -map 0:{0}" ,
2022-05-04 16:20:48 +02:00
subtitleStreamIndex ) ;
2018-12-28 00:27:57 +01:00
}
else if ( state . SubtitleStream . IsExternal & & ! state . SubtitleStream . IsTextSubtitleStream )
{
2022-05-04 16:20:48 +02:00
int externalSubtitleStreamIndex = FindIndex ( state . MediaSource . MediaStreams , state . SubtitleStream ) ;
args + = string . Format (
CultureInfo . InvariantCulture ,
" -map 1:{0} -sn" ,
externalSubtitleStreamIndex ) ;
2018-12-28 00:27:57 +01:00
}
return args ;
}
2023-03-10 01:38:15 +01:00
/// <summary>
/// Gets the negative map args by filters.
/// </summary>
/// <param name="state">The state.</param>
/// <param name="videoProcessFilters">The videoProcessFilters.</param>
/// <returns>System.String.</returns>
public string GetNegativeMapArgsByFilters ( EncodingJobInfo state , string videoProcessFilters )
{
string args = string . Empty ;
// http://ffmpeg.org/ffmpeg-all.html#toc-Complex-filtergraphs-1
if ( state . VideoStream ! = null & & videoProcessFilters . Contains ( "-filter_complex" , StringComparison . Ordinal ) )
{
int videoStreamIndex = FindIndex ( state . MediaSource . MediaStreams , state . VideoStream ) ;
args + = string . Format (
CultureInfo . InvariantCulture ,
"-map -0:{0} " ,
videoStreamIndex ) ;
}
return args ;
}
2018-12-28 00:27:57 +01:00
/// <summary>
2020-06-16 00:37:52 +02:00
/// Determines which stream will be used for playback.
2018-12-28 00:27:57 +01:00
/// </summary>
/// <param name="allStream">All stream.</param>
/// <param name="desiredIndex">Index of the desired.</param>
/// <param name="type">The type.</param>
/// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
/// <returns>MediaStream.</returns>
public MediaStream GetMediaStream ( IEnumerable < MediaStream > allStream , int? desiredIndex , MediaStreamType type , bool returnFirstIfNoIndex = true )
{
var streams = allStream . Where ( s = > s . Type = = type ) . OrderBy ( i = > i . Index ) . ToList ( ) ;
if ( desiredIndex . HasValue )
{
var stream = streams . FirstOrDefault ( s = > s . Index = = desiredIndex . Value ) ;
2022-12-05 15:01:13 +01:00
if ( stream is not null )
2018-12-28 00:27:57 +01:00
{
return stream ;
}
}
if ( returnFirstIfNoIndex & & type = = MediaStreamType . Audio )
{
return streams . FirstOrDefault ( i = > i . Channels . HasValue & & i . Channels . Value > 0 ) ? ?
streams . FirstOrDefault ( ) ;
}
// Just return the first one
return returnFirstIfNoIndex ? streams . FirstOrDefault ( ) : null ;
}
2021-12-24 22:18:24 +01:00
public static ( int? Width , int? Height ) GetFixedOutputSize (
2021-12-01 17:49:50 +01:00
int? videoWidth ,
int? videoHeight ,
int? requestedWidth ,
int? requestedHeight ,
int? requestedMaxWidth ,
int? requestedMaxHeight )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
if ( ! videoWidth . HasValue & & ! requestedWidth . HasValue )
2020-11-24 16:10:34 +01:00
{
2021-12-01 17:49:50 +01:00
return ( null , null ) ;
2020-11-24 16:10:34 +01:00
}
2021-12-01 17:49:50 +01:00
if ( ! videoHeight . HasValue & & ! requestedHeight . HasValue )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
return ( null , null ) ;
}
2018-12-28 00:27:57 +01:00
2021-12-24 09:50:40 +01:00
int inputWidth = Convert . ToInt32 ( videoWidth ? ? requestedWidth , CultureInfo . InvariantCulture ) ;
int inputHeight = Convert . ToInt32 ( videoHeight ? ? requestedHeight , CultureInfo . InvariantCulture ) ;
int outputWidth = requestedWidth ? ? inputWidth ;
int outputHeight = requestedHeight ? ? inputHeight ;
// Don't transcode video to bigger than 4k when using HW.
int maximumWidth = Math . Min ( requestedMaxWidth ? ? outputWidth , 4096 ) ;
int maximumHeight = Math . Min ( requestedMaxHeight ? ? outputHeight , 4096 ) ;
2021-07-24 18:52:16 +02:00
2021-12-01 17:49:50 +01:00
if ( outputWidth > maximumWidth | | outputHeight > maximumHeight )
{
2023-04-06 18:46:28 +02:00
var scaleW = ( double ) maximumWidth / outputWidth ;
var scaleH = ( double ) maximumHeight / outputHeight ;
2021-12-24 09:50:40 +01:00
var scale = Math . Min ( scaleW , scaleH ) ;
outputWidth = Math . Min ( maximumWidth , ( int ) ( outputWidth * scale ) ) ;
outputHeight = Math . Min ( maximumHeight , ( int ) ( outputHeight * scale ) ) ;
2018-12-28 00:27:57 +01:00
}
2021-12-24 09:50:40 +01:00
outputWidth = 2 * ( outputWidth / 2 ) ;
outputHeight = 2 * ( outputHeight / 2 ) ;
2018-12-28 00:27:57 +01:00
2021-12-24 09:50:40 +01:00
return ( outputWidth , outputHeight ) ;
2021-12-01 17:49:50 +01:00
}
2018-12-28 00:27:57 +01:00
2021-12-01 17:49:50 +01:00
public static string GetHwScaleFilter (
string hwScaleSuffix ,
string videoFormat ,
int? videoWidth ,
int? videoHeight ,
int? requestedWidth ,
int? requestedHeight ,
int? requestedMaxWidth ,
int? requestedMaxHeight )
{
2021-12-24 09:50:40 +01:00
var ( outWidth , outHeight ) = GetFixedOutputSize (
videoWidth ,
videoHeight ,
requestedWidth ,
requestedHeight ,
requestedMaxWidth ,
requestedMaxHeight ) ;
2021-12-01 17:49:50 +01:00
var isFormatFixed = ! string . IsNullOrEmpty ( videoFormat ) ;
var isSizeFixed = ! videoWidth . HasValue
| | outWidth . Value ! = videoWidth . Value
| | ! videoHeight . HasValue
| | outHeight . Value ! = videoHeight . Value ;
2019-12-04 09:16:19 +01:00
2021-12-01 17:49:50 +01:00
var arg1 = isSizeFixed ? ( "=w=" + outWidth . Value + ":h=" + outHeight . Value ) : string . Empty ;
var arg2 = isFormatFixed ? ( "format=" + videoFormat ) : string . Empty ;
if ( isFormatFixed )
2020-03-03 16:56:50 +01:00
{
2021-12-01 17:49:50 +01:00
arg2 = ( isSizeFixed ? ':' : '=' ) + arg2 ;
2020-03-03 16:56:50 +01:00
}
2021-12-01 17:49:50 +01:00
if ( ! string . IsNullOrEmpty ( hwScaleSuffix ) & & ( isSizeFixed | | isFormatFixed ) )
2021-01-24 20:40:34 +01:00
{
2021-12-01 17:49:50 +01:00
return string . Format (
CultureInfo . InvariantCulture ,
"scale_{0}{1}{2}" ,
hwScaleSuffix ,
arg1 ,
arg2 ) ;
2021-01-24 20:40:34 +01:00
}
2019-12-04 09:16:19 +01:00
2021-12-01 17:49:50 +01:00
return string . Empty ;
2018-12-28 00:27:57 +01:00
}
2021-12-01 17:49:50 +01:00
public static string GetCustomSwScaleFilter (
2019-09-01 18:39:23 +02:00
int? videoWidth ,
2018-12-28 00:27:57 +01:00
int? videoHeight ,
int? requestedWidth ,
int? requestedHeight ,
int? requestedMaxWidth ,
int? requestedMaxHeight )
{
2021-12-24 09:50:40 +01:00
var ( outWidth , outHeight ) = GetFixedOutputSize (
videoWidth ,
videoHeight ,
requestedWidth ,
requestedHeight ,
requestedMaxWidth ,
requestedMaxHeight ) ;
2021-12-01 17:49:50 +01:00
if ( outWidth . HasValue & & outHeight . HasValue )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
return string . Format (
CultureInfo . InvariantCulture ,
"scale=s={0}x{1}:flags=fast_bilinear" ,
outWidth . Value ,
outHeight . Value ) ;
2018-12-28 00:27:57 +01:00
}
2021-12-01 17:49:50 +01:00
return string . Empty ;
}
2018-12-28 00:27:57 +01:00
2021-12-01 17:49:50 +01:00
public static string GetAlphaSrcFilter (
EncodingJobInfo state ,
int? videoWidth ,
int? videoHeight ,
int? requestedWidth ,
int? requestedHeight ,
int? requestedMaxWidth ,
int? requestedMaxHeight ,
int? framerate )
{
var reqTicks = state . BaseRequest . StartTimeTicks ? ? 0 ;
var startTime = TimeSpan . FromTicks ( reqTicks ) . ToString ( @"hh\\\:mm\\\:ss\\\.fff" , CultureInfo . InvariantCulture ) ;
2021-12-24 09:50:40 +01:00
var ( outWidth , outHeight ) = GetFixedOutputSize (
videoWidth ,
videoHeight ,
requestedWidth ,
requestedHeight ,
requestedMaxWidth ,
requestedMaxHeight ) ;
2021-12-01 17:49:50 +01:00
if ( outWidth . HasValue & & outHeight . HasValue )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
return string . Format (
CultureInfo . InvariantCulture ,
"alphasrc=s={0}x{1}:r={2}:start='{3}'" ,
outWidth . Value ,
outHeight . Value ,
framerate ? ? 10 ,
reqTicks > 0 ? startTime : 0 ) ;
2018-12-28 00:27:57 +01:00
}
2021-12-01 17:49:50 +01:00
return string . Empty ;
2018-12-28 00:27:57 +01:00
}
2021-12-24 09:50:40 +01:00
public static string GetSwScaleFilter (
2020-10-12 20:05:11 +02:00
EncodingJobInfo state ,
2020-11-24 15:09:13 +01:00
EncodingOptions options ,
2021-12-01 17:49:50 +01:00
string videoEncoder ,
2020-03-20 20:29:33 +01:00
int? videoWidth ,
2018-12-28 00:27:57 +01:00
int? videoHeight ,
Video3DFormat ? threedFormat ,
int? requestedWidth ,
int? requestedHeight ,
int? requestedMaxWidth ,
int? requestedMaxHeight )
{
2021-12-01 17:49:50 +01:00
var isV4l2 = string . Equals ( videoEncoder , "h264_v4l2m2m" , StringComparison . OrdinalIgnoreCase ) ;
var scaleVal = isV4l2 ? 64 : 2 ;
2021-01-26 20:20:53 +01:00
2021-12-01 17:49:50 +01:00
// If fixed dimensions were supplied
if ( requestedWidth . HasValue & & requestedHeight . HasValue )
{
if ( isV4l2 )
2021-01-26 20:20:53 +01:00
{
2021-12-01 17:49:50 +01:00
var widthParam = requestedWidth . Value . ToString ( CultureInfo . InvariantCulture ) ;
var heightParam = requestedHeight . Value . ToString ( CultureInfo . InvariantCulture ) ;
2021-01-26 20:20:53 +01:00
2021-12-24 09:50:40 +01:00
return string . Format (
2021-01-24 20:40:34 +01:00
CultureInfo . InvariantCulture ,
2021-12-01 17:49:50 +01:00
"scale=trunc({0}/64)*64:trunc({1}/2)*2" ,
widthParam ,
2021-12-24 09:50:40 +01:00
heightParam ) ;
2021-01-26 20:20:53 +01:00
}
2023-04-06 19:38:34 +02:00
return GetFixedSwScaleFilter ( threedFormat , requestedWidth . Value , requestedHeight . Value ) ;
2021-01-24 20:40:34 +01:00
}
2021-12-01 17:49:50 +01:00
// If Max dimensions were supplied, for width selects lowest even number between input width and width req size and selects lowest even number from in width*display aspect and requested size
2023-04-06 19:38:34 +02:00
if ( requestedMaxWidth . HasValue & & requestedMaxHeight . HasValue )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
var maxWidthParam = requestedMaxWidth . Value . ToString ( CultureInfo . InvariantCulture ) ;
var maxHeightParam = requestedMaxHeight . Value . ToString ( CultureInfo . InvariantCulture ) ;
2018-12-28 00:27:57 +01:00
2021-12-24 09:50:40 +01:00
return string . Format (
2023-04-06 19:38:34 +02:00
CultureInfo . InvariantCulture ,
"scale=trunc(min(max(iw\\,ih*a)\\,min({0}\\,{1}*a))/{2})*{2}:trunc(min(max(iw/a\\,ih)\\,min({0}/a\\,{1}))/2)*2" ,
maxWidthParam ,
maxHeightParam ,
scaleVal ) ;
2021-12-01 17:49:50 +01:00
}
2018-12-28 00:27:57 +01:00
2021-12-01 17:49:50 +01:00
// If a fixed width was requested
2023-04-06 19:38:34 +02:00
if ( requestedWidth . HasValue )
2021-12-01 17:49:50 +01:00
{
if ( threedFormat . HasValue )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
// This method can handle 0 being passed in for the requested height
2021-12-24 09:50:40 +01:00
return GetFixedSwScaleFilter ( threedFormat , requestedWidth . Value , 0 ) ;
2018-12-28 00:27:57 +01:00
}
2023-04-06 19:38:34 +02:00
var widthParam = requestedWidth . Value . ToString ( CultureInfo . InvariantCulture ) ;
return string . Format (
CultureInfo . InvariantCulture ,
"scale={0}:trunc(ow/a/2)*2" ,
widthParam ) ;
2021-12-01 17:49:50 +01:00
}
2018-12-28 00:27:57 +01:00
2021-12-01 17:49:50 +01:00
// If a fixed height was requested
2023-04-06 19:38:34 +02:00
if ( requestedHeight . HasValue )
2021-12-01 17:49:50 +01:00
{
var heightParam = requestedHeight . Value . ToString ( CultureInfo . InvariantCulture ) ;
2018-12-28 00:27:57 +01:00
2021-12-24 09:50:40 +01:00
return string . Format (
2023-04-06 19:38:34 +02:00
CultureInfo . InvariantCulture ,
"scale=trunc(oh*a/{1})*{1}:{0}" ,
heightParam ,
scaleVal ) ;
2021-12-01 17:49:50 +01:00
}
2018-12-28 00:27:57 +01:00
2021-12-01 17:49:50 +01:00
// If a max width was requested
2023-04-06 19:38:34 +02:00
if ( requestedMaxWidth . HasValue )
2021-12-01 17:49:50 +01:00
{
var maxWidthParam = requestedMaxWidth . Value . ToString ( CultureInfo . InvariantCulture ) ;
2018-12-28 00:27:57 +01:00
2021-12-24 09:50:40 +01:00
return string . Format (
2023-04-06 19:38:34 +02:00
CultureInfo . InvariantCulture ,
"scale=trunc(min(max(iw\\,ih*a)\\,{0})/{1})*{1}:trunc(ow/a/2)*2" ,
maxWidthParam ,
scaleVal ) ;
2021-12-01 17:49:50 +01:00
}
2018-12-28 00:27:57 +01:00
2021-12-01 17:49:50 +01:00
// If a max height was requested
2023-04-06 19:38:34 +02:00
if ( requestedMaxHeight . HasValue )
2021-12-01 17:49:50 +01:00
{
var maxHeightParam = requestedMaxHeight . Value . ToString ( CultureInfo . InvariantCulture ) ;
2018-12-28 00:27:57 +01:00
2021-12-24 09:50:40 +01:00
return string . Format (
2023-04-06 19:38:34 +02:00
CultureInfo . InvariantCulture ,
"scale=trunc(oh*a/{1})*{1}:min(max(iw/a\\,ih)\\,{0})" ,
maxHeightParam ,
scaleVal ) ;
2018-12-28 00:27:57 +01:00
}
2021-12-24 09:50:40 +01:00
return string . Empty ;
2018-12-28 00:27:57 +01:00
}
2021-12-01 17:49:50 +01:00
private static string GetFixedSwScaleFilter ( Video3DFormat ? threedFormat , int requestedWidth , int requestedHeight )
2018-12-28 00:27:57 +01:00
{
2019-09-01 18:39:23 +02:00
var widthParam = requestedWidth . ToString ( CultureInfo . InvariantCulture ) ;
var heightParam = requestedHeight . ToString ( CultureInfo . InvariantCulture ) ;
2018-12-28 00:27:57 +01:00
string filter = null ;
if ( threedFormat . HasValue )
{
switch ( threedFormat . Value )
{
case Video3DFormat . HalfSideBySide :
filter = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2" ;
// hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
break ;
case Video3DFormat . FullSideBySide :
filter = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2" ;
2020-06-14 11:11:11 +02:00
// fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to requestedWidth.
2018-12-28 00:27:57 +01:00
break ;
case Video3DFormat . HalfTopAndBottom :
filter = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2" ;
2020-06-14 11:11:11 +02:00
// htab crop height in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth
2018-12-28 00:27:57 +01:00
break ;
case Video3DFormat . FullTopAndBottom :
filter = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2" ;
// ftab crop height in half, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth
break ;
default :
break ;
}
}
// default
2022-12-05 15:00:20 +01:00
if ( filter is null )
2018-12-28 00:27:57 +01:00
{
if ( requestedHeight > 0 )
{
filter = "scale=trunc({0}/2)*2:trunc({1}/2)*2" ;
}
else
{
2022-05-16 02:22:24 +02:00
filter = "scale={0}:trunc({0}/a/2)*2" ;
2018-12-28 00:27:57 +01:00
}
}
2019-09-01 18:39:23 +02:00
return string . Format ( CultureInfo . InvariantCulture , filter , widthParam , heightParam ) ;
2018-12-28 00:27:57 +01:00
}
2021-12-01 17:49:50 +01:00
public static string GetSwDeinterlaceFilter ( EncodingJobInfo state , EncodingOptions options )
{
2021-12-24 09:50:40 +01:00
var doubleRateDeint = options . DeinterlaceDoubleRate & & state . VideoStream ? . AverageFrameRate < = 30 ;
return string . Format (
CultureInfo . InvariantCulture ,
"{0}={1}:-1:0" ,
string . Equals ( options . DeinterlaceMethod , "bwdif" , StringComparison . OrdinalIgnoreCase ) ? "bwdif" : "yadif" ,
doubleRateDeint ? "1" : "0" ) ;
2021-12-01 17:49:50 +01:00
}
public static string GetHwDeinterlaceFilter ( EncodingJobInfo state , EncodingOptions options , string hwDeintSuffix )
{
var doubleRateDeint = options . DeinterlaceDoubleRate & & ( state . VideoStream ? . AverageFrameRate ? ? 60 ) < = 30 ;
if ( hwDeintSuffix . Contains ( "cuda" , StringComparison . OrdinalIgnoreCase ) )
{
return string . Format (
CultureInfo . InvariantCulture ,
"yadif_cuda={0}:-1:0" ,
doubleRateDeint ? "1" : "0" ) ;
}
2023-04-06 19:38:34 +02:00
if ( hwDeintSuffix . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
return string . Format (
CultureInfo . InvariantCulture ,
"deinterlace_vaapi=rate={0}" ,
doubleRateDeint ? "field" : "frame" ) ;
}
2023-04-06 19:38:34 +02:00
if ( hwDeintSuffix . Contains ( "qsv" , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
return "deinterlace_qsv=mode=2" ;
}
2023-04-06 19:38:34 +02:00
if ( hwDeintSuffix . Contains ( "videotoolbox" , StringComparison . OrdinalIgnoreCase ) )
2023-02-08 23:42:17 +01:00
{
return string . Format (
CultureInfo . InvariantCulture ,
"yadif_videotoolbox={0}:-1:0" ,
doubleRateDeint ? "1" : "0" ) ;
}
2021-12-01 17:49:50 +01:00
return string . Empty ;
}
2023-06-13 16:53:35 +02:00
public string GetHwTonemapFilter ( EncodingOptions options , string hwTonemapSuffix , string videoFormat )
2020-09-17 13:16:23 +02:00
{
2021-12-01 17:49:50 +01:00
if ( string . IsNullOrEmpty ( hwTonemapSuffix ) )
{
return string . Empty ;
}
2022-10-16 17:08:59 +02:00
var args = string . Empty ;
var algorithm = options . TonemappingAlgorithm ;
2021-12-01 17:49:50 +01:00
2022-10-16 17:08:59 +02:00
if ( string . Equals ( hwTonemapSuffix , "vaapi" , StringComparison . OrdinalIgnoreCase ) )
2022-06-17 18:01:37 +02:00
{
2023-06-18 03:59:55 +02:00
args = "procamp_vaapi=b={1}:c={2},tonemap_vaapi=format={0}:p=bt709:t=bt709:m=bt709:extra_hw_frames=32" ;
2023-06-13 16:53:35 +02:00
2022-06-17 18:01:37 +02:00
return string . Format (
CultureInfo . InvariantCulture ,
args ,
videoFormat ? ? "nv12" ,
options . VppTonemappingBrightness ,
options . VppTonemappingContrast ) ;
}
else
2021-12-01 17:49:50 +01:00
{
2022-10-16 17:08:59 +02:00
args = "tonemap_{0}=format={1}:p=bt709:t=bt709:m=bt709:tonemap={2}:peak={3}:desat={4}" ;
2021-12-01 17:49:50 +01:00
2023-06-13 16:53:35 +02:00
if ( string . Equals ( options . TonemappingMode , "max" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( options . TonemappingMode , "rgb" , StringComparison . OrdinalIgnoreCase ) )
{
if ( _mediaEncoder . EncoderVersion > = _minFFmpegOclCuTonemapMode )
{
args + = ":tonemap_mode={5}" ;
}
}
2021-12-01 17:49:50 +01:00
if ( options . TonemappingParam ! = 0 )
{
2023-06-13 16:53:35 +02:00
args + = ":param={6}" ;
2021-12-01 17:49:50 +01:00
}
2023-06-13 16:53:35 +02:00
if ( string . Equals ( options . TonemappingRange , "tv" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( options . TonemappingRange , "pc" , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
2023-06-13 16:53:35 +02:00
args + = ":range={7}" ;
2021-12-01 17:49:50 +01:00
}
}
return string . Format (
CultureInfo . InvariantCulture ,
args ,
hwTonemapSuffix ,
videoFormat ? ? "nv12" ,
2022-10-16 17:08:59 +02:00
algorithm ,
2021-12-01 17:49:50 +01:00
options . TonemappingPeak ,
options . TonemappingDesat ,
2023-06-13 16:53:35 +02:00
options . TonemappingMode ,
2021-12-01 17:49:50 +01:00
options . TonemappingParam ,
options . TonemappingRange ) ;
2020-09-17 13:16:23 +02:00
}
2023-06-12 19:13:48 +02:00
public string GetLibplaceboFilter (
EncodingOptions options ,
string videoFormat ,
bool doTonemap ,
int? videoWidth ,
int? videoHeight ,
int? requestedWidth ,
int? requestedHeight ,
int? requestedMaxWidth ,
int? requestedMaxHeight )
{
var ( outWidth , outHeight ) = GetFixedOutputSize (
videoWidth ,
videoHeight ,
requestedWidth ,
requestedHeight ,
requestedMaxWidth ,
requestedMaxHeight ) ;
var isFormatFixed = ! string . IsNullOrEmpty ( videoFormat ) ;
var isSizeFixed = ! videoWidth . HasValue
| | outWidth . Value ! = videoWidth . Value
| | ! videoHeight . HasValue
| | outHeight . Value ! = videoHeight . Value ;
var sizeArg = isSizeFixed ? ( ":w=" + outWidth . Value + ":h=" + outHeight . Value ) : string . Empty ;
var formatArg = isFormatFixed ? ( ":format=" + videoFormat ) : string . Empty ;
var tonemapArg = string . Empty ;
if ( doTonemap )
{
var algorithm = options . TonemappingAlgorithm ;
var mode = options . TonemappingMode ;
var range = options . TonemappingRange ;
if ( string . Equals ( algorithm , "bt2390" , StringComparison . OrdinalIgnoreCase ) )
{
algorithm = "bt.2390" ;
}
else if ( string . Equals ( algorithm , "none" , StringComparison . OrdinalIgnoreCase ) )
{
algorithm = "clip" ;
}
tonemapArg = ":tonemapping=" + algorithm ;
if ( string . Equals ( mode , "max" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( mode , "rgb" , StringComparison . OrdinalIgnoreCase ) )
{
tonemapArg + = ":tonemapping_mode=" + mode ;
}
tonemapArg + = ":peak_detect=0:color_primaries=bt709:color_trc=bt709:colorspace=bt709" ;
if ( string . Equals ( range , "tv" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( range , "pc" , StringComparison . OrdinalIgnoreCase ) )
{
tonemapArg + = ":range=" + range ;
}
}
return string . Format (
CultureInfo . InvariantCulture ,
"libplacebo=upscaler=none:downscaler=none{0}{1}{2}" ,
sizeArg ,
formatArg ,
tonemapArg ) ;
}
2018-12-28 00:27:57 +01:00
/// <summary>
2021-12-01 17:49:50 +01:00
/// Gets the parameter of software filter chain.
2018-12-28 00:27:57 +01:00
/// </summary>
2021-08-10 23:29:48 +02:00
/// <param name="state">Encoding state.</param>
/// <param name="options">Encoding options.</param>
2021-12-01 17:49:50 +01:00
/// <param name="vidEncoder">Video encoder to use.</param>
2021-12-26 19:08:43 +01:00
/// <returns>The tuple contains three lists: main, sub and overlay filters.</returns>
2021-12-24 22:18:24 +01:00
public ( List < string > MainFilters , List < string > SubFilters , List < string > OverlayFilters ) GetSwVidFilterChain (
2019-09-01 18:39:23 +02:00
EncodingJobInfo state ,
2018-12-28 00:27:57 +01:00
EncodingOptions options ,
2021-12-01 17:49:50 +01:00
string vidEncoder )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
var inW = state . VideoStream ? . Width ;
var inH = state . VideoStream ? . Height ;
var reqW = state . BaseRequest . Width ;
var reqH = state . BaseRequest . Height ;
var reqMaxW = state . BaseRequest . MaxWidth ;
var reqMaxH = state . BaseRequest . MaxHeight ;
2020-03-03 16:56:50 +01:00
var threeDFormat = state . MediaSource . Video3DFormat ;
2021-12-01 17:49:50 +01:00
var vidDecoder = GetHardwareVideoDecoder ( state , options ) ? ? string . Empty ;
var isSwDecoder = string . IsNullOrEmpty ( vidDecoder ) ;
var isVaapiEncoder = vidEncoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
2022-02-08 04:41:07 +01:00
var isV4l2Encoder = vidEncoder . Contains ( "h264_v4l2m2m" , StringComparison . OrdinalIgnoreCase ) ;
2021-12-01 17:49:50 +01:00
var doDeintH264 = state . DeInterlace ( "h264" , true ) | | state . DeInterlace ( "avc" , true ) ;
var doDeintHevc = state . DeInterlace ( "h265" , true ) | | state . DeInterlace ( "hevc" , true ) ;
var doDeintH2645 = doDeintH264 | | doDeintHevc ;
2020-07-20 14:48:20 +02:00
2022-12-05 15:01:13 +01:00
var hasSubs = state . SubtitleStream is not null & & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode ;
2021-12-01 17:49:50 +01:00
var hasTextSubs = hasSubs & & state . SubtitleStream . IsTextSubtitleStream ;
var hasGraphicalSubs = hasSubs & & ! state . SubtitleStream . IsTextSubtitleStream ;
2021-07-24 18:52:16 +02:00
2021-12-01 17:49:50 +01:00
/* Make main filters for video stream */
var mainFilters = new List < string > ( ) ;
2020-07-24 18:57:34 +02:00
2021-12-01 17:49:50 +01:00
mainFilters . Add ( GetOverwriteColorPropertiesParam ( state , false ) ) ;
2020-07-24 18:57:34 +02:00
2021-12-01 17:49:50 +01:00
// INPUT sw surface(memory/copy-back from vram)
2021-12-24 09:50:40 +01:00
// sw deint
if ( doDeintH2645 )
{
var deintFilter = GetSwDeinterlaceFilter ( state , options ) ;
mainFilters . Add ( deintFilter ) ;
}
2021-12-01 17:49:50 +01:00
var outFormat = isSwDecoder ? "yuv420p" : "nv12" ;
var swScaleFilter = GetSwScaleFilter ( state , options , vidEncoder , inW , inH , threeDFormat , reqW , reqH , reqMaxW , reqMaxH ) ;
if ( isVaapiEncoder )
{
outFormat = "nv12" ;
}
2022-02-08 04:41:07 +01:00
else if ( isV4l2Encoder )
{
outFormat = "yuv420p" ;
}
2021-12-24 09:50:40 +01:00
2021-12-01 17:49:50 +01:00
// sw scale
2021-12-24 09:50:40 +01:00
mainFilters . Add ( swScaleFilter ) ;
2021-12-01 17:49:50 +01:00
mainFilters . Add ( "format=" + outFormat ) ;
2020-09-17 13:16:23 +02:00
2021-12-01 17:49:50 +01:00
// sw tonemap <= TODO: finsh the fast tonemap filter
2020-11-24 15:09:13 +01:00
2021-12-01 17:49:50 +01:00
// OUTPUT yuv420p/nv12 surface(memory)
2020-11-24 15:09:13 +01:00
2021-12-01 17:49:50 +01:00
/* Make sub and overlay filters for subtitle stream */
var subFilters = new List < string > ( ) ;
var overlayFilters = new List < string > ( ) ;
if ( hasTextSubs )
{
// subtitles=f='*.ass':alpha=0
var textSubtitlesFilter = GetTextSubtitlesFilter ( state , false , false ) ;
mainFilters . Add ( textSubtitlesFilter ) ;
}
else if ( hasGraphicalSubs )
{
2023-01-22 20:06:20 +01:00
// [0:s]scale=s=1280x720
var subSwScaleFilter = GetCustomSwScaleFilter ( inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
2021-12-01 17:49:50 +01:00
subFilters . Add ( subSwScaleFilter ) ;
overlayFilters . Add ( "overlay=eof_action=endall:shortest=1:repeatlast=0" ) ;
}
2020-11-25 03:33:16 +01:00
2021-12-24 09:50:40 +01:00
return ( mainFilters , subFilters , overlayFilters ) ;
2021-12-01 17:49:50 +01:00
}
2020-09-17 13:16:23 +02:00
2021-12-01 17:49:50 +01:00
/// <summary>
/// Gets the parameter of Nvidia NVENC filter chain.
/// </summary>
/// <param name="state">Encoding state.</param>
/// <param name="options">Encoding options.</param>
/// <param name="vidEncoder">Video encoder to use.</param>
2021-12-26 19:08:43 +01:00
/// <returns>The tuple contains three lists: main, sub and overlay filters.</returns>
2021-12-24 22:18:24 +01:00
public ( List < string > MainFilters , List < string > SubFilters , List < string > OverlayFilters ) GetNvidiaVidFilterChain (
2021-12-01 17:49:50 +01:00
EncodingJobInfo state ,
EncodingOptions options ,
string vidEncoder )
{
if ( ! string . Equals ( options . HardwareAccelerationType , "nvenc" , StringComparison . OrdinalIgnoreCase ) )
{
2021-12-24 09:50:40 +01:00
return ( null , null , null ) ;
2021-12-01 17:49:50 +01:00
}
2021-01-24 20:40:34 +01:00
2021-12-01 17:49:50 +01:00
var vidDecoder = GetHardwareVideoDecoder ( state , options ) ? ? string . Empty ;
var isSwDecoder = string . IsNullOrEmpty ( vidDecoder ) ;
var isSwEncoder = ! vidEncoder . Contains ( "nvenc" , StringComparison . OrdinalIgnoreCase ) ;
2021-01-24 20:40:34 +01:00
2022-03-08 16:36:30 +01:00
// legacy cuvid pipeline(copy-back)
2021-12-01 17:49:50 +01:00
if ( ( isSwDecoder & & isSwEncoder )
| | ! IsCudaFullSupported ( )
| | ! _mediaEncoder . SupportsFilter ( "alphasrc" ) )
{
return GetSwVidFilterChain ( state , options , vidEncoder ) ;
}
2021-07-24 18:52:16 +02:00
2022-03-08 16:36:30 +01:00
// prefered nvdec/cuvid + cuda filters + nvenc pipeline
2021-12-01 17:49:50 +01:00
return GetNvidiaVidFiltersPrefered ( state , options , vidDecoder , vidEncoder ) ;
}
2020-11-24 15:09:13 +01:00
2021-12-24 22:18:24 +01:00
public ( List < string > MainFilters , List < string > SubFilters , List < string > OverlayFilters ) GetNvidiaVidFiltersPrefered (
2021-12-01 17:49:50 +01:00
EncodingJobInfo state ,
EncodingOptions options ,
string vidDecoder ,
string vidEncoder )
{
var inW = state . VideoStream ? . Width ;
var inH = state . VideoStream ? . Height ;
var reqW = state . BaseRequest . Width ;
var reqH = state . BaseRequest . Height ;
var reqMaxW = state . BaseRequest . MaxWidth ;
var reqMaxH = state . BaseRequest . MaxHeight ;
var threeDFormat = state . MediaSource . Video3DFormat ;
2020-11-24 15:09:13 +01:00
2022-03-08 16:36:30 +01:00
var isNvDecoder = vidDecoder . Contains ( "cuda" , StringComparison . OrdinalIgnoreCase ) ;
2021-12-01 17:49:50 +01:00
var isNvencEncoder = vidEncoder . Contains ( "nvenc" , StringComparison . OrdinalIgnoreCase ) ;
var isSwDecoder = string . IsNullOrEmpty ( vidDecoder ) ;
var isSwEncoder = ! isNvencEncoder ;
2022-03-08 16:36:30 +01:00
var isCuInCuOut = isNvDecoder & & isNvencEncoder ;
2021-07-24 18:52:16 +02:00
2021-12-01 17:49:50 +01:00
var doubleRateDeint = options . DeinterlaceDoubleRate & & ( state . VideoStream ? . AverageFrameRate ? ? 60 ) < = 30 ;
var doDeintH264 = state . DeInterlace ( "h264" , true ) | | state . DeInterlace ( "avc" , true ) ;
var doDeintHevc = state . DeInterlace ( "h265" , true ) | | state . DeInterlace ( "hevc" , true ) ;
var doDeintH2645 = doDeintH264 | | doDeintHevc ;
var doCuTonemap = IsHwTonemapAvailable ( state , options ) ;
2022-12-05 15:01:13 +01:00
var hasSubs = state . SubtitleStream is not null & & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode ;
2021-12-01 17:49:50 +01:00
var hasTextSubs = hasSubs & & state . SubtitleStream . IsTextSubtitleStream ;
var hasGraphicalSubs = hasSubs & & ! state . SubtitleStream . IsTextSubtitleStream ;
var hasAssSubs = hasSubs
& & ( string . Equals ( state . SubtitleStream . Codec , "ass" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( state . SubtitleStream . Codec , "ssa" , StringComparison . OrdinalIgnoreCase ) ) ;
/* Make main filters for video stream */
var mainFilters = new List < string > ( ) ;
mainFilters . Add ( GetOverwriteColorPropertiesParam ( state , doCuTonemap ) ) ;
if ( isSwDecoder )
{
// INPUT sw surface(memory)
// sw deint
if ( doDeintH2645 )
{
var swDeintFilter = GetSwDeinterlaceFilter ( state , options ) ;
mainFilters . Add ( swDeintFilter ) ;
}
2021-12-24 09:50:40 +01:00
var outFormat = doCuTonemap ? "yuv420p10le" : "yuv420p" ;
var swScaleFilter = GetSwScaleFilter ( state , options , vidEncoder , inW , inH , threeDFormat , reqW , reqH , reqMaxW , reqMaxH ) ;
// sw scale
mainFilters . Add ( swScaleFilter ) ;
mainFilters . Add ( "format=" + outFormat ) ;
2021-12-01 17:49:50 +01:00
// sw => hw
if ( doCuTonemap )
{
2022-06-14 16:18:22 +02:00
mainFilters . Add ( "hwupload=derive_device=cuda" ) ;
2020-07-24 18:57:34 +02:00
}
}
2021-12-24 22:18:24 +01:00
2022-03-08 16:36:30 +01:00
if ( isNvDecoder )
2020-03-03 16:56:50 +01:00
{
2021-12-01 17:49:50 +01:00
// INPUT cuda surface(vram)
// hw deint
if ( doDeintH2645 )
{
var deintFilter = GetHwDeinterlaceFilter ( state , options , "cuda" ) ;
mainFilters . Add ( deintFilter ) ;
}
2021-12-24 09:50:40 +01:00
var outFormat = doCuTonemap ? string . Empty : "yuv420p" ;
var hwScaleFilter = GetHwScaleFilter ( "cuda" , outFormat , inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
// hw scale
mainFilters . Add ( hwScaleFilter ) ;
2020-03-03 16:56:50 +01:00
}
2021-12-01 17:49:50 +01:00
// hw tonemap
if ( doCuTonemap )
2020-03-03 16:56:50 +01:00
{
2021-12-01 17:49:50 +01:00
var tonemapFilter = GetHwTonemapFilter ( options , "cuda" , "yuv420p" ) ;
mainFilters . Add ( tonemapFilter ) ;
2020-03-03 16:56:50 +01:00
}
2021-12-01 17:49:50 +01:00
var memoryOutput = false ;
2022-03-21 17:45:07 +01:00
var isUploadForCuTonemap = isSwDecoder & & doCuTonemap ;
if ( ( isNvDecoder & & isSwEncoder ) | | ( isUploadForCuTonemap & & hasSubs ) )
2019-08-31 04:04:31 +02:00
{
2021-12-01 17:49:50 +01:00
memoryOutput = true ;
2020-04-10 16:12:26 +02:00
2021-12-01 17:49:50 +01:00
// OUTPUT yuv420p surface(memory)
mainFilters . Add ( "hwdownload" ) ;
mainFilters . Add ( "format=yuv420p" ) ;
}
// OUTPUT yuv420p surface(memory)
2022-03-21 17:45:07 +01:00
if ( isSwDecoder & & isNvencEncoder & & ! isUploadForCuTonemap )
2021-12-01 17:49:50 +01:00
{
memoryOutput = true ;
}
2020-04-10 16:12:26 +02:00
2021-12-01 17:49:50 +01:00
if ( memoryOutput )
{
// text subtitles
if ( hasTextSubs )
2019-09-01 05:20:18 +02:00
{
2021-12-01 17:49:50 +01:00
var textSubtitlesFilter = GetTextSubtitlesFilter ( state , false , false ) ;
mainFilters . Add ( textSubtitlesFilter ) ;
2019-09-01 05:20:18 +02:00
}
2019-08-31 04:04:31 +02:00
}
2021-12-01 17:49:50 +01:00
// OUTPUT cuda(yuv420p) surface(vram)
/* Make sub and overlay filters for subtitle stream */
var subFilters = new List < string > ( ) ;
var overlayFilters = new List < string > ( ) ;
if ( isCuInCuOut )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
if ( hasSubs )
2019-12-05 21:00:09 +01:00
{
2021-12-01 17:49:50 +01:00
if ( hasGraphicalSubs )
{
// scale=s=1280x720,format=yuva420p,hwupload
var subSwScaleFilter = GetCustomSwScaleFilter ( inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
subFilters . Add ( subSwScaleFilter ) ;
subFilters . Add ( "format=yuva420p" ) ;
}
else if ( hasTextSubs )
{
// alphasrc=s=1280x720:r=10:start=0,format=yuva420p,subtitles,hwupload
var alphaSrcFilter = GetAlphaSrcFilter ( state , inW , inH , reqW , reqH , reqMaxW , reqMaxH , hasAssSubs ? 10 : 5 ) ;
var subTextSubtitlesFilter = GetTextSubtitlesFilter ( state , true , true ) ;
subFilters . Add ( alphaSrcFilter ) ;
subFilters . Add ( "format=yuva420p" ) ;
subFilters . Add ( subTextSubtitlesFilter ) ;
}
2022-06-14 16:18:22 +02:00
subFilters . Add ( "hwupload=derive_device=cuda" ) ;
2021-12-01 17:49:50 +01:00
overlayFilters . Add ( "overlay_cuda=eof_action=endall:shortest=1:repeatlast=0" ) ;
2019-12-05 21:00:09 +01:00
}
2021-12-01 17:49:50 +01:00
}
else
{
if ( hasGraphicalSubs )
2021-01-24 20:40:34 +01:00
{
2023-01-22 20:06:20 +01:00
var subSwScaleFilter = GetCustomSwScaleFilter ( inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
2021-12-01 17:49:50 +01:00
subFilters . Add ( subSwScaleFilter ) ;
overlayFilters . Add ( "overlay=eof_action=endall:shortest=1:repeatlast=0" ) ;
2021-01-24 20:40:34 +01:00
}
2018-12-28 00:27:57 +01:00
}
2021-12-24 09:50:40 +01:00
return ( mainFilters , subFilters , overlayFilters ) ;
2021-12-01 17:49:50 +01:00
}
/// <summary>
/// Gets the parameter of AMD AMF filter chain.
/// </summary>
/// <param name="state">Encoding state.</param>
/// <param name="options">Encoding options.</param>
/// <param name="vidEncoder">Video encoder to use.</param>
2021-12-26 19:08:43 +01:00
/// <returns>The tuple contains three lists: main, sub and overlay filters.</returns>
2021-12-24 22:18:24 +01:00
public ( List < string > MainFilters , List < string > SubFilters , List < string > OverlayFilters ) GetAmdVidFilterChain (
2021-12-01 17:49:50 +01:00
EncodingJobInfo state ,
EncodingOptions options ,
string vidEncoder )
{
if ( ! string . Equals ( options . HardwareAccelerationType , "amf" , StringComparison . OrdinalIgnoreCase ) )
{
2021-12-24 09:50:40 +01:00
return ( null , null , null ) ;
2021-12-01 17:49:50 +01:00
}
var isWindows = OperatingSystem . IsWindows ( ) ;
var vidDecoder = GetHardwareVideoDecoder ( state , options ) ? ? string . Empty ;
var isSwDecoder = string . IsNullOrEmpty ( vidDecoder ) ;
var isSwEncoder = ! vidEncoder . Contains ( "amf" , StringComparison . OrdinalIgnoreCase ) ;
var isAmfDx11OclSupported = isWindows & & _mediaEncoder . SupportsHwaccel ( "d3d11va" ) & & IsOpenclFullSupported ( ) ;
// legacy d3d11va pipeline(copy-back)
if ( ( isSwDecoder & & isSwEncoder )
| | ! isAmfDx11OclSupported
| | ! _mediaEncoder . SupportsFilter ( "alphasrc" ) )
{
return GetSwVidFilterChain ( state , options , vidEncoder ) ;
}
// prefered d3d11va + opencl filters + amf pipeline
return GetAmdDx11VidFiltersPrefered ( state , options , vidDecoder , vidEncoder ) ;
}
2021-12-24 22:18:24 +01:00
public ( List < string > MainFilters , List < string > SubFilters , List < string > OverlayFilters ) GetAmdDx11VidFiltersPrefered (
2021-12-01 17:49:50 +01:00
EncodingJobInfo state ,
EncodingOptions options ,
string vidDecoder ,
string vidEncoder )
{
var inW = state . VideoStream ? . Width ;
var inH = state . VideoStream ? . Height ;
var reqW = state . BaseRequest . Width ;
var reqH = state . BaseRequest . Height ;
var reqMaxW = state . BaseRequest . MaxWidth ;
var reqMaxH = state . BaseRequest . MaxHeight ;
var threeDFormat = state . MediaSource . Video3DFormat ;
var isD3d11vaDecoder = vidDecoder . Contains ( "d3d11va" , StringComparison . OrdinalIgnoreCase ) ;
var isAmfEncoder = vidEncoder . Contains ( "amf" , StringComparison . OrdinalIgnoreCase ) ;
var isSwDecoder = string . IsNullOrEmpty ( vidDecoder ) ;
var isSwEncoder = ! isAmfEncoder ;
var isDxInDxOut = isD3d11vaDecoder & & isAmfEncoder ;
var doDeintH264 = state . DeInterlace ( "h264" , true ) | | state . DeInterlace ( "avc" , true ) ;
var doDeintHevc = state . DeInterlace ( "h265" , true ) | | state . DeInterlace ( "hevc" , true ) ;
var doDeintH2645 = doDeintH264 | | doDeintHevc ;
var doOclTonemap = IsHwTonemapAvailable ( state , options ) ;
2022-12-05 15:01:13 +01:00
var hasSubs = state . SubtitleStream is not null & & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode ;
2021-12-01 17:49:50 +01:00
var hasTextSubs = hasSubs & & state . SubtitleStream . IsTextSubtitleStream ;
var hasGraphicalSubs = hasSubs & & ! state . SubtitleStream . IsTextSubtitleStream ;
var hasAssSubs = hasSubs
& & ( string . Equals ( state . SubtitleStream . Codec , "ass" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( state . SubtitleStream . Codec , "ssa" , StringComparison . OrdinalIgnoreCase ) ) ;
/* Make main filters for video stream */
var mainFilters = new List < string > ( ) ;
mainFilters . Add ( GetOverwriteColorPropertiesParam ( state , doOclTonemap ) ) ;
if ( isSwDecoder )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
// INPUT sw surface(memory)
// sw deint
if ( doDeintH2645 )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
var swDeintFilter = GetSwDeinterlaceFilter ( state , options ) ;
mainFilters . Add ( swDeintFilter ) ;
2018-12-28 00:27:57 +01:00
}
2021-12-01 17:49:50 +01:00
2021-12-24 09:50:40 +01:00
var outFormat = doOclTonemap ? "yuv420p10le" : "yuv420p" ;
var swScaleFilter = GetSwScaleFilter ( state , options , vidEncoder , inW , inH , threeDFormat , reqW , reqH , reqMaxW , reqMaxH ) ;
// sw scale
mainFilters . Add ( swScaleFilter ) ;
mainFilters . Add ( "format=" + outFormat ) ;
2021-12-01 17:49:50 +01:00
// keep video at memory except ocl tonemap,
// since the overhead caused by hwupload >>> using sw filter.
// sw => hw
if ( doOclTonemap )
2018-12-28 00:27:57 +01:00
{
2022-06-14 16:18:22 +02:00
mainFilters . Add ( "hwupload=derive_device=d3d11va:extra_hw_frames=16" ) ;
mainFilters . Add ( "format=d3d11" ) ;
mainFilters . Add ( "hwmap=derive_device=opencl" ) ;
2018-12-28 00:27:57 +01:00
}
}
2021-12-01 17:49:50 +01:00
if ( isD3d11vaDecoder )
2020-09-17 13:16:23 +02:00
{
2021-12-01 17:49:50 +01:00
// INPUT d3d11 surface(vram)
// map from d3d11va to opencl via d3d11-opencl interop.
mainFilters . Add ( "hwmap=derive_device=opencl" ) ;
2021-12-24 09:50:40 +01:00
// hw deint <= TODO: finsh the 'yadif_opencl' filter
2021-12-01 17:49:50 +01:00
var outFormat = doOclTonemap ? string . Empty : "nv12" ;
var hwScaleFilter = GetHwScaleFilter ( "opencl" , outFormat , inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
// hw scale
mainFilters . Add ( hwScaleFilter ) ;
2020-09-17 13:16:23 +02:00
}
2019-12-05 20:22:40 +01:00
2021-12-01 17:49:50 +01:00
// hw tonemap
if ( doOclTonemap )
2021-07-24 18:52:16 +02:00
{
2021-12-01 17:49:50 +01:00
var tonemapFilter = GetHwTonemapFilter ( options , "opencl" , "nv12" ) ;
mainFilters . Add ( tonemapFilter ) ;
}
2021-07-24 18:52:16 +02:00
2021-12-01 17:49:50 +01:00
var memoryOutput = false ;
var isUploadForOclTonemap = isSwDecoder & & doOclTonemap ;
2022-06-14 16:18:22 +02:00
if ( isD3d11vaDecoder & & isSwEncoder )
2021-12-01 17:49:50 +01:00
{
memoryOutput = true ;
2021-07-24 18:52:16 +02:00
2021-12-01 17:49:50 +01:00
// OUTPUT nv12 surface(memory)
// prefer hwmap to hwdownload on opencl.
2023-03-10 01:33:52 +01:00
var hwTransferFilter = hasGraphicalSubs ? "hwdownload" : "hwmap=mode=read" ;
2021-12-01 17:49:50 +01:00
mainFilters . Add ( hwTransferFilter ) ;
mainFilters . Add ( "format=nv12" ) ;
}
2021-07-24 18:52:16 +02:00
2021-12-01 17:49:50 +01:00
// OUTPUT yuv420p surface
2022-06-14 16:18:22 +02:00
if ( isSwDecoder & & isAmfEncoder & & ! isUploadForOclTonemap )
2021-12-01 17:49:50 +01:00
{
memoryOutput = true ;
}
if ( memoryOutput )
{
// text subtitles
if ( hasTextSubs )
2021-07-24 18:52:16 +02:00
{
2021-12-01 17:49:50 +01:00
var textSubtitlesFilter = GetTextSubtitlesFilter ( state , false , false ) ;
mainFilters . Add ( textSubtitlesFilter ) ;
2021-07-24 18:52:16 +02:00
}
2021-12-01 17:49:50 +01:00
}
2021-07-24 18:52:16 +02:00
2022-06-14 16:18:22 +02:00
if ( ( isDxInDxOut | | isUploadForOclTonemap ) & & ! hasSubs )
2021-12-01 17:49:50 +01:00
{
// OUTPUT d3d11(nv12) surface(vram)
// reverse-mapping via d3d11-opencl interop.
mainFilters . Add ( "hwmap=derive_device=d3d11va:reverse=1" ) ;
mainFilters . Add ( "format=d3d11" ) ;
}
/* Make sub and overlay filters for subtitle stream */
var subFilters = new List < string > ( ) ;
var overlayFilters = new List < string > ( ) ;
2022-06-14 16:18:22 +02:00
if ( isDxInDxOut | | isUploadForOclTonemap )
2021-12-01 17:49:50 +01:00
{
if ( hasSubs )
{
if ( hasGraphicalSubs )
2021-07-24 18:52:16 +02:00
{
2021-12-01 17:49:50 +01:00
// scale=s=1280x720,format=yuva420p,hwupload
var subSwScaleFilter = GetCustomSwScaleFilter ( inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
subFilters . Add ( subSwScaleFilter ) ;
subFilters . Add ( "format=yuva420p" ) ;
}
else if ( hasTextSubs )
{
// alphasrc=s=1280x720:r=10:start=0,format=yuva420p,subtitles,hwupload
var alphaSrcFilter = GetAlphaSrcFilter ( state , inW , inH , reqW , reqH , reqMaxW , reqMaxH , hasAssSubs ? 10 : 5 ) ;
var subTextSubtitlesFilter = GetTextSubtitlesFilter ( state , true , true ) ;
subFilters . Add ( alphaSrcFilter ) ;
subFilters . Add ( "format=yuva420p" ) ;
subFilters . Add ( subTextSubtitlesFilter ) ;
2021-07-24 18:52:16 +02:00
}
2022-06-14 16:18:22 +02:00
subFilters . Add ( "hwupload=derive_device=opencl" ) ;
2021-12-01 17:49:50 +01:00
overlayFilters . Add ( "overlay_opencl=eof_action=endall:shortest=1:repeatlast=0" ) ;
overlayFilters . Add ( "hwmap=derive_device=d3d11va:reverse=1" ) ;
overlayFilters . Add ( "format=d3d11" ) ;
2021-07-24 18:52:16 +02:00
}
2021-12-01 17:49:50 +01:00
}
else if ( memoryOutput )
{
if ( hasGraphicalSubs )
2021-07-24 18:52:16 +02:00
{
2023-01-22 20:06:20 +01:00
var subSwScaleFilter = GetCustomSwScaleFilter ( inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
2021-12-01 17:49:50 +01:00
subFilters . Add ( subSwScaleFilter ) ;
overlayFilters . Add ( "overlay=eof_action=endall:shortest=1:repeatlast=0" ) ;
2021-07-24 18:52:16 +02:00
}
}
2021-12-24 09:50:40 +01:00
return ( mainFilters , subFilters , overlayFilters ) ;
2021-12-01 17:49:50 +01:00
}
/// <summary>
/// Gets the parameter of Intel QSV filter chain.
/// </summary>
/// <param name="state">Encoding state.</param>
/// <param name="options">Encoding options.</param>
/// <param name="vidEncoder">Video encoder to use.</param>
2021-12-26 19:08:43 +01:00
/// <returns>The tuple contains three lists: main, sub and overlay filters.</returns>
2021-12-24 22:18:24 +01:00
public ( List < string > MainFilters , List < string > SubFilters , List < string > OverlayFilters ) GetIntelVidFilterChain (
2021-12-01 17:49:50 +01:00
EncodingJobInfo state ,
EncodingOptions options ,
string vidEncoder )
{
if ( ! string . Equals ( options . HardwareAccelerationType , "qsv" , StringComparison . OrdinalIgnoreCase ) )
2021-01-25 20:45:56 +01:00
{
2021-12-24 09:50:40 +01:00
return ( null , null , null ) ;
2021-01-25 20:45:56 +01:00
}
2021-12-01 17:49:50 +01:00
var isWindows = OperatingSystem . IsWindows ( ) ;
var isLinux = OperatingSystem . IsLinux ( ) ;
var vidDecoder = GetHardwareVideoDecoder ( state , options ) ? ? string . Empty ;
var isSwDecoder = string . IsNullOrEmpty ( vidDecoder ) ;
var isSwEncoder = ! vidEncoder . Contains ( "qsv" , StringComparison . OrdinalIgnoreCase ) ;
var isQsvOclSupported = _mediaEncoder . SupportsHwaccel ( "qsv" ) & & IsOpenclFullSupported ( ) ;
var isIntelDx11OclSupported = isWindows
& & _mediaEncoder . SupportsHwaccel ( "d3d11va" )
& & isQsvOclSupported ;
var isIntelVaapiOclSupported = isLinux
& & IsVaapiSupported ( state )
& & isQsvOclSupported ;
// legacy qsv pipeline(copy-back)
if ( ( isSwDecoder & & isSwEncoder )
| | ( ! isIntelVaapiOclSupported & & ! isIntelDx11OclSupported )
| | ! _mediaEncoder . SupportsFilter ( "alphasrc" ) )
2021-01-24 20:40:34 +01:00
{
2021-12-01 17:49:50 +01:00
return GetSwVidFilterChain ( state , options , vidEncoder ) ;
}
2021-01-24 20:40:34 +01:00
2021-12-01 17:49:50 +01:00
// prefered qsv(vaapi) + opencl filters pipeline
if ( isIntelVaapiOclSupported )
{
return GetIntelQsvVaapiVidFiltersPrefered ( state , options , vidDecoder , vidEncoder ) ;
}
2021-01-24 20:40:34 +01:00
2021-12-01 17:49:50 +01:00
// prefered qsv(d3d11) + opencl filters pipeline
if ( isIntelDx11OclSupported )
{
return GetIntelQsvDx11VidFiltersPrefered ( state , options , vidDecoder , vidEncoder ) ;
}
2021-01-26 20:20:53 +01:00
2021-12-24 09:50:40 +01:00
return ( null , null , null ) ;
2021-12-01 17:49:50 +01:00
}
2021-12-24 22:18:24 +01:00
public ( List < string > MainFilters , List < string > SubFilters , List < string > OverlayFilters ) GetIntelQsvDx11VidFiltersPrefered (
2021-12-01 17:49:50 +01:00
EncodingJobInfo state ,
EncodingOptions options ,
string vidDecoder ,
string vidEncoder )
{
var inW = state . VideoStream ? . Width ;
var inH = state . VideoStream ? . Height ;
var reqW = state . BaseRequest . Width ;
var reqH = state . BaseRequest . Height ;
var reqMaxW = state . BaseRequest . MaxWidth ;
var reqMaxH = state . BaseRequest . MaxHeight ;
var threeDFormat = state . MediaSource . Video3DFormat ;
var isD3d11vaDecoder = vidDecoder . Contains ( "d3d11va" , StringComparison . OrdinalIgnoreCase ) ;
var isQsvDecoder = vidDecoder . Contains ( "qsv" , StringComparison . OrdinalIgnoreCase ) ;
var isQsvEncoder = vidEncoder . Contains ( "qsv" , StringComparison . OrdinalIgnoreCase ) ;
var isHwDecoder = isD3d11vaDecoder | | isQsvDecoder ;
var isSwDecoder = string . IsNullOrEmpty ( vidDecoder ) ;
var isSwEncoder = ! isQsvEncoder ;
var isQsvInQsvOut = isHwDecoder & & isQsvEncoder ;
var doDeintH264 = state . DeInterlace ( "h264" , true ) | | state . DeInterlace ( "avc" , true ) ;
var doDeintHevc = state . DeInterlace ( "h265" , true ) | | state . DeInterlace ( "hevc" , true ) ;
var doDeintH2645 = doDeintH264 | | doDeintHevc ;
var doOclTonemap = IsHwTonemapAvailable ( state , options ) ;
2022-12-05 15:01:13 +01:00
var hasSubs = state . SubtitleStream is not null & & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode ;
2021-12-01 17:49:50 +01:00
var hasTextSubs = hasSubs & & state . SubtitleStream . IsTextSubtitleStream ;
var hasGraphicalSubs = hasSubs & & ! state . SubtitleStream . IsTextSubtitleStream ;
var hasAssSubs = hasSubs
& & ( string . Equals ( state . SubtitleStream . Codec , "ass" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( state . SubtitleStream . Codec , "ssa" , StringComparison . OrdinalIgnoreCase ) ) ;
/* Make main filters for video stream */
var mainFilters = new List < string > ( ) ;
mainFilters . Add ( GetOverwriteColorPropertiesParam ( state , doOclTonemap ) ) ;
if ( isSwDecoder )
{
// INPUT sw surface(memory)
// sw deint
if ( doDeintH2645 )
{
var swDeintFilter = GetSwDeinterlaceFilter ( state , options ) ;
mainFilters . Add ( swDeintFilter ) ;
2021-01-24 20:40:34 +01:00
}
2023-06-19 17:01:15 +02:00
var outFormat = doOclTonemap ? "yuv420p10le" : ( hasGraphicalSubs ? "yuv420p" : "nv12" ) ;
2021-12-24 09:50:40 +01:00
var swScaleFilter = GetSwScaleFilter ( state , options , vidEncoder , inW , inH , threeDFormat , reqW , reqH , reqMaxW , reqMaxH ) ;
// sw scale
mainFilters . Add ( swScaleFilter ) ;
mainFilters . Add ( "format=" + outFormat ) ;
2021-12-01 17:49:50 +01:00
// keep video at memory except ocl tonemap,
// since the overhead caused by hwupload >>> using sw filter.
// sw => hw
if ( doOclTonemap )
{
2022-06-14 16:18:22 +02:00
mainFilters . Add ( "hwupload=derive_device=opencl" ) ;
2021-12-01 17:49:50 +01:00
}
}
else if ( isD3d11vaDecoder | | isQsvDecoder )
{
var outFormat = doOclTonemap ? string . Empty : "nv12" ;
var hwScaleFilter = GetHwScaleFilter ( "qsv" , outFormat , inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
if ( isD3d11vaDecoder )
2021-01-24 20:40:34 +01:00
{
2021-12-01 17:49:50 +01:00
if ( ! string . IsNullOrEmpty ( hwScaleFilter ) | | doDeintH2645 )
2021-01-24 20:40:34 +01:00
{
2021-12-01 17:49:50 +01:00
// INPUT d3d11 surface(vram)
// map from d3d11va to qsv.
mainFilters . Add ( "hwmap=derive_device=qsv" ) ;
2021-01-24 20:40:34 +01:00
}
2022-10-29 04:39:01 +02:00
else
{
// Insert a qsv scaler to sync the decoder surface,
// msdk will passthrough this internally.
mainFilters . Add ( "hwmap=derive_device=qsv,scale_qsv" ) ;
}
2021-12-01 17:49:50 +01:00
}
2021-01-24 20:40:34 +01:00
2021-12-01 17:49:50 +01:00
// hw deint
if ( doDeintH2645 )
{
var deintFilter = GetHwDeinterlaceFilter ( state , options , "qsv" ) ;
mainFilters . Add ( deintFilter ) ;
2021-01-24 20:40:34 +01:00
}
2021-12-24 09:50:40 +01:00
// hw scale
mainFilters . Add ( hwScaleFilter ) ;
2021-01-24 20:40:34 +01:00
}
2021-12-01 17:49:50 +01:00
if ( doOclTonemap & & isHwDecoder )
{
// map from qsv to opencl via qsv(d3d11)-opencl interop.
mainFilters . Add ( "hwmap=derive_device=opencl" ) ;
}
// hw tonemap
if ( doOclTonemap )
{
var tonemapFilter = GetHwTonemapFilter ( options , "opencl" , "nv12" ) ;
mainFilters . Add ( tonemapFilter ) ;
}
var memoryOutput = false ;
var isUploadForOclTonemap = isSwDecoder & & doOclTonemap ;
var isHwmapUsable = isSwEncoder & & doOclTonemap ;
if ( ( isHwDecoder & & isSwEncoder ) | | isUploadForOclTonemap )
{
memoryOutput = true ;
// OUTPUT nv12 surface(memory)
// prefer hwmap to hwdownload on opencl.
// qsv hwmap is not fully implemented for the time being.
2023-03-10 01:33:52 +01:00
mainFilters . Add ( isHwmapUsable ? "hwmap=mode=read" : "hwdownload" ) ;
2021-12-01 17:49:50 +01:00
mainFilters . Add ( "format=nv12" ) ;
}
// OUTPUT nv12 surface(memory)
if ( isSwDecoder & & isQsvEncoder )
{
memoryOutput = true ;
}
if ( memoryOutput )
2020-03-03 16:56:50 +01:00
{
2021-12-01 17:49:50 +01:00
// text subtitles
2020-07-20 14:48:20 +02:00
if ( hasTextSubs )
2020-03-03 16:56:50 +01:00
{
2021-12-01 17:49:50 +01:00
var textSubtitlesFilter = GetTextSubtitlesFilter ( state , false , false ) ;
mainFilters . Add ( textSubtitlesFilter ) ;
}
}
if ( isQsvInQsvOut & & doOclTonemap )
{
// OUTPUT qsv(nv12) surface(vram)
// reverse-mapping via qsv(d3d11)-opencl interop.
2021-12-24 09:50:40 +01:00
mainFilters . Add ( "hwmap=derive_device=qsv:reverse=1" ) ;
2021-12-01 17:49:50 +01:00
mainFilters . Add ( "format=qsv" ) ;
}
/* Make sub and overlay filters for subtitle stream */
var subFilters = new List < string > ( ) ;
var overlayFilters = new List < string > ( ) ;
if ( isQsvInQsvOut )
{
if ( hasSubs )
{
if ( hasGraphicalSubs )
{
// scale,format=bgra,hwupload
// overlay_qsv can handle overlay scaling,
// add a dummy scale filter to pair with -canvas_size.
subFilters . Add ( "scale=flags=fast_bilinear" ) ;
subFilters . Add ( "format=bgra" ) ;
}
else if ( hasTextSubs )
2020-11-24 15:09:13 +01:00
{
2021-12-01 17:49:50 +01:00
// alphasrc=s=1280x720:r=10:start=0,format=bgra,subtitles,hwupload
var alphaSrcFilter = GetAlphaSrcFilter ( state , inW , inH , reqW , reqH , reqMaxW , 1080 , hasAssSubs ? 10 : 5 ) ;
var subTextSubtitlesFilter = GetTextSubtitlesFilter ( state , true , true ) ;
subFilters . Add ( alphaSrcFilter ) ;
subFilters . Add ( "format=bgra" ) ;
subFilters . Add ( subTextSubtitlesFilter ) ;
2020-11-24 15:09:13 +01:00
}
2021-12-01 17:49:50 +01:00
// qsv requires a fixed pool size.
2022-04-05 00:05:50 +02:00
// default to 64 otherwise it will fail on certain iGPU.
2022-06-14 16:18:22 +02:00
subFilters . Add ( "hwupload=derive_device=qsv:extra_hw_frames=64" ) ;
2021-12-01 17:49:50 +01:00
var ( overlayW , overlayH ) = GetFixedOutputSize ( inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
var overlaySize = ( overlayW . HasValue & & overlayH . HasValue )
? ( ":w=" + overlayW . Value + ":h=" + overlayH . Value )
: string . Empty ;
var overlayQsvFilter = string . Format (
CultureInfo . InvariantCulture ,
"overlay_qsv=eof_action=endall:shortest=1:repeatlast=0{0}" ,
overlaySize ) ;
overlayFilters . Add ( overlayQsvFilter ) ;
2020-03-03 16:56:50 +01:00
}
}
2021-12-01 17:49:50 +01:00
else if ( memoryOutput )
2018-12-28 00:27:57 +01:00
{
2021-12-01 17:49:50 +01:00
if ( hasGraphicalSubs )
{
2023-01-22 20:06:20 +01:00
var subSwScaleFilter = GetCustomSwScaleFilter ( inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
2021-12-01 17:49:50 +01:00
subFilters . Add ( subSwScaleFilter ) ;
overlayFilters . Add ( "overlay=eof_action=endall:shortest=1:repeatlast=0" ) ;
}
}
2021-12-24 09:50:40 +01:00
return ( mainFilters , subFilters , overlayFilters ) ;
2021-12-01 17:49:50 +01:00
}
2021-12-24 22:18:24 +01:00
public ( List < string > MainFilters , List < string > SubFilters , List < string > OverlayFilters ) GetIntelQsvVaapiVidFiltersPrefered (
2021-12-01 17:49:50 +01:00
EncodingJobInfo state ,
EncodingOptions options ,
string vidDecoder ,
string vidEncoder )
{
var inW = state . VideoStream ? . Width ;
var inH = state . VideoStream ? . Height ;
var reqW = state . BaseRequest . Width ;
var reqH = state . BaseRequest . Height ;
var reqMaxW = state . BaseRequest . MaxWidth ;
var reqMaxH = state . BaseRequest . MaxHeight ;
var threeDFormat = state . MediaSource . Video3DFormat ;
var isVaapiDecoder = vidDecoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
var isQsvDecoder = vidDecoder . Contains ( "qsv" , StringComparison . OrdinalIgnoreCase ) ;
var isQsvEncoder = vidEncoder . Contains ( "qsv" , StringComparison . OrdinalIgnoreCase ) ;
var isHwDecoder = isVaapiDecoder | | isQsvDecoder ;
var isSwDecoder = string . IsNullOrEmpty ( vidDecoder ) ;
var isSwEncoder = ! isQsvEncoder ;
var isQsvInQsvOut = isHwDecoder & & isQsvEncoder ;
var doDeintH264 = state . DeInterlace ( "h264" , true ) | | state . DeInterlace ( "avc" , true ) ;
var doDeintHevc = state . DeInterlace ( "h265" , true ) | | state . DeInterlace ( "hevc" , true ) ;
var doVaVppTonemap = IsVaapiVppTonemapAvailable ( state , options ) ;
var doOclTonemap = ! doVaVppTonemap & & IsHwTonemapAvailable ( state , options ) ;
var doTonemap = doVaVppTonemap | | doOclTonemap ;
var doDeintH2645 = doDeintH264 | | doDeintHevc ;
2022-12-05 15:01:13 +01:00
var hasSubs = state . SubtitleStream is not null & & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode ;
2021-12-01 17:49:50 +01:00
var hasTextSubs = hasSubs & & state . SubtitleStream . IsTextSubtitleStream ;
var hasGraphicalSubs = hasSubs & & ! state . SubtitleStream . IsTextSubtitleStream ;
var hasAssSubs = hasSubs
& & ( string . Equals ( state . SubtitleStream . Codec , "ass" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( state . SubtitleStream . Codec , "ssa" , StringComparison . OrdinalIgnoreCase ) ) ;
/* Make main filters for video stream */
var mainFilters = new List < string > ( ) ;
2018-12-28 00:27:57 +01:00
2021-12-01 17:49:50 +01:00
mainFilters . Add ( GetOverwriteColorPropertiesParam ( state , doTonemap ) ) ;
2018-12-28 00:27:57 +01:00
2021-12-01 17:49:50 +01:00
if ( isSwDecoder )
{
// INPUT sw surface(memory)
// sw deint
if ( doDeintH2645 )
2019-01-27 09:44:56 +01:00
{
2021-12-01 17:49:50 +01:00
var swDeintFilter = GetSwDeinterlaceFilter ( state , options ) ;
mainFilters . Add ( swDeintFilter ) ;
2019-01-27 09:44:56 +01:00
}
2021-01-24 20:40:34 +01:00
2023-06-19 17:01:15 +02:00
var outFormat = doOclTonemap ? "yuv420p10le" : ( hasGraphicalSubs ? "yuv420p" : "nv12" ) ;
2021-12-24 09:50:40 +01:00
var swScaleFilter = GetSwScaleFilter ( state , options , vidEncoder , inW , inH , threeDFormat , reqW , reqH , reqMaxW , reqMaxH ) ;
// sw scale
mainFilters . Add ( swScaleFilter ) ;
mainFilters . Add ( "format=" + outFormat ) ;
2021-12-01 17:49:50 +01:00
// keep video at memory except ocl tonemap,
// since the overhead caused by hwupload >>> using sw filter.
// sw => hw
if ( doOclTonemap )
{
2022-06-14 16:18:22 +02:00
mainFilters . Add ( "hwupload=derive_device=opencl" ) ;
2021-12-01 17:49:50 +01:00
}
}
else if ( isVaapiDecoder | | isQsvDecoder )
{
// INPUT vaapi/qsv surface(vram)
2021-12-24 09:50:40 +01:00
// hw deint
if ( doDeintH2645 )
{
var deintFilter = GetHwDeinterlaceFilter ( state , options , isVaapiDecoder ? "vaapi" : "qsv" ) ;
mainFilters . Add ( deintFilter ) ;
}
2021-12-01 17:49:50 +01:00
var outFormat = doTonemap ? string . Empty : "nv12" ;
var hwScaleFilter = GetHwScaleFilter ( isVaapiDecoder ? "vaapi" : "qsv" , outFormat , inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
2023-03-10 01:33:52 +01:00
// allocate extra pool sizes for vaapi vpp
if ( ! string . IsNullOrEmpty ( hwScaleFilter ) & & isVaapiDecoder )
{
hwScaleFilter + = ":extra_hw_frames=24" ;
}
2021-12-01 17:49:50 +01:00
// hw scale
mainFilters . Add ( hwScaleFilter ) ;
}
// vaapi vpp tonemap
if ( doVaVppTonemap & & isHwDecoder )
{
if ( isQsvDecoder )
{
// map from qsv to vaapi.
mainFilters . Add ( "hwmap=derive_device=vaapi" ) ;
}
var tonemapFilter = GetHwTonemapFilter ( options , "vaapi" , "nv12" ) ;
mainFilters . Add ( tonemapFilter ) ;
if ( isQsvDecoder )
{
// map from vaapi to qsv.
mainFilters . Add ( "hwmap=derive_device=qsv" ) ;
}
}
if ( doOclTonemap & & isHwDecoder )
{
// map from qsv to opencl via qsv(vaapi)-opencl interop.
mainFilters . Add ( "hwmap=derive_device=opencl" ) ;
}
// ocl tonemap
if ( doOclTonemap )
{
var tonemapFilter = GetHwTonemapFilter ( options , "opencl" , "nv12" ) ;
mainFilters . Add ( tonemapFilter ) ;
}
var memoryOutput = false ;
var isUploadForOclTonemap = isSwDecoder & & doOclTonemap ;
var isHwmapUsable = isSwEncoder & & ( doOclTonemap | | isVaapiDecoder ) ;
if ( ( isHwDecoder & & isSwEncoder ) | | isUploadForOclTonemap )
{
memoryOutput = true ;
// OUTPUT nv12 surface(memory)
// prefer hwmap to hwdownload on opencl/vaapi.
// qsv hwmap is not fully implemented for the time being.
2023-03-10 01:33:52 +01:00
mainFilters . Add ( isHwmapUsable ? "hwmap=mode=read" : "hwdownload" ) ;
2021-12-01 17:49:50 +01:00
mainFilters . Add ( "format=nv12" ) ;
}
// OUTPUT nv12 surface(memory)
if ( isSwDecoder & & isQsvEncoder )
{
memoryOutput = true ;
}
if ( memoryOutput )
{
// text subtitles
if ( hasTextSubs )
{
var textSubtitlesFilter = GetTextSubtitlesFilter ( state , false , false ) ;
mainFilters . Add ( textSubtitlesFilter ) ;
}
}
if ( isQsvInQsvOut )
{
if ( doOclTonemap )
{
// OUTPUT qsv(nv12) surface(vram)
// reverse-mapping via qsv(vaapi)-opencl interop.
2021-12-24 09:50:40 +01:00
// add extra pool size to avoid the 'cannot allocate memory' error on hevc_qsv.
2021-12-01 17:49:50 +01:00
mainFilters . Add ( "hwmap=derive_device=qsv:reverse=1:extra_hw_frames=16" ) ;
mainFilters . Add ( "format=qsv" ) ;
}
else if ( isVaapiDecoder )
{
mainFilters . Add ( "hwmap=derive_device=qsv" ) ;
mainFilters . Add ( "format=qsv" ) ;
}
}
/* Make sub and overlay filters for subtitle stream */
var subFilters = new List < string > ( ) ;
var overlayFilters = new List < string > ( ) ;
if ( isQsvInQsvOut )
{
if ( hasSubs )
{
if ( hasGraphicalSubs )
{
subFilters . Add ( "scale=flags=fast_bilinear" ) ;
subFilters . Add ( "format=bgra" ) ;
}
else if ( hasTextSubs )
{
var alphaSrcFilter = GetAlphaSrcFilter ( state , inW , inH , reqW , reqH , reqMaxW , 1080 , hasAssSubs ? 10 : 5 ) ;
var subTextSubtitlesFilter = GetTextSubtitlesFilter ( state , true , true ) ;
subFilters . Add ( alphaSrcFilter ) ;
subFilters . Add ( "format=bgra" ) ;
subFilters . Add ( subTextSubtitlesFilter ) ;
}
// qsv requires a fixed pool size.
2022-04-05 00:05:50 +02:00
// default to 64 otherwise it will fail on certain iGPU.
2022-06-14 16:18:22 +02:00
subFilters . Add ( "hwupload=derive_device=qsv:extra_hw_frames=64" ) ;
2021-12-01 17:49:50 +01:00
var ( overlayW , overlayH ) = GetFixedOutputSize ( inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
var overlaySize = ( overlayW . HasValue & & overlayH . HasValue )
? ( ":w=" + overlayW . Value + ":h=" + overlayH . Value )
: string . Empty ;
var overlayQsvFilter = string . Format (
CultureInfo . InvariantCulture ,
"overlay_qsv=eof_action=endall:shortest=1:repeatlast=0{0}" ,
overlaySize ) ;
overlayFilters . Add ( overlayQsvFilter ) ;
}
}
else if ( memoryOutput )
{
if ( hasGraphicalSubs )
{
2023-01-22 20:06:20 +01:00
var subSwScaleFilter = GetCustomSwScaleFilter ( inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
2021-12-01 17:49:50 +01:00
subFilters . Add ( subSwScaleFilter ) ;
overlayFilters . Add ( "overlay=eof_action=pass:shortest=1:repeatlast=0" ) ;
}
}
2021-12-24 09:50:40 +01:00
return ( mainFilters , subFilters , overlayFilters ) ;
2021-12-01 17:49:50 +01:00
}
/// <summary>
/// Gets the parameter of Intel/AMD VAAPI filter chain.
/// </summary>
/// <param name="state">Encoding state.</param>
/// <param name="options">Encoding options.</param>
/// <param name="vidEncoder">Video encoder to use.</param>
2021-12-26 19:08:43 +01:00
/// <returns>The tuple contains three lists: main, sub and overlay filters.</returns>
2021-12-24 22:18:24 +01:00
public ( List < string > MainFilters , List < string > SubFilters , List < string > OverlayFilters ) GetVaapiVidFilterChain (
2021-12-01 17:49:50 +01:00
EncodingJobInfo state ,
EncodingOptions options ,
string vidEncoder )
{
if ( ! string . Equals ( options . HardwareAccelerationType , "vaapi" , StringComparison . OrdinalIgnoreCase ) )
{
2021-12-24 09:50:40 +01:00
return ( null , null , null ) ;
2021-12-01 17:49:50 +01:00
}
var isLinux = OperatingSystem . IsLinux ( ) ;
var vidDecoder = GetHardwareVideoDecoder ( state , options ) ? ? string . Empty ;
var isSwDecoder = string . IsNullOrEmpty ( vidDecoder ) ;
var isSwEncoder = ! vidEncoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
2022-10-16 17:08:59 +02:00
var isVaapiFullSupported = isLinux & & IsVaapiSupported ( state ) & & IsVaapiFullSupported ( ) ;
var isVaapiOclSupported = isVaapiFullSupported & & IsOpenclFullSupported ( ) ;
var isVaapiVkSupported = isVaapiFullSupported & & IsVulkanFullSupported ( ) ;
2021-12-01 17:49:50 +01:00
// legacy vaapi pipeline(copy-back)
if ( ( isSwDecoder & & isSwEncoder )
| | ! isVaapiOclSupported
| | ! _mediaEncoder . SupportsFilter ( "alphasrc" ) )
{
var swFilterChain = GetSwVidFilterChain ( state , options , vidEncoder ) ;
if ( ! isSwEncoder )
{
var newfilters = new List < string > ( ) ;
2021-12-24 22:18:24 +01:00
var noOverlay = swFilterChain . OverlayFilters . Count = = 0 ;
newfilters . AddRange ( noOverlay ? swFilterChain . MainFilters : swFilterChain . OverlayFilters ) ;
2022-06-14 16:18:22 +02:00
newfilters . Add ( "hwupload=derive_device=vaapi" ) ;
2021-12-01 17:49:50 +01:00
2021-12-24 22:18:24 +01:00
var mainFilters = noOverlay ? newfilters : swFilterChain . MainFilters ;
var overlayFilters = noOverlay ? swFilterChain . OverlayFilters : newfilters ;
return ( mainFilters , swFilterChain . SubFilters , overlayFilters ) ;
2021-12-01 17:49:50 +01:00
}
return swFilterChain ;
}
// prefered vaapi + opencl filters pipeline
2021-12-24 09:50:40 +01:00
if ( _mediaEncoder . IsVaapiDeviceInteliHD )
2021-12-01 17:49:50 +01:00
{
// Intel iHD path, with extra vpp tonemap and overlay support.
2022-10-16 17:08:59 +02:00
return GetIntelVaapiFullVidFiltersPrefered ( state , options , vidDecoder , vidEncoder ) ;
}
// prefered vaapi + vulkan filters pipeline
if ( _mediaEncoder . IsVaapiDeviceAmd
& & isVaapiVkSupported
& & _mediaEncoder . IsVaapiDeviceSupportVulkanFmtModifier
& & Environment . OSVersion . Version > = _minKernelVersionAmdVkFmtModifier )
{
// AMD radeonsi path(Vega/gfx9+, kernel>=5.15), with extra vulkan tonemap and overlay support.
return GetAmdVaapiFullVidFiltersPrefered ( state , options , vidDecoder , vidEncoder ) ;
2021-12-01 17:49:50 +01:00
}
2022-10-16 17:08:59 +02:00
// Intel i965 and Amd radeonsi/r600 path(Polaris/gfx8-), only featuring scale and deinterlace support.
2021-12-01 17:49:50 +01:00
return GetVaapiLimitedVidFiltersPrefered ( state , options , vidDecoder , vidEncoder ) ;
}
2022-10-16 17:08:59 +02:00
public ( List < string > MainFilters , List < string > SubFilters , List < string > OverlayFilters ) GetIntelVaapiFullVidFiltersPrefered (
2021-12-01 17:49:50 +01:00
EncodingJobInfo state ,
EncodingOptions options ,
string vidDecoder ,
string vidEncoder )
{
var inW = state . VideoStream ? . Width ;
var inH = state . VideoStream ? . Height ;
var reqW = state . BaseRequest . Width ;
var reqH = state . BaseRequest . Height ;
var reqMaxW = state . BaseRequest . MaxWidth ;
var reqMaxH = state . BaseRequest . MaxHeight ;
var threeDFormat = state . MediaSource . Video3DFormat ;
var isVaapiDecoder = vidDecoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
var isVaapiEncoder = vidEncoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
var isSwDecoder = string . IsNullOrEmpty ( vidDecoder ) ;
var isSwEncoder = ! isVaapiEncoder ;
var isVaInVaOut = isVaapiDecoder & & isVaapiEncoder ;
var doDeintH264 = state . DeInterlace ( "h264" , true ) | | state . DeInterlace ( "avc" , true ) ;
var doDeintHevc = state . DeInterlace ( "h265" , true ) | | state . DeInterlace ( "hevc" , true ) ;
var doVaVppTonemap = isVaapiDecoder & & IsVaapiVppTonemapAvailable ( state , options ) ;
var doOclTonemap = ! doVaVppTonemap & & IsHwTonemapAvailable ( state , options ) ;
var doTonemap = doVaVppTonemap | | doOclTonemap ;
var doDeintH2645 = doDeintH264 | | doDeintHevc ;
2022-12-05 15:01:13 +01:00
var hasSubs = state . SubtitleStream is not null & & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode ;
2021-12-01 17:49:50 +01:00
var hasTextSubs = hasSubs & & state . SubtitleStream . IsTextSubtitleStream ;
var hasGraphicalSubs = hasSubs & & ! state . SubtitleStream . IsTextSubtitleStream ;
var hasAssSubs = hasSubs
& & ( string . Equals ( state . SubtitleStream . Codec , "ass" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( state . SubtitleStream . Codec , "ssa" , StringComparison . OrdinalIgnoreCase ) ) ;
/* Make main filters for video stream */
var mainFilters = new List < string > ( ) ;
mainFilters . Add ( GetOverwriteColorPropertiesParam ( state , doTonemap ) ) ;
if ( isSwDecoder )
{
// INPUT sw surface(memory)
// sw deint
if ( doDeintH2645 )
{
var swDeintFilter = GetSwDeinterlaceFilter ( state , options ) ;
mainFilters . Add ( swDeintFilter ) ;
}
2021-12-24 09:50:40 +01:00
var outFormat = doOclTonemap ? "yuv420p10le" : "nv12" ;
var swScaleFilter = GetSwScaleFilter ( state , options , vidEncoder , inW , inH , threeDFormat , reqW , reqH , reqMaxW , reqMaxH ) ;
// sw scale
mainFilters . Add ( swScaleFilter ) ;
mainFilters . Add ( "format=" + outFormat ) ;
2021-12-01 17:49:50 +01:00
// keep video at memory except ocl tonemap,
// since the overhead caused by hwupload >>> using sw filter.
// sw => hw
if ( doOclTonemap )
{
2022-06-14 16:18:22 +02:00
mainFilters . Add ( "hwupload=derive_device=opencl" ) ;
2021-12-01 17:49:50 +01:00
}
}
else if ( isVaapiDecoder )
{
// INPUT vaapi surface(vram)
2021-12-24 09:50:40 +01:00
// hw deint
if ( doDeintH2645 )
{
var deintFilter = GetHwDeinterlaceFilter ( state , options , "vaapi" ) ;
mainFilters . Add ( deintFilter ) ;
}
2021-12-01 17:49:50 +01:00
var outFormat = doTonemap ? string . Empty : "nv12" ;
var hwScaleFilter = GetHwScaleFilter ( "vaapi" , outFormat , inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
2023-03-10 01:33:52 +01:00
// allocate extra pool sizes for vaapi vpp
if ( ! string . IsNullOrEmpty ( hwScaleFilter ) )
{
hwScaleFilter + = ":extra_hw_frames=24" ;
}
2021-12-01 17:49:50 +01:00
// hw scale
mainFilters . Add ( hwScaleFilter ) ;
}
// vaapi vpp tonemap
if ( doVaVppTonemap & & isVaapiDecoder )
{
var tonemapFilter = GetHwTonemapFilter ( options , "vaapi" , "nv12" ) ;
mainFilters . Add ( tonemapFilter ) ;
}
if ( doOclTonemap & & isVaapiDecoder )
{
// map from vaapi to opencl via vaapi-opencl interop(Intel only).
mainFilters . Add ( "hwmap=derive_device=opencl" ) ;
}
// ocl tonemap
if ( doOclTonemap )
{
var tonemapFilter = GetHwTonemapFilter ( options , "opencl" , "nv12" ) ;
mainFilters . Add ( tonemapFilter ) ;
}
if ( doOclTonemap & & isVaInVaOut )
{
// OUTPUT vaapi(nv12) surface(vram)
// reverse-mapping via vaapi-opencl interop.
mainFilters . Add ( "hwmap=derive_device=vaapi:reverse=1" ) ;
mainFilters . Add ( "format=vaapi" ) ;
}
var memoryOutput = false ;
var isUploadForOclTonemap = isSwDecoder & & doOclTonemap ;
var isHwmapNotUsable = isUploadForOclTonemap & & isVaapiEncoder ;
if ( ( isVaapiDecoder & & isSwEncoder ) | | isUploadForOclTonemap )
{
memoryOutput = true ;
// OUTPUT nv12 surface(memory)
// prefer hwmap to hwdownload on opencl/vaapi.
2023-03-10 01:33:52 +01:00
mainFilters . Add ( isHwmapNotUsable ? "hwdownload" : "hwmap=mode=read" ) ;
2021-12-01 17:49:50 +01:00
mainFilters . Add ( "format=nv12" ) ;
}
// OUTPUT nv12 surface(memory)
if ( isSwDecoder & & isVaapiEncoder )
{
memoryOutput = true ;
}
if ( memoryOutput )
{
// text subtitles
if ( hasTextSubs )
{
var textSubtitlesFilter = GetTextSubtitlesFilter ( state , false , false ) ;
mainFilters . Add ( textSubtitlesFilter ) ;
}
}
if ( memoryOutput & & isVaapiEncoder )
{
if ( ! hasGraphicalSubs )
{
mainFilters . Add ( "hwupload_vaapi" ) ;
}
}
/* Make sub and overlay filters for subtitle stream */
var subFilters = new List < string > ( ) ;
var overlayFilters = new List < string > ( ) ;
if ( isVaInVaOut )
{
if ( hasSubs )
{
if ( hasGraphicalSubs )
{
subFilters . Add ( "scale=flags=fast_bilinear" ) ;
subFilters . Add ( "format=bgra" ) ;
}
else if ( hasTextSubs )
{
var alphaSrcFilter = GetAlphaSrcFilter ( state , inW , inH , reqW , reqH , reqMaxW , 1080 , hasAssSubs ? 10 : 5 ) ;
var subTextSubtitlesFilter = GetTextSubtitlesFilter ( state , true , true ) ;
subFilters . Add ( alphaSrcFilter ) ;
subFilters . Add ( "format=bgra" ) ;
subFilters . Add ( subTextSubtitlesFilter ) ;
}
2022-06-14 16:18:22 +02:00
subFilters . Add ( "hwupload=derive_device=vaapi" ) ;
2021-12-01 17:49:50 +01:00
var ( overlayW , overlayH ) = GetFixedOutputSize ( inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
var overlaySize = ( overlayW . HasValue & & overlayH . HasValue )
? ( ":w=" + overlayW . Value + ":h=" + overlayH . Value )
: string . Empty ;
var overlayVaapiFilter = string . Format (
CultureInfo . InvariantCulture ,
"overlay_vaapi=eof_action=endall:shortest=1:repeatlast=0{0}" ,
overlaySize ) ;
overlayFilters . Add ( overlayVaapiFilter ) ;
}
}
else if ( memoryOutput )
{
if ( hasGraphicalSubs )
{
2023-01-22 20:06:20 +01:00
var subSwScaleFilter = GetCustomSwScaleFilter ( inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
2021-12-01 17:49:50 +01:00
subFilters . Add ( subSwScaleFilter ) ;
overlayFilters . Add ( "overlay=eof_action=pass:shortest=1:repeatlast=0" ) ;
if ( isVaapiEncoder )
{
overlayFilters . Add ( "hwupload_vaapi" ) ;
}
}
}
2022-10-16 17:08:59 +02:00
return ( mainFilters , subFilters , overlayFilters ) ;
}
public ( List < string > MainFilters , List < string > SubFilters , List < string > OverlayFilters ) GetAmdVaapiFullVidFiltersPrefered (
EncodingJobInfo state ,
EncodingOptions options ,
string vidDecoder ,
string vidEncoder )
{
var inW = state . VideoStream ? . Width ;
var inH = state . VideoStream ? . Height ;
var reqW = state . BaseRequest . Width ;
var reqH = state . BaseRequest . Height ;
var reqMaxW = state . BaseRequest . MaxWidth ;
var reqMaxH = state . BaseRequest . MaxHeight ;
var threeDFormat = state . MediaSource . Video3DFormat ;
var isVaapiDecoder = vidDecoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
var isVaapiEncoder = vidEncoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
var isSwDecoder = string . IsNullOrEmpty ( vidDecoder ) ;
var isSwEncoder = ! isVaapiEncoder ;
var doDeintH264 = state . DeInterlace ( "h264" , true ) | | state . DeInterlace ( "avc" , true ) ;
var doDeintHevc = state . DeInterlace ( "h265" , true ) | | state . DeInterlace ( "hevc" , true ) ;
var doVkTonemap = IsVulkanHwTonemapAvailable ( state , options ) ;
var doDeintH2645 = doDeintH264 | | doDeintHevc ;
2022-12-05 15:01:13 +01:00
var hasSubs = state . SubtitleStream is not null & & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode ;
2022-10-16 17:08:59 +02:00
var hasTextSubs = hasSubs & & state . SubtitleStream . IsTextSubtitleStream ;
var hasGraphicalSubs = hasSubs & & ! state . SubtitleStream . IsTextSubtitleStream ;
var hasAssSubs = hasSubs
& & ( string . Equals ( state . SubtitleStream . Codec , "ass" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( state . SubtitleStream . Codec , "ssa" , StringComparison . OrdinalIgnoreCase ) ) ;
/* Make main filters for video stream */
var mainFilters = new List < string > ( ) ;
mainFilters . Add ( GetOverwriteColorPropertiesParam ( state , doVkTonemap ) ) ;
if ( isSwDecoder )
{
// INPUT sw surface(memory)
// sw deint
if ( doDeintH2645 )
{
var swDeintFilter = GetSwDeinterlaceFilter ( state , options ) ;
mainFilters . Add ( swDeintFilter ) ;
}
2023-06-12 19:13:48 +02:00
if ( doVkTonemap | | hasSubs )
2022-10-16 17:08:59 +02:00
{
2023-06-12 19:13:48 +02:00
// sw => hw
mainFilters . Add ( "hwupload=derive_device=vulkan" ) ;
2023-03-04 17:22:43 +01:00
mainFilters . Add ( "format=vulkan" ) ;
2022-10-16 17:08:59 +02:00
}
2023-06-12 19:13:48 +02:00
else
{
// sw scale
var swScaleFilter = GetSwScaleFilter ( state , options , vidEncoder , inW , inH , threeDFormat , reqW , reqH , reqMaxW , reqMaxH ) ;
mainFilters . Add ( swScaleFilter ) ;
mainFilters . Add ( "format=nv12" ) ;
}
2022-10-16 17:08:59 +02:00
}
else if ( isVaapiDecoder )
{
// INPUT vaapi surface(vram)
2023-06-12 19:13:48 +02:00
if ( doVkTonemap | | hasSubs )
2022-10-16 17:08:59 +02:00
{
2023-06-12 19:13:48 +02:00
// map from vaapi to vulkan/drm via interop (Vega/gfx9+).
mainFilters . Add ( "hwmap=derive_device=vulkan" ) ;
mainFilters . Add ( "format=vulkan" ) ;
2022-10-16 17:08:59 +02:00
}
2023-06-12 19:13:48 +02:00
else
2022-10-16 17:08:59 +02:00
{
2023-06-12 19:13:48 +02:00
// hw deint
if ( doDeintH2645 )
{
var deintFilter = GetHwDeinterlaceFilter ( state , options , "vaapi" ) ;
mainFilters . Add ( deintFilter ) ;
}
2022-10-16 17:08:59 +02:00
2023-06-12 19:13:48 +02:00
// hw scale
var hwScaleFilter = GetHwScaleFilter ( "vaapi" , "nv12" , inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
mainFilters . Add ( hwScaleFilter ) ;
}
2022-10-16 17:08:59 +02:00
}
2023-06-12 19:13:48 +02:00
// vk libplacebo
if ( doVkTonemap | | hasSubs )
2022-10-16 17:08:59 +02:00
{
2023-06-12 19:13:48 +02:00
var libplaceboFilter = GetLibplaceboFilter ( options , "bgra" , doVkTonemap , inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
mainFilters . Add ( libplaceboFilter ) ;
2022-10-16 17:08:59 +02:00
}
2023-06-12 19:13:48 +02:00
if ( doVkTonemap & & ! hasSubs )
2022-10-16 17:08:59 +02:00
{
2023-06-12 19:13:48 +02:00
// OUTPUT vaapi(nv12) surface(vram)
// map from vulkan/drm to vaapi via interop (Vega/gfx9+).
mainFilters . Add ( "hwmap=derive_device=drm" ) ;
mainFilters . Add ( "format=drm_prime" ) ;
mainFilters . Add ( "hwmap=derive_device=vaapi" ) ;
2022-10-16 17:08:59 +02:00
mainFilters . Add ( "format=vaapi" ) ;
2023-06-12 19:13:48 +02:00
// clear the surf->meta_offset and output nv12
mainFilters . Add ( "scale_vaapi=format=nv12" ) ;
2022-10-16 17:08:59 +02:00
2023-06-12 19:13:48 +02:00
// hw deint
if ( doDeintH2645 )
{
var deintFilter = GetHwDeinterlaceFilter ( state , options , "vaapi" ) ;
mainFilters . Add ( deintFilter ) ;
}
2022-10-16 17:08:59 +02:00
}
2023-06-12 19:13:48 +02:00
if ( ! hasSubs )
2022-10-16 17:08:59 +02:00
{
2023-06-12 19:13:48 +02:00
// OUTPUT nv12 surface(memory)
if ( isSwEncoder & & ( doVkTonemap | | isVaapiDecoder ) )
2022-10-16 17:08:59 +02:00
{
2023-06-12 19:13:48 +02:00
mainFilters . Add ( "hwdownload" ) ;
mainFilters . Add ( "format=nv12" ) ;
2022-10-16 17:08:59 +02:00
}
2023-06-12 19:13:48 +02:00
if ( isSwDecoder & & isVaapiEncoder & & ! doVkTonemap )
2022-10-16 17:08:59 +02:00
{
mainFilters . Add ( "hwupload_vaapi" ) ;
}
}
/* Make sub and overlay filters for subtitle stream */
var subFilters = new List < string > ( ) ;
var overlayFilters = new List < string > ( ) ;
2023-06-12 19:13:48 +02:00
if ( hasSubs )
2022-10-16 17:08:59 +02:00
{
2023-06-12 19:13:48 +02:00
if ( hasGraphicalSubs )
2022-10-16 17:08:59 +02:00
{
2023-06-12 19:13:48 +02:00
// scale=s=1280x720,format=bgra,hwupload
var subSwScaleFilter = GetCustomSwScaleFilter ( inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
subFilters . Add ( subSwScaleFilter ) ;
subFilters . Add ( "format=bgra" ) ;
}
else if ( hasTextSubs )
{
var alphaSrcFilter = GetAlphaSrcFilter ( state , inW , inH , reqW , reqH , reqMaxW , reqMaxH , hasAssSubs ? 10 : 5 ) ;
var subTextSubtitlesFilter = GetTextSubtitlesFilter ( state , true , true ) ;
subFilters . Add ( alphaSrcFilter ) ;
subFilters . Add ( "format=bgra" ) ;
subFilters . Add ( subTextSubtitlesFilter ) ;
}
2022-10-16 17:08:59 +02:00
2023-06-12 19:13:48 +02:00
subFilters . Add ( "hwupload=derive_device=vulkan" ) ;
subFilters . Add ( "format=vulkan" ) ;
2023-04-02 11:30:22 +02:00
2023-06-12 19:13:48 +02:00
overlayFilters . Add ( "overlay_vulkan=eof_action=endall:shortest=1:repeatlast=0" ) ;
2022-10-16 17:08:59 +02:00
2023-06-12 19:13:48 +02:00
if ( isSwEncoder )
{
// OUTPUT nv12 surface(memory)
overlayFilters . Add ( "scale_vulkan=format=nv12" ) ;
overlayFilters . Add ( "hwdownload" ) ;
overlayFilters . Add ( "format=nv12" ) ;
2022-10-16 17:08:59 +02:00
}
2023-06-12 19:13:48 +02:00
else if ( isVaapiEncoder )
2022-10-16 17:08:59 +02:00
{
2023-06-12 19:13:48 +02:00
// OUTPUT vaapi(nv12) surface(vram)
// map from vulkan/drm to vaapi via interop (Vega/gfx9+).
overlayFilters . Add ( "hwmap=derive_device=drm" ) ;
overlayFilters . Add ( "format=drm_prime" ) ;
overlayFilters . Add ( "hwmap=derive_device=vaapi" ) ;
overlayFilters . Add ( "format=vaapi" ) ;
2022-10-16 17:08:59 +02:00
2023-06-12 19:13:48 +02:00
// clear the surf->meta_offset and output nv12
overlayFilters . Add ( "scale_vaapi=format=nv12" ) ;
// hw deint
if ( doDeintH2645 )
2021-12-01 17:49:50 +01:00
{
2023-06-12 19:13:48 +02:00
var deintFilter = GetHwDeinterlaceFilter ( state , options , "vaapi" ) ;
overlayFilters . Add ( deintFilter ) ;
2021-12-01 17:49:50 +01:00
}
}
}
2021-12-24 09:50:40 +01:00
return ( mainFilters , subFilters , overlayFilters ) ;
2021-12-01 17:49:50 +01:00
}
2021-12-24 22:18:24 +01:00
public ( List < string > MainFilters , List < string > SubFilters , List < string > OverlayFilters ) GetVaapiLimitedVidFiltersPrefered (
2021-12-01 17:49:50 +01:00
EncodingJobInfo state ,
EncodingOptions options ,
string vidDecoder ,
string vidEncoder )
{
var inW = state . VideoStream ? . Width ;
var inH = state . VideoStream ? . Height ;
var reqW = state . BaseRequest . Width ;
var reqH = state . BaseRequest . Height ;
var reqMaxW = state . BaseRequest . MaxWidth ;
var reqMaxH = state . BaseRequest . MaxHeight ;
var threeDFormat = state . MediaSource . Video3DFormat ;
var isVaapiDecoder = vidDecoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
var isVaapiEncoder = vidEncoder . Contains ( "vaapi" , StringComparison . OrdinalIgnoreCase ) ;
var isSwDecoder = string . IsNullOrEmpty ( vidDecoder ) ;
var isSwEncoder = ! isVaapiEncoder ;
var isVaInVaOut = isVaapiDecoder & & isVaapiEncoder ;
2021-12-24 09:50:40 +01:00
var isi965Driver = _mediaEncoder . IsVaapiDeviceInteli965 ;
var isAmdDriver = _mediaEncoder . IsVaapiDeviceAmd ;
2021-12-01 17:49:50 +01:00
var doDeintH264 = state . DeInterlace ( "h264" , true ) | | state . DeInterlace ( "avc" , true ) ;
var doDeintHevc = state . DeInterlace ( "h265" , true ) | | state . DeInterlace ( "hevc" , true ) ;
var doDeintH2645 = doDeintH264 | | doDeintHevc ;
var doOclTonemap = IsHwTonemapAvailable ( state , options ) ;
2022-12-05 15:01:13 +01:00
var hasSubs = state . SubtitleStream is not null & & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode ;
2021-12-01 17:49:50 +01:00
var hasTextSubs = hasSubs & & state . SubtitleStream . IsTextSubtitleStream ;
var hasGraphicalSubs = hasSubs & & ! state . SubtitleStream . IsTextSubtitleStream ;
/* Make main filters for video stream */
var mainFilters = new List < string > ( ) ;
mainFilters . Add ( GetOverwriteColorPropertiesParam ( state , doOclTonemap ) ) ;
var outFormat = string . Empty ;
if ( isSwDecoder )
{
// INPUT sw surface(memory)
// sw deint
if ( doDeintH2645 )
{
var swDeintFilter = GetSwDeinterlaceFilter ( state , options ) ;
mainFilters . Add ( swDeintFilter ) ;
}
2021-12-24 09:50:40 +01:00
outFormat = doOclTonemap ? "yuv420p10le" : "nv12" ;
var swScaleFilter = GetSwScaleFilter ( state , options , vidEncoder , inW , inH , threeDFormat , reqW , reqH , reqMaxW , reqMaxH ) ;
// sw scale
mainFilters . Add ( swScaleFilter ) ;
mainFilters . Add ( "format=" + outFormat ) ;
2021-12-01 17:49:50 +01:00
// keep video at memory except ocl tonemap,
// since the overhead caused by hwupload >>> using sw filter.
// sw => hw
if ( doOclTonemap )
{
2022-06-14 16:18:22 +02:00
mainFilters . Add ( "hwupload=derive_device=opencl" ) ;
2021-12-01 17:49:50 +01:00
}
}
else if ( isVaapiDecoder )
{
// INPUT vaapi surface(vram)
2021-12-24 09:50:40 +01:00
// hw deint
if ( doDeintH2645 )
{
var deintFilter = GetHwDeinterlaceFilter ( state , options , "vaapi" ) ;
mainFilters . Add ( deintFilter ) ;
}
2021-12-01 17:49:50 +01:00
outFormat = doOclTonemap ? string . Empty : "nv12" ;
var hwScaleFilter = GetHwScaleFilter ( "vaapi" , outFormat , inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
2023-03-10 01:33:52 +01:00
// allocate extra pool sizes for vaapi vpp
if ( ! string . IsNullOrEmpty ( hwScaleFilter ) )
{
hwScaleFilter + = ":extra_hw_frames=24" ;
}
2021-12-01 17:49:50 +01:00
// hw scale
mainFilters . Add ( hwScaleFilter ) ;
}
if ( doOclTonemap & & isVaapiDecoder )
{
if ( isi965Driver )
{
// map from vaapi to opencl via vaapi-opencl interop(Intel only).
mainFilters . Add ( "hwmap=derive_device=opencl" ) ;
}
else
{
mainFilters . Add ( "hwdownload" ) ;
mainFilters . Add ( "format=p010le" ) ;
2022-06-14 16:18:22 +02:00
mainFilters . Add ( "hwupload=derive_device=opencl" ) ;
2021-12-01 17:49:50 +01:00
}
}
// ocl tonemap
if ( doOclTonemap )
{
var tonemapFilter = GetHwTonemapFilter ( options , "opencl" , "nv12" ) ;
mainFilters . Add ( tonemapFilter ) ;
}
if ( doOclTonemap & & isVaInVaOut )
{
if ( isi965Driver )
{
// OUTPUT vaapi(nv12) surface(vram)
// reverse-mapping via vaapi-opencl interop.
mainFilters . Add ( "hwmap=derive_device=vaapi:reverse=1" ) ;
mainFilters . Add ( "format=vaapi" ) ;
}
}
var memoryOutput = false ;
var isUploadForOclTonemap = doOclTonemap & & ( isSwDecoder | | ( isVaapiDecoder & & ! isi965Driver ) ) ;
var isHwmapNotUsable = hasGraphicalSubs | | isUploadForOclTonemap ;
var isHwmapForSubs = hasSubs & & isVaapiDecoder ;
var isHwUnmapForTextSubs = hasTextSubs & & isVaInVaOut & & ! isUploadForOclTonemap ;
if ( ( isVaapiDecoder & & isSwEncoder ) | | isUploadForOclTonemap | | isHwmapForSubs )
{
memoryOutput = true ;
// OUTPUT nv12 surface(memory)
// prefer hwmap to hwdownload on opencl/vaapi.
mainFilters . Add ( isHwmapNotUsable ? "hwdownload" : "hwmap" ) ;
mainFilters . Add ( "format=nv12" ) ;
}
// OUTPUT nv12 surface(memory)
if ( isSwDecoder & & isVaapiEncoder )
{
memoryOutput = true ;
}
if ( memoryOutput )
{
// text subtitles
if ( hasTextSubs )
{
var textSubtitlesFilter = GetTextSubtitlesFilter ( state , false , false ) ;
mainFilters . Add ( textSubtitlesFilter ) ;
}
}
if ( isHwUnmapForTextSubs )
{
mainFilters . Add ( "hwmap" ) ;
mainFilters . Add ( "format=vaapi" ) ;
}
else if ( memoryOutput & & isVaapiEncoder )
{
if ( ! hasGraphicalSubs )
{
mainFilters . Add ( "hwupload_vaapi" ) ;
}
}
/* Make sub and overlay filters for subtitle stream */
var subFilters = new List < string > ( ) ;
var overlayFilters = new List < string > ( ) ;
if ( memoryOutput )
{
if ( hasGraphicalSubs )
{
2023-01-22 20:06:20 +01:00
var subSwScaleFilter = GetCustomSwScaleFilter ( inW , inH , reqW , reqH , reqMaxW , reqMaxH ) ;
2021-12-01 17:49:50 +01:00
subFilters . Add ( subSwScaleFilter ) ;
overlayFilters . Add ( "overlay=eof_action=pass:shortest=1:repeatlast=0" ) ;
if ( isVaapiEncoder )
{
overlayFilters . Add ( "hwupload_vaapi" ) ;
}
}
}
2021-12-24 09:50:40 +01:00
return ( mainFilters , subFilters , overlayFilters ) ;
2021-12-01 17:49:50 +01:00
}
2023-02-08 23:42:17 +01:00
/// <summary>
/// Gets the parameter of Apple VideoToolBox filter chain.
/// </summary>
/// <param name="state">Encoding state.</param>
/// <param name="options">Encoding options.</param>
/// <param name="vidEncoder">Video encoder to use.</param>
/// <returns>The tuple contains three lists: main, sub and overlay filters.</returns>
public ( List < string > MainFilters , List < string > SubFilters , List < string > OverlayFilters ) GetAppleVidFilterChain (
EncodingJobInfo state ,
EncodingOptions options ,
string vidEncoder )
{
if ( ! string . Equals ( options . HardwareAccelerationType , "videotoolbox" , StringComparison . OrdinalIgnoreCase ) )
{
return ( null , null , null ) ;
}
var swFilterChain = GetSwVidFilterChain ( state , options , vidEncoder ) ;
if ( ! options . EnableHardwareEncoding )
{
return swFilterChain ;
}
if ( _mediaEncoder . EncoderVersion . CompareTo ( new Version ( "5.0.0" ) ) < 0 )
{
// All features used here requires ffmpeg 5.0 or later, fallback to software filters if using an old ffmpeg
return swFilterChain ;
}
var doDeintH264 = state . DeInterlace ( "h264" , true ) | | state . DeInterlace ( "avc" , true ) ;
var doDeintHevc = state . DeInterlace ( "h265" , true ) | | state . DeInterlace ( "hevc" , true ) ;
var doDeintH2645 = doDeintH264 | | doDeintHevc ;
var inW = state . VideoStream ? . Width ;
var inH = state . VideoStream ? . Height ;
var reqW = state . BaseRequest . Width ;
var reqH = state . BaseRequest . Height ;
var reqMaxW = state . BaseRequest . MaxWidth ;
var reqMaxH = state . BaseRequest . MaxHeight ;
var threeDFormat = state . MediaSource . Video3DFormat ;
var newfilters = new List < string > ( ) ;
var noOverlay = swFilterChain . OverlayFilters . Count = = 0 ;
var supportsHwDeint = _mediaEncoder . SupportsFilter ( "yadif_videotoolbox" ) ;
// fallback to software filters if we are using filters not supported by hardware yet.
var useHardwareFilters = noOverlay & & ( ! doDeintH2645 | | supportsHwDeint ) ;
if ( ! useHardwareFilters )
{
return swFilterChain ;
}
// ffmpeg cannot use videotoolbox to scale
var swScaleFilter = GetSwScaleFilter ( state , options , vidEncoder , inW , inH , threeDFormat , reqW , reqH , reqMaxW , reqMaxH ) ;
newfilters . Add ( swScaleFilter ) ;
// hwupload on videotoolbox encoders can automatically convert AVFrame into its CVPixelBuffer equivalent
// videotoolbox will automatically convert the CVPixelBuffer to a pixel format the encoder supports, so we don't have to set a pixel format explicitly here
// This will reduce CPU usage significantly on UHD videos with 10 bit colors because we bypassed the ffmpeg pixel format conversion
newfilters . Add ( "hwupload" ) ;
if ( doDeintH2645 )
{
var deintFilter = GetHwDeinterlaceFilter ( state , options , "videotoolbox" ) ;
newfilters . Add ( deintFilter ) ;
}
return ( newfilters , swFilterChain . SubFilters , swFilterChain . OverlayFilters ) ;
}
2021-12-01 17:49:50 +01:00
/// <summary>
/// Gets the parameter of video processing filters.
/// </summary>
/// <param name="state">Encoding state.</param>
/// <param name="options">Encoding options.</param>
/// <param name="outputVideoCodec">Video codec to use.</param>
/// <returns>The video processing filters parameter.</returns>
public string GetVideoProcessingFilterParam (
EncodingJobInfo state ,
EncodingOptions options ,
string outputVideoCodec )
{
var videoStream = state . VideoStream ;
2022-12-05 15:00:20 +01:00
if ( videoStream is null )
2021-12-01 17:49:50 +01:00
{
return string . Empty ;
}
2022-12-05 15:01:13 +01:00
var hasSubs = state . SubtitleStream is not null & & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode ;
2021-12-01 17:49:50 +01:00
var hasTextSubs = hasSubs & & state . SubtitleStream . IsTextSubtitleStream ;
var hasGraphicalSubs = hasSubs & & ! state . SubtitleStream . IsTextSubtitleStream ;
2021-12-24 09:50:40 +01:00
List < string > mainFilters ;
List < string > subFilters ;
List < string > overlayFilters ;
2021-12-01 17:49:50 +01:00
if ( string . Equals ( options . HardwareAccelerationType , "vaapi" , StringComparison . OrdinalIgnoreCase ) )
{
2021-12-24 09:50:40 +01:00
( mainFilters , subFilters , overlayFilters ) = GetVaapiVidFilterChain ( state , options , outputVideoCodec ) ;
2021-12-01 17:49:50 +01:00
}
else if ( string . Equals ( options . HardwareAccelerationType , "qsv" , StringComparison . OrdinalIgnoreCase ) )
{
2021-12-24 09:50:40 +01:00
( mainFilters , subFilters , overlayFilters ) = GetIntelVidFilterChain ( state , options , outputVideoCodec ) ;
2021-12-01 17:49:50 +01:00
}
else if ( string . Equals ( options . HardwareAccelerationType , "nvenc" , StringComparison . OrdinalIgnoreCase ) )
{
2021-12-24 09:50:40 +01:00
( mainFilters , subFilters , overlayFilters ) = GetNvidiaVidFilterChain ( state , options , outputVideoCodec ) ;
2021-12-01 17:49:50 +01:00
}
else if ( string . Equals ( options . HardwareAccelerationType , "amf" , StringComparison . OrdinalIgnoreCase ) )
{
2021-12-24 09:50:40 +01:00
( mainFilters , subFilters , overlayFilters ) = GetAmdVidFilterChain ( state , options , outputVideoCodec ) ;
2021-12-01 17:49:50 +01:00
}
2023-02-08 23:42:17 +01:00
else if ( string . Equals ( options . HardwareAccelerationType , "videotoolbox" , StringComparison . OrdinalIgnoreCase ) )
{
( mainFilters , subFilters , overlayFilters ) = GetAppleVidFilterChain ( state , options , outputVideoCodec ) ;
}
2021-12-01 17:49:50 +01:00
else
{
2021-12-24 09:50:40 +01:00
( mainFilters , subFilters , overlayFilters ) = GetSwVidFilterChain ( state , options , outputVideoCodec ) ;
2021-12-01 17:49:50 +01:00
}
2021-12-24 09:50:40 +01:00
mainFilters ? . RemoveAll ( filter = > string . IsNullOrEmpty ( filter ) ) ;
subFilters ? . RemoveAll ( filter = > string . IsNullOrEmpty ( filter ) ) ;
overlayFilters ? . RemoveAll ( filter = > string . IsNullOrEmpty ( filter ) ) ;
2021-12-01 17:49:50 +01:00
var mainStr = string . Empty ;
2021-12-24 09:50:40 +01:00
if ( mainFilters ? . Count > 0 )
2021-12-01 17:49:50 +01:00
{
mainStr = string . Format (
CultureInfo . InvariantCulture ,
"{0}" ,
string . Join ( ',' , mainFilters ) ) ;
}
2021-12-24 09:50:40 +01:00
if ( overlayFilters ? . Count = = 0 )
2021-12-01 17:49:50 +01:00
{
// -vf "scale..."
return string . IsNullOrEmpty ( mainStr ) ? string . Empty : " -vf \"" + mainStr + "\"" ;
}
2021-12-24 09:50:40 +01:00
if ( overlayFilters ? . Count > 0
& & subFilters ? . Count > 0
2022-12-05 15:01:13 +01:00
& & state . SubtitleStream is not null )
2021-12-01 17:49:50 +01:00
{
// overlay graphical/text subtitles
var subStr = string . Format (
CultureInfo . InvariantCulture ,
"{0}" ,
string . Join ( ',' , subFilters ) ) ;
var overlayStr = string . Format (
CultureInfo . InvariantCulture ,
"{0}" ,
string . Join ( ',' , overlayFilters ) ) ;
2021-12-24 09:50:40 +01:00
var mapPrefix = Convert . ToInt32 ( state . SubtitleStream . IsExternal ) ;
2022-05-04 16:20:48 +02:00
var subtitleStreamIndex = FindIndex ( state . MediaSource . MediaStreams , state . SubtitleStream ) ;
var videoStreamIndex = FindIndex ( state . MediaSource . MediaStreams , state . VideoStream ) ;
2021-12-01 17:49:50 +01:00
if ( hasSubs )
{
// -filter_complex "[0:s]scale=s[sub]..."
var filterStr = string . IsNullOrEmpty ( mainStr )
? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]{5}\""
: " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[main];[main][sub]{5}\"" ;
if ( hasTextSubs )
{
filterStr = string . IsNullOrEmpty ( mainStr )
? " -filter_complex \"{4}[sub];[0:{2}][sub]{5}\""
: " -filter_complex \"{4}[sub];[0:{2}]{3}[main];[main][sub]{5}\"" ;
}
return string . Format (
CultureInfo . InvariantCulture ,
filterStr ,
mapPrefix ,
subtitleStreamIndex ,
2022-05-04 16:20:48 +02:00
videoStreamIndex ,
2021-12-01 17:49:50 +01:00
mainStr ,
subStr ,
overlayStr ) ;
}
}
return string . Empty ;
}
public string GetOverwriteColorPropertiesParam ( EncodingJobInfo state , bool isTonemapAvailable )
{
if ( isTonemapAvailable )
{
return GetInputHdrParam ( state . VideoStream ? . ColorTransfer ) ;
}
2021-12-24 09:50:40 +01:00
return GetOutputSdrParam ( null ) ;
2021-12-01 17:49:50 +01:00
}
public string GetInputHdrParam ( string colorTransfer )
{
if ( string . Equals ( colorTransfer , "arib-std-b67" , StringComparison . OrdinalIgnoreCase ) )
{
// HLG
return "setparams=color_primaries=bt2020:color_trc=arib-std-b67:colorspace=bt2020nc" ;
}
2021-12-24 09:50:40 +01:00
// HDR10
return "setparams=color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc" ;
2021-12-01 17:49:50 +01:00
}
public string GetOutputSdrParam ( string tonemappingRange )
{
// SDR
if ( string . Equals ( tonemappingRange , "tv" , StringComparison . OrdinalIgnoreCase ) )
{
return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709:range=tv" ;
}
if ( string . Equals ( tonemappingRange , "pc" , StringComparison . OrdinalIgnoreCase ) )
{
return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709:range=pc" ;
}
return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709" ;
}
public static int GetVideoColorBitDepth ( EncodingJobInfo state )
{
var videoStream = state . VideoStream ;
2022-12-05 15:01:13 +01:00
if ( videoStream is not null )
2021-12-01 17:49:50 +01:00
{
if ( videoStream . BitDepth . HasValue )
{
return videoStream . BitDepth . Value ;
}
2023-04-06 19:38:34 +02:00
if ( string . Equals ( videoStream . PixelFormat , "yuv420p" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoStream . PixelFormat , "yuvj420p" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoStream . PixelFormat , "yuv444p" , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
return 8 ;
}
2023-04-06 19:38:34 +02:00
if ( string . Equals ( videoStream . PixelFormat , "yuv420p10le" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoStream . PixelFormat , "yuv444p10le" , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
return 10 ;
}
2023-04-06 19:38:34 +02:00
if ( string . Equals ( videoStream . PixelFormat , "yuv420p12le" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoStream . PixelFormat , "yuv444p12le" , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
return 12 ;
}
2023-04-06 19:38:34 +02:00
return 8 ;
2021-12-01 17:49:50 +01:00
}
return 0 ;
}
/// <summary>
/// Gets the ffmpeg option string for the hardware accelerated video decoder.
/// </summary>
/// <param name="state">The encoding job info.</param>
/// <param name="options">The encoding options.</param>
/// <returns>The option string or null if none available.</returns>
protected string GetHardwareVideoDecoder ( EncodingJobInfo state , EncodingOptions options )
{
var videoStream = state . VideoStream ;
2022-06-23 15:32:35 +02:00
var mediaSource = state . MediaSource ;
2022-12-05 15:00:20 +01:00
if ( videoStream is null | | mediaSource is null )
2021-12-01 17:49:50 +01:00
{
return null ;
}
2022-06-23 15:32:35 +02:00
// HWA decoders can handle both video files and video folders.
2023-03-10 01:38:16 +01:00
var videoType = state . VideoType ;
2022-06-23 15:32:35 +02:00
if ( videoType ! = VideoType . VideoFile
& & videoType ! = VideoType . Iso
& & videoType ! = VideoType . Dvd
& & videoType ! = VideoType . BluRay )
2021-12-01 17:49:50 +01:00
{
return null ;
}
if ( IsCopyCodec ( state . OutputVideoCodec ) )
{
return null ;
}
if ( ! string . IsNullOrEmpty ( videoStream . Codec ) & & ! string . IsNullOrEmpty ( options . HardwareAccelerationType ) )
{
var bitDepth = GetVideoColorBitDepth ( state ) ;
// Only HEVC, VP9 and AV1 formats have 10-bit hardware decoder support now.
2021-12-24 09:50:40 +01:00
if ( bitDepth = = 10
& & ! ( string . Equals ( videoStream . Codec , "hevc" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoStream . Codec , "h265" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoStream . Codec , "vp9" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoStream . Codec , "av1" , StringComparison . OrdinalIgnoreCase ) ) )
2021-12-01 17:49:50 +01:00
{
return null ;
}
if ( string . Equals ( options . HardwareAccelerationType , "qsv" , StringComparison . OrdinalIgnoreCase ) )
{
return GetQsvHwVidDecoder ( state , options , videoStream , bitDepth ) ;
}
if ( string . Equals ( options . HardwareAccelerationType , "nvenc" , StringComparison . OrdinalIgnoreCase ) )
{
return GetNvdecVidDecoder ( state , options , videoStream , bitDepth ) ;
}
if ( string . Equals ( options . HardwareAccelerationType , "amf" , StringComparison . OrdinalIgnoreCase ) )
{
return GetAmfVidDecoder ( state , options , videoStream , bitDepth ) ;
}
if ( string . Equals ( options . HardwareAccelerationType , "vaapi" , StringComparison . OrdinalIgnoreCase ) )
{
return GetVaapiVidDecoder ( state , options , videoStream , bitDepth ) ;
}
if ( string . Equals ( options . HardwareAccelerationType , "videotoolbox" , StringComparison . OrdinalIgnoreCase ) )
{
return GetVideotoolboxVidDecoder ( state , options , videoStream , bitDepth ) ;
}
}
2021-12-24 09:50:40 +01:00
var whichCodec = videoStream . Codec ;
if ( string . Equals ( whichCodec , "avc" , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
2021-12-24 09:50:40 +01:00
whichCodec = "h264" ;
}
else if ( string . Equals ( whichCodec , "h265" , StringComparison . OrdinalIgnoreCase ) )
{
whichCodec = "hevc" ;
2021-12-01 17:49:50 +01:00
}
// Avoid a second attempt if no hardware acceleration is being used
2021-12-24 09:50:40 +01:00
options . HardwareDecodingCodecs = Array . FindAll ( options . HardwareDecodingCodecs , val = > ! string . Equals ( val , whichCodec , StringComparison . OrdinalIgnoreCase ) ) ;
2021-12-01 17:49:50 +01:00
// leave blank so ffmpeg will decide
return null ;
}
/// <summary>
/// Gets a hw decoder name.
/// </summary>
/// <param name="options">Encoding options.</param>
/// <param name="decoderPrefix">Decoder prefix.</param>
/// <param name="decoderSuffix">Decoder suffix.</param>
/// <param name="videoCodec">Video codec to use.</param>
/// <param name="bitDepth">Video color bit depth.</param>
/// <returns>Hardware decoder name.</returns>
public string GetHwDecoderName ( EncodingOptions options , string decoderPrefix , string decoderSuffix , string videoCodec , int bitDepth )
{
if ( string . IsNullOrEmpty ( decoderPrefix ) | | string . IsNullOrEmpty ( decoderSuffix ) )
{
return null ;
}
var decoderName = decoderPrefix + '_' + decoderSuffix ;
2022-01-08 15:31:45 +01:00
var isCodecAvailable = _mediaEncoder . SupportsDecoder ( decoderName ) & & options . HardwareDecodingCodecs . Contains ( videoCodec , StringComparison . OrdinalIgnoreCase ) ;
2021-12-01 17:49:50 +01:00
if ( bitDepth = = 10 & & isCodecAvailable )
{
2022-01-08 15:31:45 +01:00
if ( string . Equals ( videoCodec , "hevc" , StringComparison . OrdinalIgnoreCase )
& & options . HardwareDecodingCodecs . Contains ( "hevc" , StringComparison . OrdinalIgnoreCase )
& & ! options . EnableDecodingColorDepth10Hevc )
{
return null ;
}
if ( string . Equals ( videoCodec , "vp9" , StringComparison . OrdinalIgnoreCase )
& & options . HardwareDecodingCodecs . Contains ( "vp9" , StringComparison . OrdinalIgnoreCase )
& & ! options . EnableDecodingColorDepth10Vp9 )
2021-12-01 17:49:50 +01:00
{
return null ;
}
}
if ( string . Equals ( decoderSuffix , "cuvid" , StringComparison . OrdinalIgnoreCase ) & & options . EnableEnhancedNvdecDecoder )
{
return null ;
}
if ( string . Equals ( decoderSuffix , "qsv" , StringComparison . OrdinalIgnoreCase ) & & options . PreferSystemNativeHwDecoder )
{
return null ;
}
return isCodecAvailable ? ( " -c:v " + decoderName ) : null ;
}
/// <summary>
/// Gets a hwaccel type to use as a hardware decoder depending on the system.
/// </summary>
/// <param name="state">Encoding state.</param>
/// <param name="options">Encoding options.</param>
/// <param name="videoCodec">Video codec to use.</param>
/// <param name="bitDepth">Video color bit depth.</param>
/// <param name="outputHwSurface">Specifies if output hw surface.</param>
/// <returns>Hardware accelerator type.</returns>
public string GetHwaccelType ( EncodingJobInfo state , EncodingOptions options , string videoCodec , int bitDepth , bool outputHwSurface )
{
var isWindows = OperatingSystem . IsWindows ( ) ;
var isLinux = OperatingSystem . IsLinux ( ) ;
var isMacOS = OperatingSystem . IsMacOS ( ) ;
var isD3d11Supported = isWindows & & _mediaEncoder . SupportsHwaccel ( "d3d11va" ) ;
var isVaapiSupported = isLinux & & IsVaapiSupported ( state ) ;
var isCudaSupported = ( isLinux | | isWindows ) & & IsCudaFullSupported ( ) ;
var isQsvSupported = ( isLinux | | isWindows ) & & _mediaEncoder . SupportsHwaccel ( "qsv" ) ;
var isVideotoolboxSupported = isMacOS & & _mediaEncoder . SupportsHwaccel ( "videotoolbox" ) ;
2022-01-08 15:31:45 +01:00
var isCodecAvailable = options . HardwareDecodingCodecs . Contains ( videoCodec , StringComparison . OrdinalIgnoreCase ) ;
2021-12-01 17:49:50 +01:00
2023-03-10 01:38:15 +01:00
var ffmpegVersion = _mediaEncoder . EncoderVersion ;
2021-12-24 09:50:40 +01:00
// Set the av1 codec explicitly to trigger hw accelerator, otherwise libdav1d will be used.
2023-03-10 01:38:15 +01:00
var isAv1 = ffmpegVersion < _minFFmpegImplictHwaccel
& & string . Equals ( videoCodec , "av1" , StringComparison . OrdinalIgnoreCase ) ;
2021-12-24 09:50:40 +01:00
2023-03-10 01:35:54 +01:00
// Allow profile mismatch if decoding H.264 baseline with d3d11va and vaapi hwaccels.
var profileMismatch = string . Equals ( videoCodec , "h264" , StringComparison . OrdinalIgnoreCase )
& & string . Equals ( state . VideoStream ? . Profile , "baseline" , StringComparison . OrdinalIgnoreCase ) ;
2023-03-10 01:38:15 +01:00
// Disable the extra internal copy in nvdec. We already handle it in filter chain.
var nvdecNoInternalCopy = ffmpegVersion > = _minFFmpegHwaUnsafeOutput ;
2021-12-01 17:49:50 +01:00
if ( bitDepth = = 10 & & isCodecAvailable )
{
2022-01-08 15:31:45 +01:00
if ( string . Equals ( videoCodec , "hevc" , StringComparison . OrdinalIgnoreCase )
& & options . HardwareDecodingCodecs . Contains ( "hevc" , StringComparison . OrdinalIgnoreCase )
& & ! options . EnableDecodingColorDepth10Hevc )
{
return null ;
}
if ( string . Equals ( videoCodec , "vp9" , StringComparison . OrdinalIgnoreCase )
& & options . HardwareDecodingCodecs . Contains ( "vp9" , StringComparison . OrdinalIgnoreCase )
& & ! options . EnableDecodingColorDepth10Vp9 )
2021-12-01 17:49:50 +01:00
{
return null ;
}
}
// Intel qsv/d3d11va/vaapi
if ( string . Equals ( options . HardwareAccelerationType , "qsv" , StringComparison . OrdinalIgnoreCase ) )
{
if ( options . PreferSystemNativeHwDecoder )
{
if ( isVaapiSupported & & isCodecAvailable )
{
2023-03-10 01:35:54 +01:00
return " -hwaccel vaapi" + ( outputHwSurface ? " -hwaccel_output_format vaapi" : string . Empty )
+ ( profileMismatch ? " -hwaccel_flags +allow_profile_mismatch" : string . Empty ) + ( isAv1 ? " -c:v av1" : string . Empty ) ;
2021-12-01 17:49:50 +01:00
}
if ( isD3d11Supported & & isCodecAvailable )
{
2022-08-01 20:25:41 +02:00
// set -threads 3 to intel d3d11va decoder explicitly. Lower threads may result in dead lock.
// on newer devices such as Xe, the larger the init_pool_size, the longer the initialization time for opencl to derive from d3d11.
2023-03-10 01:35:54 +01:00
return " -hwaccel d3d11va" + ( outputHwSurface ? " -hwaccel_output_format d3d11" : string . Empty )
+ ( profileMismatch ? " -hwaccel_flags +allow_profile_mismatch" : string . Empty ) + " -threads 3" + ( isAv1 ? " -c:v av1" : string . Empty ) ;
2021-12-01 17:49:50 +01:00
}
}
else
{
if ( isQsvSupported & & isCodecAvailable )
{
return " -hwaccel qsv" + ( outputHwSurface ? " -hwaccel_output_format qsv" : string . Empty ) ;
}
}
}
// Nvidia cuda
if ( string . Equals ( options . HardwareAccelerationType , "nvenc" , StringComparison . OrdinalIgnoreCase ) )
{
2022-03-08 16:36:30 +01:00
if ( isCudaSupported & & isCodecAvailable )
2021-12-01 17:49:50 +01:00
{
2022-03-08 16:36:30 +01:00
if ( options . EnableEnhancedNvdecDecoder )
{
// set -threads 1 to nvdec decoder explicitly since it doesn't implement threading support.
2023-03-10 01:38:15 +01:00
return " -hwaccel cuda" + ( outputHwSurface ? " -hwaccel_output_format cuda" : string . Empty )
+ ( nvdecNoInternalCopy ? " -hwaccel_flags +unsafe_output" : string . Empty ) + " -threads 1" + ( isAv1 ? " -c:v av1" : string . Empty ) ;
2022-03-08 16:36:30 +01:00
}
2023-04-06 19:38:34 +02:00
// cuvid decoder doesn't have threading issue.
return " -hwaccel cuda" + ( outputHwSurface ? " -hwaccel_output_format cuda" : string . Empty ) ;
2021-12-01 17:49:50 +01:00
}
}
// Amd d3d11va
if ( string . Equals ( options . HardwareAccelerationType , "amf" , StringComparison . OrdinalIgnoreCase ) )
{
if ( isD3d11Supported & & isCodecAvailable )
{
2023-03-10 01:35:54 +01:00
return " -hwaccel d3d11va" + ( outputHwSurface ? " -hwaccel_output_format d3d11" : string . Empty )
+ ( profileMismatch ? " -hwaccel_flags +allow_profile_mismatch" : string . Empty ) + ( isAv1 ? " -c:v av1" : string . Empty ) ;
2021-12-01 17:49:50 +01:00
}
}
// Vaapi
2021-12-24 09:50:40 +01:00
if ( string . Equals ( options . HardwareAccelerationType , "vaapi" , StringComparison . OrdinalIgnoreCase )
& & isVaapiSupported
& & isCodecAvailable )
2021-12-01 17:49:50 +01:00
{
2023-03-10 01:35:54 +01:00
return " -hwaccel vaapi" + ( outputHwSurface ? " -hwaccel_output_format vaapi" : string . Empty )
+ ( profileMismatch ? " -hwaccel_flags +allow_profile_mismatch" : string . Empty ) + ( isAv1 ? " -c:v av1" : string . Empty ) ;
2021-12-01 17:49:50 +01:00
}
2023-03-10 01:35:54 +01:00
// Apple videotoolbox
2021-12-24 09:50:40 +01:00
if ( string . Equals ( options . HardwareAccelerationType , "videotoolbox" , StringComparison . OrdinalIgnoreCase )
& & isVideotoolboxSupported
& & isCodecAvailable )
2021-12-01 17:49:50 +01:00
{
2021-12-24 09:50:40 +01:00
return " -hwaccel videotoolbox" + ( outputHwSurface ? " -hwaccel_output_format videotoolbox_vld" : string . Empty ) ;
2021-12-01 17:49:50 +01:00
}
return null ;
}
public string GetQsvHwVidDecoder ( EncodingJobInfo state , EncodingOptions options , MediaStream videoStream , int bitDepth )
{
var isWindows = OperatingSystem . IsWindows ( ) ;
var isLinux = OperatingSystem . IsLinux ( ) ;
2021-12-24 09:50:40 +01:00
if ( ( ! isWindows & & ! isLinux )
| | ! string . Equals ( options . HardwareAccelerationType , "qsv" , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
return null ;
}
var isQsvOclSupported = _mediaEncoder . SupportsHwaccel ( "qsv" ) & & IsOpenclFullSupported ( ) ;
var isIntelDx11OclSupported = isWindows
& & _mediaEncoder . SupportsHwaccel ( "d3d11va" )
& & isQsvOclSupported ;
var isIntelVaapiOclSupported = isLinux
& & IsVaapiSupported ( state )
& & isQsvOclSupported ;
var hwSurface = ( isIntelDx11OclSupported | | isIntelVaapiOclSupported )
& & _mediaEncoder . SupportsFilter ( "alphasrc" ) ;
2022-06-24 14:49:27 +02:00
var is8bitSwFormatsQsv = string . Equals ( "yuv420p" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( "yuvj420p" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase ) ;
2021-12-24 09:50:40 +01:00
var is8_10bitSwFormatsQsv = is8bitSwFormatsQsv | | string . Equals ( "yuv420p10le" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase ) ;
// TODO: add more 8/10bit and 4:4:4 formats for Qsv after finishing the ffcheck tool
2021-12-01 17:49:50 +01:00
2021-12-24 09:50:40 +01:00
if ( is8bitSwFormatsQsv )
2021-12-01 17:49:50 +01:00
{
2021-12-24 09:50:40 +01:00
if ( string . Equals ( videoStream . Codec , "avc" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoStream . Codec , "h264" , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "h264" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "h264" , "qsv" , "h264" , bitDepth ) ;
}
if ( string . Equals ( videoStream . Codec , "vc1" , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "vc1" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "vc1" , "qsv" , "vc1" , bitDepth ) ;
}
if ( string . Equals ( videoStream . Codec , "vp8" , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "vp8" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "vp8" , "qsv" , "vp8" , bitDepth ) ;
}
if ( string . Equals ( videoStream . Codec , "mpeg2video" , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "mpeg2video" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "mpeg2" , "qsv" , "mpeg2video" , bitDepth ) ;
}
}
if ( is8_10bitSwFormatsQsv )
{
if ( string . Equals ( videoStream . Codec , "hevc" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( videoStream . Codec , "h265" , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "hevc" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "hevc" , "qsv" , "hevc" , bitDepth ) ;
}
if ( string . Equals ( videoStream . Codec , "vp9" , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "vp9" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "vp9" , "qsv" , "vp9" , bitDepth ) ;
}
if ( string . Equals ( videoStream . Codec , "av1" , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "av1" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "av1" , "qsv" , "av1" , bitDepth ) ;
2021-12-01 17:49:50 +01:00
}
}
return null ;
}
public string GetNvdecVidDecoder ( EncodingJobInfo state , EncodingOptions options , MediaStream videoStream , int bitDepth )
{
2021-12-24 09:50:40 +01:00
if ( ( ! OperatingSystem . IsWindows ( ) & & ! OperatingSystem . IsLinux ( ) )
| | ! string . Equals ( options . HardwareAccelerationType , "nvenc" , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
return null ;
}
2021-01-29 10:53:42 +01:00
2022-03-08 16:36:30 +01:00
var hwSurface = IsCudaFullSupported ( ) & & _mediaEncoder . SupportsFilter ( "alphasrc" ) ;
2022-06-24 14:49:27 +02:00
var is8bitSwFormatsNvdec = string . Equals ( "yuv420p" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( "yuvj420p" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase ) ;
2021-12-24 09:50:40 +01:00
var is8_10bitSwFormatsNvdec = is8bitSwFormatsNvdec | | string . Equals ( "yuv420p10le" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase ) ;
// TODO: add more 8/10/12bit and 4:4:4 formats for Nvdec after finishing the ffcheck tool
2021-12-01 17:49:50 +01:00
2021-12-24 09:50:40 +01:00
if ( is8bitSwFormatsNvdec )
2021-12-01 17:49:50 +01:00
{
2021-12-24 09:50:40 +01:00
if ( string . Equals ( "avc" , videoStream . Codec , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( "h264" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "h264" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "h264" , "cuvid" , "h264" , bitDepth ) ;
}
if ( string . Equals ( "mpeg2video" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "mpeg2video" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "mpeg2" , "cuvid" , "mpeg2video" , bitDepth ) ;
}
if ( string . Equals ( "vc1" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "vc1" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "vc1" , "cuvid" , "vc1" , bitDepth ) ;
}
if ( string . Equals ( "mpeg4" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "mpeg4" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "mpeg4" , "cuvid" , "mpeg4" , bitDepth ) ;
}
if ( string . Equals ( "vp8" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "vp8" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "vp8" , "cuvid" , "vp8" , bitDepth ) ;
}
}
if ( is8_10bitSwFormatsNvdec )
{
if ( string . Equals ( "hevc" , videoStream . Codec , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( "h265" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "hevc" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "hevc" , "cuvid" , "hevc" , bitDepth ) ;
}
if ( string . Equals ( "vp9" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "vp9" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "vp9" , "cuvid" , "vp9" , bitDepth ) ;
}
if ( string . Equals ( "av1" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "av1" , bitDepth , hwSurface ) + GetHwDecoderName ( options , "av1" , "cuvid" , "av1" , bitDepth ) ;
2021-01-24 20:40:34 +01:00
}
}
2021-12-01 17:49:50 +01:00
return null ;
}
public string GetAmfVidDecoder ( EncodingJobInfo state , EncodingOptions options , MediaStream videoStream , int bitDepth )
{
2021-12-24 09:50:40 +01:00
if ( ! OperatingSystem . IsWindows ( )
| | ! string . Equals ( options . HardwareAccelerationType , "amf" , StringComparison . OrdinalIgnoreCase ) )
2021-01-29 10:53:42 +01:00
{
2021-12-01 17:49:50 +01:00
return null ;
2021-01-29 10:53:42 +01:00
}
2021-12-01 17:49:50 +01:00
var hwSurface = _mediaEncoder . SupportsHwaccel ( "d3d11va" )
& & IsOpenclFullSupported ( )
& & _mediaEncoder . SupportsFilter ( "alphasrc" ) ;
2022-06-24 14:49:27 +02:00
var is8bitSwFormatsAmf = string . Equals ( "yuv420p" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( "yuvj420p" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase ) ;
2021-12-24 09:50:40 +01:00
var is8_10bitSwFormatsAmf = is8bitSwFormatsAmf | | string . Equals ( "yuv420p10le" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase ) ;
2021-12-01 17:49:50 +01:00
2021-12-24 09:50:40 +01:00
if ( is8bitSwFormatsAmf )
2021-01-24 20:40:34 +01:00
{
2021-12-24 09:50:40 +01:00
if ( string . Equals ( "avc" , videoStream . Codec , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( "h264" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "h264" , bitDepth , hwSurface ) ;
}
if ( string . Equals ( "mpeg2video" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "mpeg2video" , bitDepth , hwSurface ) ;
}
if ( string . Equals ( "vc1" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "vc1" , bitDepth , hwSurface ) ;
}
}
if ( is8_10bitSwFormatsAmf )
{
if ( string . Equals ( "hevc" , videoStream . Codec , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( "h265" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "hevc" , bitDepth , hwSurface ) ;
}
if ( string . Equals ( "vp9" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "vp9" , bitDepth , hwSurface ) ;
}
if ( string . Equals ( "av1" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "av1" , bitDepth , hwSurface ) ;
2021-12-01 17:49:50 +01:00
}
2018-12-28 00:27:57 +01:00
}
2021-12-01 17:49:50 +01:00
return null ;
}
public string GetVaapiVidDecoder ( EncodingJobInfo state , EncodingOptions options , MediaStream videoStream , int bitDepth )
{
2021-12-24 09:50:40 +01:00
if ( ! OperatingSystem . IsLinux ( )
| | ! string . Equals ( options . HardwareAccelerationType , "vaapi" , StringComparison . OrdinalIgnoreCase ) )
2021-07-24 18:52:16 +02:00
{
2021-12-01 17:49:50 +01:00
return null ;
2021-07-24 18:52:16 +02:00
}
2021-12-01 17:49:50 +01:00
var hwSurface = IsVaapiSupported ( state )
& & IsVaapiFullSupported ( )
& & IsOpenclFullSupported ( )
& & _mediaEncoder . SupportsFilter ( "alphasrc" ) ;
2022-06-24 14:49:27 +02:00
var is8bitSwFormatsVaapi = string . Equals ( "yuv420p" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( "yuvj420p" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase ) ;
2021-12-24 09:50:40 +01:00
var is8_10bitSwFormatsVaapi = is8bitSwFormatsVaapi | | string . Equals ( "yuv420p10le" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase ) ;
2021-12-01 17:49:50 +01:00
2021-12-24 09:50:40 +01:00
if ( is8bitSwFormatsVaapi )
{
if ( string . Equals ( "avc" , videoStream . Codec , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( "h264" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "h264" , bitDepth , hwSurface ) ;
}
if ( string . Equals ( "mpeg2video" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "mpeg2video" , bitDepth , hwSurface ) ;
}
if ( string . Equals ( "vc1" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "vc1" , bitDepth , hwSurface ) ;
}
if ( string . Equals ( "vp8" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "vp8" , bitDepth , hwSurface ) ;
}
}
if ( is8_10bitSwFormatsVaapi )
2018-12-28 00:27:57 +01:00
{
2021-12-24 09:50:40 +01:00
if ( string . Equals ( "hevc" , videoStream . Codec , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( "h265" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "hevc" , bitDepth , hwSurface ) ;
}
if ( string . Equals ( "vp9" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "vp9" , bitDepth , hwSurface ) ;
}
if ( string . Equals ( "av1" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "av1" , bitDepth , hwSurface ) ;
2021-12-01 17:49:50 +01:00
}
2018-12-28 00:27:57 +01:00
}
2021-12-01 17:49:50 +01:00
return null ;
2018-12-28 00:27:57 +01:00
}
2021-12-01 17:49:50 +01:00
public string GetVideotoolboxVidDecoder ( EncodingJobInfo state , EncodingOptions options , MediaStream videoStream , int bitDepth )
2021-07-24 18:52:16 +02:00
{
2021-12-24 09:50:40 +01:00
if ( ! OperatingSystem . IsMacOS ( )
| | ! string . Equals ( options . HardwareAccelerationType , "videotoolbox" , StringComparison . OrdinalIgnoreCase ) )
2021-07-24 18:52:16 +02:00
{
2021-12-01 17:49:50 +01:00
return null ;
2021-07-24 18:52:16 +02:00
}
2021-12-01 17:49:50 +01:00
2022-06-24 14:49:27 +02:00
var is8bitSwFormatsVt = string . Equals ( "yuv420p" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( "yuvj420p" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase ) ;
2021-12-24 09:50:40 +01:00
var is8_10bitSwFormatsVt = is8bitSwFormatsVt | | string . Equals ( "yuv420p10le" , videoStream . PixelFormat , StringComparison . OrdinalIgnoreCase ) ;
2021-12-01 17:49:50 +01:00
2021-12-24 09:50:40 +01:00
if ( is8bitSwFormatsVt )
2021-07-24 18:52:16 +02:00
{
2021-12-24 09:50:40 +01:00
if ( string . Equals ( "avc" , videoStream . Codec , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( "h264" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "h264" , bitDepth , false ) ;
}
if ( string . Equals ( "mpeg2video" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "mpeg2video" , bitDepth , false ) ;
}
if ( string . Equals ( "mpeg4" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
2021-12-01 17:49:50 +01:00
{
2021-12-24 09:50:40 +01:00
return GetHwaccelType ( state , options , "mpeg4" , bitDepth , false ) ;
}
}
if ( is8_10bitSwFormatsVt )
{
if ( string . Equals ( "hevc" , videoStream . Codec , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( "h265" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "hevc" , bitDepth , false ) ;
}
if ( string . Equals ( "vp9" , videoStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
return GetHwaccelType ( state , options , "vp9" , bitDepth , false ) ;
2021-12-01 17:49:50 +01:00
}
2021-07-24 18:52:16 +02:00
}
2021-12-01 17:49:50 +01:00
return null ;
2021-07-24 18:52:16 +02:00
}
2018-12-28 00:27:57 +01:00
/// <summary>
/// Gets the number of threads.
/// </summary>
2021-08-10 23:29:48 +02:00
/// <param name="state">Encoding state.</param>
/// <param name="encodingOptions">Encoding options.</param>
/// <param name="outputVideoCodec">Video codec to use.</param>
/// <returns>Number of threads.</returns>
2020-11-18 10:54:21 +01:00
#nullable enable
public static int GetNumberOfThreads ( EncodingJobInfo ? state , EncodingOptions encodingOptions , string? outputVideoCodec )
2018-12-28 00:27:57 +01:00
{
2021-08-20 20:22:21 +02:00
// VP8 and VP9 encoders must have their thread counts set.
bool mustSetThreadCount = string . Equals ( outputVideoCodec , "libvpx" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( outputVideoCodec , "libvpx-vp9" , StringComparison . OrdinalIgnoreCase ) ;
2018-12-28 00:27:57 +01:00
2020-11-18 10:01:03 +01:00
var threads = state ? . BaseRequest . CpuCoreLimit ? ? encodingOptions . EncodingThreadCount ;
2018-12-28 00:27:57 +01:00
2020-11-18 10:01:03 +01:00
if ( threads < = 0 )
2018-12-28 00:27:57 +01:00
{
2021-08-20 20:22:21 +02:00
// Automatically set thread count
return mustSetThreadCount ? Math . Max ( Environment . ProcessorCount - 1 , 1 ) : 0 ;
2021-02-13 00:39:18 +01:00
}
2023-04-06 19:38:34 +02:00
if ( threads > = Environment . ProcessorCount )
2018-12-28 00:27:57 +01:00
{
2020-11-17 14:26:05 +01:00
return Environment . ProcessorCount ;
2018-12-28 00:27:57 +01:00
}
return threads ;
}
2021-05-13 15:32:02 +02:00
2020-11-18 10:54:21 +01:00
#nullable disable
2018-12-28 00:27:57 +01:00
public void TryStreamCopy ( EncodingJobInfo state )
{
2022-12-05 15:01:13 +01:00
if ( state . VideoStream is not null & & CanStreamCopyVideo ( state , state . VideoStream ) )
2018-12-28 00:27:57 +01:00
{
state . OutputVideoCodec = "copy" ;
}
else
{
var user = state . User ;
// If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
2022-12-05 15:01:13 +01:00
if ( user is not null & & ! user . HasPermission ( PermissionKind . EnableVideoPlaybackTranscoding ) )
2018-12-28 00:27:57 +01:00
{
state . OutputVideoCodec = "copy" ;
}
}
2022-12-05 15:01:13 +01:00
if ( state . AudioStream is not null
2019-09-01 18:39:23 +02:00
& & CanStreamCopyAudio ( state , state . AudioStream , state . SupportedAudioCodecs ) )
2018-12-28 00:27:57 +01:00
{
state . OutputAudioCodec = "copy" ;
}
else
{
var user = state . User ;
// If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
2022-12-05 15:01:13 +01:00
if ( user is not null & & ! user . HasPermission ( PermissionKind . EnableAudioPlaybackTranscoding ) )
2018-12-28 00:27:57 +01:00
{
state . OutputAudioCodec = "copy" ;
}
}
}
2022-03-09 14:28:58 +01:00
public string GetInputModifier ( EncodingJobInfo state , EncodingOptions encodingOptions , string segmentContainer )
2018-12-28 00:27:57 +01:00
{
var inputModifier = string . Empty ;
2022-06-06 17:29:39 +02:00
var analyzeDurationArgument = string . Empty ;
2018-12-28 00:27:57 +01:00
2022-06-06 17:29:39 +02:00
// Apply -analyzeduration as per the environment variable,
// otherwise ffmpeg will break on certain files due to default value is 0.
// The default value of -probesize is more than enough, so leave it as is.
var ffmpegAnalyzeDuration = _config . GetFFmpegAnalyzeDuration ( ) ? ? string . Empty ;
2022-09-24 05:09:36 +02:00
if ( state . MediaSource . AnalyzeDurationMs > 0 )
2018-12-28 00:27:57 +01:00
{
2022-09-24 05:09:36 +02:00
analyzeDurationArgument = "-analyzeduration " + ( state . MediaSource . AnalyzeDurationMs . Value * 1000 ) . ToString ( CultureInfo . InvariantCulture ) ;
2018-12-28 00:27:57 +01:00
}
2022-09-24 05:09:36 +02:00
else if ( ! string . IsNullOrEmpty ( ffmpegAnalyzeDuration ) )
2018-12-28 00:27:57 +01:00
{
2022-09-24 05:09:36 +02:00
analyzeDurationArgument = "-analyzeduration " + ffmpegAnalyzeDuration ;
2018-12-28 00:27:57 +01:00
}
if ( ! string . IsNullOrEmpty ( analyzeDurationArgument ) )
{
inputModifier + = " " + analyzeDurationArgument ;
}
inputModifier = inputModifier . Trim ( ) ;
var userAgentParam = GetUserAgentParam ( state ) ;
if ( ! string . IsNullOrEmpty ( userAgentParam ) )
{
inputModifier + = " " + userAgentParam ;
}
inputModifier = inputModifier . Trim ( ) ;
2022-07-19 08:30:27 +02:00
var refererParam = GetRefererParam ( state ) ;
if ( ! string . IsNullOrEmpty ( refererParam ) )
{
inputModifier + = " " + refererParam ;
}
inputModifier = inputModifier . Trim ( ) ;
2022-03-09 14:28:58 +01:00
inputModifier + = " " + GetFastSeekCommandLineParameter ( state , encodingOptions , segmentContainer ) ;
2018-12-28 00:27:57 +01:00
inputModifier = inputModifier . Trim ( ) ;
if ( state . InputProtocol = = MediaProtocol . Rtsp )
{
2022-07-24 18:35:46 +02:00
inputModifier + = " -rtsp_transport tcp+udp -rtsp_flags prefer_tcp" ;
2018-12-28 00:27:57 +01:00
}
if ( ! string . IsNullOrEmpty ( state . InputAudioSync ) )
{
inputModifier + = " -async " + state . InputAudioSync ;
}
if ( ! string . IsNullOrEmpty ( state . InputVideoSync ) )
{
inputModifier + = " -vsync " + state . InputVideoSync ;
}
if ( state . ReadInputAtNativeFramerate & & state . InputProtocol ! = MediaProtocol . Rtsp )
{
inputModifier + = " -re" ;
}
var flags = new List < string > ( ) ;
if ( state . IgnoreInputDts )
{
flags . Add ( "+igndts" ) ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( state . IgnoreInputIndex )
{
flags . Add ( "+ignidx" ) ;
}
2019-09-01 18:39:23 +02:00
2020-07-15 06:58:36 +02:00
if ( state . GenPtsInput | | IsCopyCodec ( state . OutputVideoCodec ) )
2018-12-28 00:27:57 +01:00
{
flags . Add ( "+genpts" ) ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( state . DiscardCorruptFramesInput )
{
flags . Add ( "+discardcorrupt" ) ;
}
2019-09-01 18:39:23 +02:00
2018-12-28 00:27:57 +01:00
if ( state . EnableFastSeekInput )
{
flags . Add ( "+fastseek" ) ;
}
if ( flags . Count > 0 )
{
2019-09-01 18:39:23 +02:00
inputModifier + = " -fflags " + string . Join ( string . Empty , flags ) ;
2018-12-28 00:27:57 +01:00
}
if ( state . IsVideoRequest )
{
if ( ! string . IsNullOrEmpty ( state . InputContainer ) & & state . VideoType = = VideoType . VideoFile & & string . IsNullOrEmpty ( encodingOptions . HardwareAccelerationType ) )
{
var inputFormat = GetInputFormat ( state . InputContainer ) ;
if ( ! string . IsNullOrEmpty ( inputFormat ) )
{
inputModifier + = " -f " + inputFormat ;
}
}
}
if ( state . MediaSource . RequiresLooping )
{
2019-01-13 02:06:59 +01:00
inputModifier + = " -stream_loop -1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2" ;
2018-12-28 00:27:57 +01:00
}
return inputModifier ;
}
2019-09-01 18:39:23 +02:00
public void AttachMediaSourceInfo (
EncodingJobInfo state ,
2020-11-12 04:02:56 +01:00
EncodingOptions encodingOptions ,
2019-09-01 18:39:23 +02:00
MediaSourceInfo mediaSource ,
string requestedUrl )
2018-12-28 00:27:57 +01:00
{
2022-10-06 20:21:23 +02:00
ArgumentNullException . ThrowIfNull ( state ) ;
2019-09-01 18:39:23 +02:00
2022-10-06 20:21:23 +02:00
ArgumentNullException . ThrowIfNull ( mediaSource ) ;
2018-12-28 00:27:57 +01:00
var path = mediaSource . Path ;
var protocol = mediaSource . Protocol ;
if ( ! string . IsNullOrEmpty ( mediaSource . EncoderPath ) & & mediaSource . EncoderProtocol . HasValue )
{
path = mediaSource . EncoderPath ;
protocol = mediaSource . EncoderProtocol . Value ;
}
state . MediaPath = path ;
state . InputProtocol = protocol ;
state . InputContainer = mediaSource . Container ;
state . RunTimeTicks = mediaSource . RunTimeTicks ;
state . RemoteHttpHeaders = mediaSource . RequiredHttpHeaders ;
state . IsoType = mediaSource . IsoType ;
if ( mediaSource . Timestamp . HasValue )
{
state . InputTimestamp = mediaSource . Timestamp . Value ;
}
state . RunTimeTicks = mediaSource . RunTimeTicks ;
state . RemoteHttpHeaders = mediaSource . RequiredHttpHeaders ;
state . ReadInputAtNativeFramerate = mediaSource . ReadAtNativeFramerate ;
2019-09-01 18:39:23 +02:00
if ( state . ReadInputAtNativeFramerate
2021-06-06 17:16:41 +02:00
| | ( mediaSource . Protocol = = MediaProtocol . File
& & string . Equals ( mediaSource . Container , "wtv" , StringComparison . OrdinalIgnoreCase ) ) )
2018-12-28 00:27:57 +01:00
{
state . InputVideoSync = "-1" ;
state . InputAudioSync = "1" ;
}
2019-09-01 18:39:23 +02:00
if ( string . Equals ( mediaSource . Container , "wma" , StringComparison . OrdinalIgnoreCase )
| | string . Equals ( mediaSource . Container , "asf" , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
// Seeing some stuttering when transcoding wma to audio-only HLS
state . InputAudioSync = "1" ;
}
var mediaStreams = mediaSource . MediaStreams ;
if ( state . IsVideoRequest )
{
var videoRequest = state . BaseRequest ;
if ( string . IsNullOrEmpty ( videoRequest . VideoCodec ) )
{
if ( string . IsNullOrEmpty ( requestedUrl ) )
{
2019-01-13 02:06:59 +01:00
requestedUrl = "test." + videoRequest . Container ;
2018-12-28 00:27:57 +01:00
}
videoRequest . VideoCodec = InferVideoCodec ( requestedUrl ) ;
}
state . VideoStream = GetMediaStream ( mediaStreams , videoRequest . VideoStreamIndex , MediaStreamType . Video ) ;
state . SubtitleStream = GetMediaStream ( mediaStreams , videoRequest . SubtitleStreamIndex , MediaStreamType . Subtitle , false ) ;
state . SubtitleDeliveryMethod = videoRequest . SubtitleMethod ;
state . AudioStream = GetMediaStream ( mediaStreams , videoRequest . AudioStreamIndex , MediaStreamType . Audio ) ;
2022-12-05 15:01:13 +01:00
if ( state . SubtitleStream is not null & & ! state . SubtitleStream . IsExternal )
2018-12-28 00:27:57 +01:00
{
state . InternalSubtitleStreamOffset = mediaStreams . Where ( i = > i . Type = = MediaStreamType . Subtitle & & ! i . IsExternal ) . ToList ( ) . IndexOf ( state . SubtitleStream ) ;
}
EnforceResolutionLimit ( state ) ;
NormalizeSubtitleEmbed ( state ) ;
}
else
{
state . AudioStream = GetMediaStream ( mediaStreams , null , MediaStreamType . Audio , true ) ;
}
state . MediaSource = mediaSource ;
2019-01-13 02:06:59 +01:00
var request = state . BaseRequest ;
2020-10-31 17:33:38 +01:00
var supportedAudioCodecs = state . SupportedAudioCodecs ;
2022-12-05 15:01:13 +01:00
if ( request is not null & & supportedAudioCodecs is not null & & supportedAudioCodecs . Length > 0 )
2019-01-13 02:06:59 +01:00
{
2020-10-31 17:33:38 +01:00
var supportedAudioCodecsList = supportedAudioCodecs . ToList ( ) ;
2019-01-13 02:06:59 +01:00
ShiftAudioCodecsIfNeeded ( supportedAudioCodecsList , state . AudioStream ) ;
state . SupportedAudioCodecs = supportedAudioCodecsList . ToArray ( ) ;
request . AudioCodec = state . SupportedAudioCodecs . FirstOrDefault ( i = > _mediaEncoder . CanEncodeToAudioCodec ( i ) )
? ? state . SupportedAudioCodecs . FirstOrDefault ( ) ;
}
2020-11-12 04:02:56 +01:00
var supportedVideoCodecs = state . SupportedVideoCodecs ;
2022-12-05 15:01:13 +01:00
if ( request is not null & & supportedVideoCodecs is not null & & supportedVideoCodecs . Length > 0 )
2020-11-12 04:02:56 +01:00
{
var supportedVideoCodecsList = supportedVideoCodecs . ToList ( ) ;
ShiftVideoCodecsIfNeeded ( supportedVideoCodecsList , encodingOptions ) ;
state . SupportedVideoCodecs = supportedVideoCodecsList . ToArray ( ) ;
request . VideoCodec = state . SupportedVideoCodecs . FirstOrDefault ( ) ;
}
2019-01-13 02:06:59 +01:00
}
private void ShiftAudioCodecsIfNeeded ( List < string > audioCodecs , MediaStream audioStream )
{
2020-11-12 04:02:56 +01:00
// No need to shift if there is only one supported audio codec.
2019-01-13 02:06:59 +01:00
if ( audioCodecs . Count < 2 )
{
return ;
}
2022-12-05 15:00:20 +01:00
var inputChannels = audioStream is null ? 6 : audioStream . Channels ? ? 6 ;
2023-03-15 10:13:06 +01:00
var shiftAudioCodecs = new List < string > ( ) ;
2019-01-13 02:06:59 +01:00
if ( inputChannels > = 6 )
{
2023-03-15 10:13:06 +01:00
// DTS and TrueHD are not supported by HLS
// Keep them in the supported codecs list, but shift them to the end of the list so that if transcoding happens, another codec is used
shiftAudioCodecs . Add ( "dca" ) ;
shiftAudioCodecs . Add ( "truehd" ) ;
}
else
{
// Transcoding to 2ch ac3 or eac3 almost always causes a playback failure
// Keep them in the supported codecs list, but shift them to the end of the list so that if transcoding happens, another codec is used
shiftAudioCodecs . Add ( "ac3" ) ;
shiftAudioCodecs . Add ( "eac3" ) ;
2019-01-13 02:06:59 +01:00
}
2022-01-08 15:31:45 +01:00
if ( audioCodecs . All ( i = > shiftAudioCodecs . Contains ( i , StringComparison . OrdinalIgnoreCase ) ) )
2019-01-13 02:06:59 +01:00
{
return ;
}
2022-01-08 15:31:45 +01:00
while ( shiftAudioCodecs . Contains ( audioCodecs [ 0 ] , StringComparison . OrdinalIgnoreCase ) )
2019-01-13 02:06:59 +01:00
{
var removed = shiftAudioCodecs [ 0 ] ;
audioCodecs . RemoveAt ( 0 ) ;
audioCodecs . Add ( removed ) ;
}
2018-12-28 00:27:57 +01:00
}
2020-11-12 04:02:56 +01:00
private void ShiftVideoCodecsIfNeeded ( List < string > videoCodecs , EncodingOptions encodingOptions )
{
2023-06-19 21:49:26 +02:00
// No need to shift if there is only one supported video codec.
if ( videoCodecs . Count < 2 )
2020-11-12 04:02:56 +01:00
{
return ;
}
2023-06-19 21:49:26 +02:00
// Shift codecs to the end of list if it's not allowed.
var shiftVideoCodecs = new List < string > ( ) ;
if ( ! encodingOptions . AllowHevcEncoding )
2020-11-12 04:02:56 +01:00
{
2023-06-19 21:49:26 +02:00
shiftVideoCodecs . Add ( "hevc" ) ;
shiftVideoCodecs . Add ( "h265" ) ;
}
if ( ! encodingOptions . AllowAv1Encoding )
{
shiftVideoCodecs . Add ( "av1" ) ;
2020-11-12 04:02:56 +01:00
}
2022-01-08 15:31:45 +01:00
if ( videoCodecs . All ( i = > shiftVideoCodecs . Contains ( i , StringComparison . OrdinalIgnoreCase ) ) )
2020-11-12 04:02:56 +01:00
{
return ;
}
2022-01-08 15:31:45 +01:00
while ( shiftVideoCodecs . Contains ( videoCodecs [ 0 ] , StringComparison . OrdinalIgnoreCase ) )
2020-11-12 04:02:56 +01:00
{
var removed = shiftVideoCodecs [ 0 ] ;
videoCodecs . RemoveAt ( 0 ) ;
videoCodecs . Add ( removed ) ;
}
}
2018-12-28 00:27:57 +01:00
private void NormalizeSubtitleEmbed ( EncodingJobInfo state )
{
2022-12-05 15:00:20 +01:00
if ( state . SubtitleStream is null | | state . SubtitleDeliveryMethod ! = SubtitleDeliveryMethod . Embed )
2018-12-28 00:27:57 +01:00
{
return ;
}
// This is tricky to remux in, after converting to dvdsub it's not positioned correctly
// Therefore, let's just burn it in
if ( string . Equals ( state . SubtitleStream . Codec , "DVBSUB" , StringComparison . OrdinalIgnoreCase ) )
{
state . SubtitleDeliveryMethod = SubtitleDeliveryMethod . Encode ;
}
}
public string GetSubtitleEmbedArguments ( EncodingJobInfo state )
{
2022-12-05 15:00:20 +01:00
if ( state . SubtitleStream is null | | state . SubtitleDeliveryMethod ! = SubtitleDeliveryMethod . Embed )
2018-12-28 00:27:57 +01:00
{
return string . Empty ;
}
var format = state . SupportedSubtitleCodecs . FirstOrDefault ( ) ;
string codec ;
if ( string . IsNullOrEmpty ( format ) | | string . Equals ( format , state . SubtitleStream . Codec , StringComparison . OrdinalIgnoreCase ) )
{
codec = "copy" ;
}
else
{
codec = format ;
}
2019-09-01 18:39:23 +02:00
return " -codec:s:0 " + codec + " -disposition:s:0 default" ;
2018-12-28 00:27:57 +01:00
}
2019-06-02 00:03:48 +02:00
public string GetProgressiveVideoFullCommandLine ( EncodingJobInfo state , EncodingOptions encodingOptions , string outputPath , string defaultPreset )
2018-12-28 00:27:57 +01:00
{
// Get the output codec name
var videoCodec = GetVideoEncoder ( state , encodingOptions ) ;
var format = string . Empty ;
var keyFrame = string . Empty ;
2019-09-01 18:39:23 +02:00
if ( string . Equals ( Path . GetExtension ( outputPath ) , ".mp4" , StringComparison . OrdinalIgnoreCase )
& & state . BaseRequest . Context = = EncodingContext . Streaming )
2018-12-28 00:27:57 +01:00
{
// Comparison: https://github.com/jansmolders86/mediacenterjs/blob/master/lib/transcoding/desktop.js
2023-02-04 04:59:35 +01:00
format = " -f mp4 -movflags frag_keyframe+empty_moov+delay_moov" ;
2018-12-28 00:27:57 +01:00
}
var threads = GetNumberOfThreads ( state , encodingOptions , videoCodec ) ;
2022-03-09 14:28:58 +01:00
var inputModifier = GetInputModifier ( state , encodingOptions , null ) ;
2018-12-28 00:27:57 +01:00
2019-09-01 18:39:23 +02:00
return string . Format (
CultureInfo . InvariantCulture ,
"{0} {1}{2} {3} {4} -map_metadata -1 -map_chapters -1 -threads {5} {6}{7}{8} -y \"{9}\"" ,
2018-12-28 00:27:57 +01:00
inputModifier ,
2022-03-09 14:28:58 +01:00
GetInputArgument ( state , encodingOptions , null ) ,
2018-12-28 00:27:57 +01:00
keyFrame ,
GetMapArgs ( state ) ,
2019-06-02 00:03:48 +02:00
GetProgressiveVideoArguments ( state , encodingOptions , videoCodec , defaultPreset ) ,
2018-12-28 00:27:57 +01:00
threads ,
GetProgressiveVideoAudioArguments ( state , encodingOptions ) ,
GetSubtitleEmbedArguments ( state ) ,
format ,
2019-09-01 18:39:23 +02:00
outputPath ) . Trim ( ) ;
2018-12-28 00:27:57 +01:00
}
public string GetOutputFFlags ( EncodingJobInfo state )
{
var flags = new List < string > ( ) ;
if ( state . GenPtsOutput )
{
flags . Add ( "+genpts" ) ;
}
if ( flags . Count > 0 )
{
2021-06-06 17:16:41 +02:00
return " -fflags " + string . Join ( string . Empty , flags ) ;
2018-12-28 00:27:57 +01:00
}
return string . Empty ;
}
2019-06-02 00:03:48 +02:00
public string GetProgressiveVideoArguments ( EncodingJobInfo state , EncodingOptions encodingOptions , string videoCodec , string defaultPreset )
2018-12-28 00:27:57 +01:00
{
var args = "-codec:v:0 " + videoCodec ;
if ( state . BaseRequest . EnableMpegtsM2TsMode )
{
args + = " -mpegts_m2ts_mode 1" ;
}
2020-07-15 06:58:36 +02:00
if ( IsCopyCodec ( videoCodec ) )
2018-12-28 00:27:57 +01:00
{
2022-12-05 15:01:13 +01:00
if ( state . VideoStream is not null
2019-09-01 18:39:23 +02:00
& & string . Equals ( state . OutputContainer , "ts" , StringComparison . OrdinalIgnoreCase )
& & ! string . Equals ( state . VideoStream . NalLengthSize , "0" , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
2019-06-02 00:03:48 +02:00
string bitStreamArgs = GetBitStreamArgs ( state . VideoStream ) ;
if ( ! string . IsNullOrEmpty ( bitStreamArgs ) )
{
args + = " " + bitStreamArgs ;
}
2018-12-28 00:27:57 +01:00
}
if ( state . RunTimeTicks . HasValue & & state . BaseRequest . CopyTimestamps )
{
2020-11-19 15:46:02 +01:00
args + = " -copyts -avoid_negative_ts disabled -start_at_zero" ;
2018-12-28 00:27:57 +01:00
}
2019-02-23 16:01:41 +01:00
if ( ! state . RunTimeTicks . HasValue )
{
2019-12-22 13:01:18 +01:00
args + = " -fflags +genpts" ;
2019-02-23 16:01:41 +01:00
}
2018-12-28 00:27:57 +01:00
}
else
{
2019-09-01 18:39:23 +02:00
var keyFrameArg = string . Format (
CultureInfo . InvariantCulture ,
" -force_key_frames \"expr:gte(t,n_forced*{0})\"" ,
5 ) ;
2018-12-28 00:27:57 +01:00
args + = keyFrameArg ;
2022-12-05 15:01:13 +01:00
var hasGraphicalSubs = state . SubtitleStream is not null & & ! state . SubtitleStream . IsTextSubtitleStream & & state . SubtitleDeliveryMethod = = SubtitleDeliveryMethod . Encode ;
2018-12-28 00:27:57 +01:00
var hasCopyTs = false ;
2020-03-03 16:56:50 +01:00
2021-12-01 17:49:50 +01:00
// video processing filters.
var videoProcessParam = GetVideoProcessingFilterParam ( state , encodingOptions , videoCodec ) ;
2018-12-28 00:27:57 +01:00
2023-03-10 01:38:15 +01:00
var negativeMapArgs = GetNegativeMapArgsByFilters ( state , videoProcessParam ) ;
args = negativeMapArgs + args + videoProcessParam ;
2020-03-03 16:56:50 +01:00
2021-12-24 09:50:40 +01:00
hasCopyTs = videoProcessParam . Contains ( "copyts" , StringComparison . OrdinalIgnoreCase ) ;
2020-03-03 16:56:50 +01:00
2018-12-28 00:27:57 +01:00
if ( state . RunTimeTicks . HasValue & & state . BaseRequest . CopyTimestamps )
{
if ( ! hasCopyTs )
{
args + = " -copyts" ;
}
2019-09-01 18:39:23 +02:00
2020-11-19 15:46:02 +01:00
args + = " -avoid_negative_ts disabled" ;
2018-12-28 00:27:57 +01:00
2022-12-05 15:01:13 +01:00
if ( ! ( state . SubtitleStream is not null & & state . SubtitleStream . IsExternal & & ! state . SubtitleStream . IsTextSubtitleStream ) )
2020-03-03 16:56:50 +01:00
{
args + = " -start_at_zero" ;
}
2018-12-28 00:27:57 +01:00
}
2019-06-02 00:03:48 +02:00
var qualityParam = GetVideoQualityParam ( state , videoCodec , encodingOptions , defaultPreset ) ;
2018-12-28 00:27:57 +01:00
if ( ! string . IsNullOrEmpty ( qualityParam ) )
{
args + = " " + qualityParam . Trim ( ) ;
}
}
if ( ! string . IsNullOrEmpty ( state . OutputVideoSync ) )
{
args + = " -vsync " + state . OutputVideoSync ;
}
args + = GetOutputFFlags ( state ) ;
return args ;
}
public string GetProgressiveVideoAudioArguments ( EncodingJobInfo state , EncodingOptions encodingOptions )
{
// If the video doesn't have an audio stream, return a default.
2022-12-05 15:01:13 +01:00
if ( state . AudioStream is null & & state . VideoStream is not null )
2018-12-28 00:27:57 +01:00
{
return string . Empty ;
}
// Get the output codec name
var codec = GetAudioEncoder ( state ) ;
var args = "-codec:a:0 " + codec ;
2020-07-15 06:58:36 +02:00
if ( IsCopyCodec ( codec ) )
2018-12-28 00:27:57 +01:00
{
return args ;
}
var channels = state . OutputAudioChannels ;
2023-01-02 22:26:54 +01:00
if ( channels . HasValue & & ( ( channels . Value ! = 2 & & state . AudioStream . Channels < = 5 ) | | encodingOptions . DownMixStereoAlgorithm = = DownMixStereoAlgorithms . None ) )
2018-12-28 00:27:57 +01:00
{
args + = " -ac " + channels . Value ;
}
var bitrate = state . OutputAudioBitrate ;
2023-03-02 20:57:59 +01:00
if ( bitrate . HasValue & & ! LosslessAudioCodecs . Contains ( codec , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
2023-02-27 16:03:12 +01:00
var vbrParam = GetAudioVbrModeParam ( codec , bitrate . Value / ( channels ? ? 2 ) ) ;
if ( encodingOptions . EnableAudioVbr & & vbrParam is not null )
2022-11-07 00:15:04 +01:00
{
args + = vbrParam ;
}
else
{
args + = " -ab " + bitrate . Value . ToString ( CultureInfo . InvariantCulture ) ;
}
2018-12-28 00:27:57 +01:00
}
if ( state . OutputAudioSampleRate . HasValue )
{
2021-09-26 16:14:36 +02:00
args + = " -ar " + state . OutputAudioSampleRate . Value . ToString ( CultureInfo . InvariantCulture ) ;
2018-12-28 00:27:57 +01:00
}
2021-07-10 18:09:02 +02:00
args + = GetAudioFilterParam ( state , encodingOptions ) ;
2018-12-28 00:27:57 +01:00
return args ;
}
public string GetProgressiveAudioFullCommandLine ( EncodingJobInfo state , EncodingOptions encodingOptions , string outputPath )
{
var audioTranscodeParams = new List < string > ( ) ;
var bitrate = state . OutputAudioBitrate ;
2022-11-07 00:15:04 +01:00
var channels = state . OutputAudioChannels ;
2023-03-02 20:57:59 +01:00
var outputCodec = state . OutputAudioCodec ;
2018-12-28 00:27:57 +01:00
2023-03-02 20:57:59 +01:00
if ( bitrate . HasValue & & ! LosslessAudioCodecs . Contains ( outputCodec , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
2023-03-21 15:01:32 +01:00
var vbrParam = GetAudioVbrModeParam ( GetAudioEncoder ( state ) , bitrate . Value / ( channels ? ? 2 ) ) ;
2023-02-27 16:03:12 +01:00
if ( encodingOptions . EnableAudioVbr & & vbrParam is not null )
2022-11-07 00:15:04 +01:00
{
audioTranscodeParams . Add ( vbrParam ) ;
}
else
{
audioTranscodeParams . Add ( "-ab " + bitrate . Value . ToString ( CultureInfo . InvariantCulture ) ) ;
}
2018-12-28 00:27:57 +01:00
}
2022-11-07 00:15:04 +01:00
if ( channels . HasValue )
2018-12-28 00:27:57 +01:00
{
2021-09-26 16:14:36 +02:00
audioTranscodeParams . Add ( "-ac " + state . OutputAudioChannels . Value . ToString ( CultureInfo . InvariantCulture ) ) ;
2018-12-28 00:27:57 +01:00
}
2023-03-02 20:57:59 +01:00
if ( ! string . IsNullOrEmpty ( outputCodec ) )
2023-02-02 14:54:05 +01:00
{
audioTranscodeParams . Add ( "-acodec " + GetAudioEncoder ( state ) ) ;
}
2023-03-02 20:57:59 +01:00
if ( ! string . Equals ( outputCodec , "opus" , StringComparison . OrdinalIgnoreCase ) )
2018-12-28 00:27:57 +01:00
{
2022-05-08 23:23:58 +02:00
// opus only supports specific sampling rates
var sampleRate = state . OutputAudioSampleRate ;
if ( sampleRate . HasValue )
2018-12-28 00:27:57 +01:00
{
2022-05-08 23:23:58 +02:00
var sampleRateValue = sampleRate . Value switch
{
< = 8000 = > 8000 ,
< = 12000 = > 12000 ,
< = 16000 = > 16000 ,
< = 24000 = > 24000 ,
_ = > 48000
} ;
audioTranscodeParams . Add ( "-ar " + sampleRateValue . ToString ( CultureInfo . InvariantCulture ) ) ;
2018-12-28 00:27:57 +01:00
}
}
2023-02-04 02:56:14 +01:00
// Copy the movflags from GetProgressiveVideoFullCommandLine
2023-02-04 03:17:36 +01:00
// See #9248 and the associated PR for why this is needed
2023-02-04 19:52:35 +01:00
if ( _mp4ContainerNames . Contains ( state . OutputContainer ) )
2023-02-04 02:56:14 +01:00
{
2023-02-04 04:59:35 +01:00
audioTranscodeParams . Add ( "-movflags empty_moov+delay_moov" ) ;
2023-02-04 02:56:14 +01:00
}
2018-12-28 00:27:57 +01:00
var threads = GetNumberOfThreads ( state , encodingOptions , null ) ;
2022-03-09 14:28:58 +01:00
var inputModifier = GetInputModifier ( state , encodingOptions , null ) ;
2018-12-28 00:27:57 +01:00
2019-09-01 18:39:23 +02:00
return string . Format (
CultureInfo . InvariantCulture ,
"{0} {1}{7}{8} -threads {2}{3} {4} -id3v2_version 3 -write_id3v1 1{6} -y \"{5}\"" ,
2018-12-28 00:27:57 +01:00
inputModifier ,
2022-03-09 14:28:58 +01:00
GetInputArgument ( state , encodingOptions , null ) ,
2018-12-28 00:27:57 +01:00
threads ,
2019-09-01 18:39:23 +02:00
" -vn" ,
2021-02-13 00:39:18 +01:00
string . Join ( ' ' , audioTranscodeParams ) ,
2018-12-28 00:27:57 +01:00
outputPath ,
2019-09-01 18:39:23 +02:00
string . Empty ,
string . Empty ,
string . Empty ) . Trim ( ) ;
2018-12-28 00:27:57 +01:00
}
2020-05-25 23:58:19 +02:00
2022-05-04 16:20:48 +02:00
public static int FindIndex ( IReadOnlyList < MediaStream > mediaStreams , MediaStream streamToFind )
{
var index = 0 ;
var length = mediaStreams . Count ;
for ( var i = 0 ; i < length ; i + + )
{
var currentMediaStream = mediaStreams [ i ] ;
if ( currentMediaStream = = streamToFind )
{
return index ;
}
2022-08-14 03:46:33 +02:00
if ( string . Equals ( currentMediaStream . Path , streamToFind . Path , StringComparison . Ordinal ) )
2022-05-04 16:20:48 +02:00
{
index + + ;
}
}
return - 1 ;
}
2020-05-25 23:58:19 +02:00
public static bool IsCopyCodec ( string codec )
{
return string . Equals ( codec , "copy" , StringComparison . OrdinalIgnoreCase ) ;
}
2018-12-28 00:27:57 +01:00
}
}