├── .gitmodules ├── src ├── avs_libplacebo.rc ├── avs_libplacebo.h ├── plugin.cpp ├── common.cpp ├── deband.cpp ├── shader.cpp ├── resample.cpp └── tonemap.cpp ├── cmake_uninstall.cmake.in ├── .gitattributes ├── CMakeLists.txt ├── CHANGELOG.md ├── .gitignore ├── LICENSE └── README.md /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "libplacebo"] 2 | path = libplacebo 3 | url = https://gitlab.com/uvz/libplacebo 4 | [submodule "dovi_tool"] 5 | path = dovi_tool 6 | url = https://github.com/quietvoid/dovi_tool 7 | -------------------------------------------------------------------------------- /src/avs_libplacebo.rc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 1 VERSIONINFO 4 | FILEVERSION 1,5,2,0 5 | PRODUCTVERSION 1,5,2,0 6 | FILEFLAGSMASK VS_FFI_FILEFLAGSMASK 7 | FILETYPE VFT_DLL 8 | BEGIN 9 | BLOCK "StringFileInfo" 10 | BEGIN 11 | BLOCK "040904E4" 12 | BEGIN 13 | VALUE "Comments", "AviSynth+ plugin interface to libplacebo." 14 | VALUE "FileDescription", "avs_libplacebo for AviSynth+." 15 | VALUE "FileVersion", "1.5.2" 16 | VALUE "InternalName", "avs_libplacebo" 17 | VALUE "OriginalFilename", "avs_libplacebo.dll" 18 | VALUE "ProductName", "avs_libplacebo" 19 | VALUE "ProductVersion", "1.5.2" 20 | END 21 | END 22 | BLOCK "VarFileInfo" 23 | BEGIN 24 | VALUE "Translation", 0x409, 1252 25 | END 26 | END 27 | -------------------------------------------------------------------------------- /cmake_uninstall.cmake.in: -------------------------------------------------------------------------------- 1 | if(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt") 2 | message(FATAL_ERROR "Cannot find install manifest: @CMAKE_BINARY_DIR@/install_manifest.txt") 3 | endif() 4 | 5 | file(READ "@CMAKE_BINARY_DIR@/install_manifest.txt" files) 6 | string(REGEX REPLACE "\n" ";" files "${files}") 7 | foreach(file ${files}) 8 | message(STATUS "Uninstalling $ENV{DESTDIR}${file}") 9 | if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") 10 | exec_program( 11 | "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\"" 12 | OUTPUT_VARIABLE rm_out 13 | RETURN_VALUE rm_retval 14 | ) 15 | if(NOT "${rm_retval}" STREQUAL 0) 16 | message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}") 17 | endif() 18 | else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") 19 | message(STATUS "File $ENV{DESTDIR}${file} does not exist.") 20 | endif() 21 | endforeach() 22 | -------------------------------------------------------------------------------- /src/avs_libplacebo.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "avisynth_c.h" 9 | 10 | extern "C" 11 | { 12 | #include "libplacebo/dispatch.h" 13 | #include "libplacebo/renderer.h" 14 | #include "libplacebo/shaders.h" 15 | #include "libplacebo/utils/upload.h" 16 | #include "libplacebo/vulkan.h" 17 | } 18 | 19 | std::unique_ptr avs_libplacebo_init(const VkPhysicalDevice& device, std::string& err_msg); 20 | void avs_libplacebo_uninit(const std::unique_ptr& p); 21 | 22 | [[maybe_unused]] 23 | AVS_Value devices_info(AVS_Clip* clip, AVS_ScriptEnvironment* env, std::vector& devices, VkInstance& inst, std::string& msg, const std::string& name, const int device, const int list_device); 24 | AVS_Value avs_version(std::string& msg, const std::string& name, AVS_ScriptEnvironment* env); 25 | [[maybe_unused]] 26 | AVS_Value set_error(AVS_Clip* clip, const char* error_message, const std::unique_ptr& p); 27 | 28 | struct priv 29 | { 30 | pl_log log; 31 | pl_vulkan vk; 32 | pl_gpu gpu; 33 | pl_dispatch dp; 34 | pl_shader_obj dither_state; 35 | 36 | pl_renderer rr; 37 | pl_tex tex_in[3]; 38 | pl_tex tex_out[3]; 39 | 40 | std::ostringstream log_buffer; 41 | }; 42 | 43 | AVS_Value AVSC_CC create_deband(AVS_ScriptEnvironment* env, AVS_Value args, void* param); 44 | AVS_Value AVSC_CC create_resample(AVS_ScriptEnvironment* env, AVS_Value args, void* param); 45 | AVS_Value AVSC_CC create_shader(AVS_ScriptEnvironment* env, AVS_Value args, void* param); 46 | AVS_Value AVSC_CC create_tonemap(AVS_ScriptEnvironment* env, AVS_Value args, void* param); 47 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | #sources 2 | *.c text 3 | *.cc text 4 | *.cxx text 5 | *.cpp text 6 | *.c++ text 7 | *.hpp text 8 | *.h text 9 | *.h++ text 10 | *.hh text 11 | 12 | # Compiled Object files 13 | *.slo binary 14 | *.lo binary 15 | *.o binary 16 | *.obj binary 17 | 18 | # Precompiled Headers 19 | *.gch binary 20 | *.pch binary 21 | 22 | # Compiled Dynamic libraries 23 | *.so binary 24 | *.dylib binary 25 | *.dll binary 26 | 27 | # Compiled Static libraries 28 | *.lai binary 29 | *.la binary 30 | *.a binary 31 | *.lib binary 32 | 33 | # Executables 34 | *.exe binary 35 | *.out binary 36 | *.app binary 37 | ############################################################################### 38 | # Set default behavior to automatically normalize line endings. 39 | ############################################################################### 40 | * text=auto 41 | 42 | ############################################################################### 43 | # Set the merge driver for project and solution files 44 | # 45 | # Merging from the command prompt will add diff markers to the files if there 46 | # are conflicts (Merging from VS is not affected by the settings below, in VS 47 | # the diff markers are never inserted). Diff markers may cause the following 48 | # file extensions to fail to load in VS. An alternative would be to treat 49 | # these files as binary and thus will always conflict and require user 50 | # intervention with every merge. To do so, just comment the entries below and 51 | # uncomment the group further below 52 | ############################################################################### 53 | 54 | *.sln text eol=crlf 55 | *.csproj text eol=crlf 56 | *.vbproj text eol=crlf 57 | *.vcxproj text eol=crlf 58 | *.vcproj text eol=crlf 59 | *.dbproj text eol=crlf 60 | *.fsproj text eol=crlf 61 | *.lsproj text eol=crlf 62 | *.wixproj text eol=crlf 63 | *.modelproj text eol=crlf 64 | *.sqlproj text eol=crlf 65 | *.wmaproj text eol=crlf 66 | 67 | *.xproj text eol=crlf 68 | *.props text eol=crlf 69 | *.filters text eol=crlf 70 | *.vcxitems text eol=crlf 71 | 72 | 73 | #*.sln merge=binary 74 | #*.csproj merge=binary 75 | #*.vbproj merge=binary 76 | #*.vcxproj merge=binary 77 | #*.vcproj merge=binary 78 | #*.dbproj merge=binary 79 | #*.fsproj merge=binary 80 | #*.lsproj merge=binary 81 | #*.wixproj merge=binary 82 | #*.modelproj merge=binary 83 | #*.sqlproj merge=binary 84 | #*.wwaproj merge=binary 85 | 86 | #*.xproj merge=binary 87 | #*.props merge=binary 88 | #*.filters merge=binary 89 | #*.vcxitems merge=binary 90 | -------------------------------------------------------------------------------- /src/plugin.cpp: -------------------------------------------------------------------------------- 1 | #include "avs_libplacebo.h" 2 | 3 | const char* AVSC_CC avisynth_c_plugin_init(AVS_ScriptEnvironment* env) 4 | { 5 | avs_add_function(env, "libplacebo_Deband", 6 | "c" 7 | "[iterations]i" 8 | "[threshold]f" 9 | "[radius]f" 10 | "[grainY]f" 11 | "[grainC]f" 12 | "[dither]i" 13 | "[lut_size]i" 14 | "[temporal]b" 15 | "[planes]i*" 16 | "[device]i" 17 | "[list_device]b" 18 | "[grain_neutral]f*", 19 | create_deband, 0); 20 | 21 | avs_add_function(env, "libplacebo_Resample", 22 | "c" 23 | "i" 24 | "i" 25 | "[filter]s" 26 | "[radius]f" 27 | "[clamp]f" 28 | "[taper]f" 29 | "[blur]f" 30 | "[param1]f" 31 | "[param2]f" 32 | "[sx]f" 33 | "[sy]f" 34 | "[antiring]f" 35 | "[sigmoidize]b" 36 | "[linearize]b" 37 | "[sigmoid_center]f" 38 | "[sigmoid_slope]f" 39 | "[trc]i" 40 | "[cplace]i" 41 | "[device]i" 42 | "[list_device]b" 43 | "[src_width]f" 44 | "[src_height]f", 45 | create_resample, 0); 46 | 47 | avs_add_function(env, "libplacebo_Shader", 48 | "c" 49 | "s" 50 | "[width]i" 51 | "[height]i" 52 | "[chroma_loc]i" 53 | "[matrix]i" 54 | "[trc]i" 55 | "[filter]s" 56 | "[radius]f" 57 | "[clamp]f" 58 | "[taper]f" 59 | "[blur]f" 60 | "[param1]f" 61 | "[param2]f" 62 | "[antiring]f" 63 | "[sigmoidize]b" 64 | "[linearize]b" 65 | "[sigmoid_center]f" 66 | "[sigmoid_slope]f" 67 | "[shader_param]s" 68 | "[device]i" 69 | "[list_device]b", 70 | create_shader, 0); 71 | 72 | avs_add_function(env, "libplacebo_Tonemap", 73 | "c" 74 | "[src_csp]i" 75 | "[dst_csp]i" 76 | "[src_max]f" 77 | "[src_min]f" 78 | "[dst_max]f" 79 | "[dst_min]f" 80 | "[dynamic_peak_detection]b" 81 | "[smoothing_period]f" 82 | "[scene_threshold_low]f" 83 | "[scene_threshold_high]f" 84 | "[percentile]f" 85 | "[black_cutoff]f" 86 | "[gamut_mapping_mode]s" 87 | "[tone_mapping_function]s" 88 | "[tone_constants]s*" 89 | "[metadata]i" 90 | "[contrast_recovery]f" 91 | "[contrast_smoothness]f" 92 | "[visualize_lut]b" 93 | "[show_clipping]b" 94 | "[use_dovi]b" 95 | "[device]i" 96 | "[list_device]b" 97 | "[cscale]s" 98 | "[lut]s" 99 | "[lut_type]i" 100 | "[dst_prim]i" 101 | "[dst_trc]i" 102 | "[dst_sys]i", 103 | create_tonemap, 0); 104 | 105 | return "avslibplacebo"; 106 | } 107 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.25) 2 | 3 | if (NOT CMAKE_GENERATOR MATCHES "Visual Studio") 4 | if (NOT CMAKE_BUILD_TYPE) 5 | set(CMAKE_BUILD_TYPE "Release" CACHE STRING "" FORCE) 6 | endif() 7 | endif() 8 | 9 | project(avs_libplacebo LANGUAGES CXX) 10 | 11 | find_package(Vulkan REQUIRED COMPONENTS shaderc_combined) 12 | 13 | set(sources 14 | ${CMAKE_CURRENT_SOURCE_DIR}/src/common.cpp 15 | ${CMAKE_CURRENT_SOURCE_DIR}/src/deband.cpp 16 | ${CMAKE_CURRENT_SOURCE_DIR}/src/plugin.cpp 17 | ${CMAKE_CURRENT_SOURCE_DIR}/src/resample.cpp 18 | ${CMAKE_CURRENT_SOURCE_DIR}/src/shader.cpp 19 | ${CMAKE_CURRENT_SOURCE_DIR}/src/tonemap.cpp 20 | ) 21 | 22 | if (WIN32) 23 | set(sources ${sources} ${CMAKE_CURRENT_SOURCE_DIR}/src/avs_libplacebo.rc) 24 | endif() 25 | 26 | add_library(avs_libplacebo SHARED ${sources}) 27 | 28 | target_include_directories(avs_libplacebo PRIVATE 29 | ${CMAKE_CURRENT_SOURCE_DIR}/src 30 | ${Vulkan_INCLUDE_DIRS} 31 | ) 32 | 33 | if (UNIX) 34 | target_include_directories(avs_libplacebo PRIVATE 35 | /usr/local/include/avisynth 36 | /usr/local/include 37 | ) 38 | endif() 39 | 40 | if (WIN32) 41 | target_link_libraries(avs_libplacebo PRIVATE 42 | ws2_32 43 | bcrypt 44 | userenv 45 | shlwapi 46 | Ntdll 47 | ) 48 | endif() 49 | 50 | find_library(dovi dovi) 51 | find_library(libplacebo libplacebo) 52 | 53 | target_link_libraries(avs_libplacebo PRIVATE 54 | avisynth 55 | Vulkan::Vulkan 56 | Vulkan::shaderc_combined 57 | ${dovi} 58 | ${libplacebo} 59 | ) 60 | 61 | if (MINGW) 62 | set_target_properties(avs_libplacebo PROPERTIES PREFIX "") 63 | 64 | target_link_libraries(avs_libplacebo PRIVATE -static-libgcc -static-libstdc++ -s) 65 | endif() 66 | 67 | if (NOT CMAKE_GENERATOR MATCHES "Visual Studio") 68 | string(TOLOWER ${CMAKE_BUILD_TYPE} build_type) 69 | if (build_type STREQUAL Debug) 70 | target_compile_definitions(avs_libplacebo PRIVATE DEBUG_BUILD) 71 | else (build_type STREQUAL Release) 72 | target_compile_definitions(avs_libplacebo PRIVATE RELEASE_BUILD) 73 | endif() 74 | 75 | target_compile_options(avs_libplacebo PRIVATE $<$:-s>) 76 | 77 | message(STATUS "Build type - ${CMAKE_BUILD_TYPE}") 78 | endif() 79 | 80 | target_compile_options(avs_libplacebo PRIVATE "-DPL_STATIC") 81 | 82 | target_compile_features(avs_libplacebo PRIVATE cxx_std_20) 83 | 84 | if (UNIX) 85 | find_package (Git) 86 | 87 | if (GIT_FOUND) 88 | execute_process (COMMAND ${GIT_EXECUTABLE} describe --tags --abbrev=0 89 | OUTPUT_VARIABLE ver 90 | OUTPUT_STRIP_TRAILING_WHITESPACE 91 | ) 92 | set_target_properties(avs_libplacebo PROPERTIES OUTPUT_NAME "avs_libplacebo.${ver}") 93 | else() 94 | message (STATUS "GIT not found") 95 | endif() 96 | 97 | include(GNUInstallDirs) 98 | 99 | INSTALL(TARGETS avs_libplacebo LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}/avisynth") 100 | 101 | # uninstall target 102 | if(NOT TARGET uninstall) 103 | configure_file( 104 | "${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake.in" 105 | "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" 106 | IMMEDIATE @ONLY) 107 | 108 | add_custom_target(uninstall 109 | COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) 110 | endif() 111 | endif() 112 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ##### 1.5.2: 2 | Tonemap: allowed SDR->HDR conversion. 3 | Tonemap: fixed opening lut file in some cases (ACP). 4 | Shader: fixed opening shader file in some cases (ACP). 5 | Deband/Resample: improved speed (faster upload/dowload data). 6 | 7 | ##### 1.5.1: 8 | Resample/Shader: fixed `param1` and `param2`. 9 | libplacebo error messages are propagated. 10 | 11 | ##### 1.5.0: 12 | Fixed more error messages. 13 | Moved some memory freeing right after the plane is downloaded. 14 | Resample/Shader: removed parameters `lut_entries` and `cutoff`. 15 | Added filter/cscale `ewa_lanczossharp`, `ewa_lanczos4sharpest` and `mitchell_clamp`. 16 | Tonemap: changed the type of `gamut_mapping_mode` and `tone_mapping_function` from `int` to `string`. 17 | Tonemap: removed parameters `tone_mapping_mode`, `tone_mapping_param`, `tone_mapping_crosstalk`. 18 | Tonemap: changed default value of `smoothing_period` from `100.0` to `20.0`. 19 | Tonemap: changed default value of `scene_threshold_low` from `5.5` to `1.0`. 20 | Tonemap: changed default value of `scene_threshold_high` from `10.0` to `3.0`. 21 | Tonemap: removed `gamut_mapping_mode` `auto` and changed default value to `perceptual`. 22 | Tonemap: added `gamut_mapping_mode` `softclip`. 23 | Tonemap: removed `tone_mapping_function` `auto` and changed default value to `bt2390`. 24 | Tonemap: added `tone_mapping_function` `linearlight`. 25 | Tonemap: added parameter `tone_constants`. 26 | 27 | ##### 1.4.1: 28 | Tonemap: added parameters lut, lut_type. 29 | Tonemap: added parameters dst_prim/trc/sys. 30 | 31 | ##### 1.4.0: 32 | Tonemap: added cscale parameter. 33 | Tonemap: replaced parameters intent, gamut_mode with gamut_mapping_mode. 34 | 35 | ##### 1.3.0: 36 | Tonemap: added parameters contrast_recovery and contrast_smoothness. 37 | Fixed crashing when unsupported Avs+ used by explicitly throwing error. 38 | Changed the required Avs+ version. 39 | 40 | ##### 1.2.0: 41 | Resample/Shader: added trc ST428. 42 | Tonemap: added parameters percentile, metadata, visualize_lut, show_clipping. 43 | Tonemap: added tone_mapping_function st2094_40, st2094_10. 44 | Shader/Tonemap: improved speed. (based on https://github.com/Lypheo/vs-placebo/commit/09075cf2a3768b7c87903bb23640916b0b3b68cc) 45 | Tonemap: added support for libdovi 3. (based on https://github.com/Lypheo/vs-placebo/commit/f65161b7dd167b60e7af4670a692c6df3c40de6e) 46 | Removed libp2p dependency. 47 | Tonemap: fixed wrong levels when output is SDR. 48 | Tonemap: remove HDR frame props when output is SDR. 49 | Tonemap: added support for libplacebo v5.264.0. (based on https://github.com/Lypheo/vs-placebo/commit/4a42255c880572d75c8b50b69b784a67fd93e241) 50 | Shader: removed shader_param limit. 51 | 52 | ##### 1.1.5: 53 | libplacebo_Tonemap: fixed `dst_min`. 54 | 55 | ##### 1.1.4: 56 | libplacebo_Tonemap: fixed `src_csp` < 3. 57 | 58 | ##### 1.1.3: 59 | libplacebo_Resample: added `src_width` and `src_height` parameters. 60 | libplacebo_Deband: added `grain_neutral` parameter. 61 | 62 | ##### 1.1.2: 63 | libplacebo_Tonemap: properly handle video w/o `DolbyVisionRPU`. 64 | 65 | ##### 1.1.1: 66 | libplacebo_Resample: fixed chroma location for YUV444. 67 | 68 | ##### 1.1.0: 69 | libplacebo_Deband: replaced parameter `grain` with `grainY` and `grainC`. 70 | Fixed undefined behavior when upstream throw runtime error. 71 | libplacebo_Tonemap: throw error when src_csp=3 and there is no frame property `DolbyVisionRPU`. 72 | libplacebo_Tonemap: fixed black point for any Dolby Vision to PQ conversion. 73 | 74 | ##### 1.0.1: 75 | libplacebo_Shader: added shader_param. 76 | 77 | ##### 1.0.0: 78 | Initial release. (port of the vs-placebo 1.4.2) 79 | -------------------------------------------------------------------------------- /src/common.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "avs_libplacebo.h" 4 | 5 | static_assert(PL_API_VER >= 349, "libplacebo version must be at least v7.349.0."); 6 | 7 | static void pl_logging(void* stream, pl_log_level level, const char* msg) 8 | { 9 | constexpr const char* const constants_list[] 10 | { 11 | "[fatal] ", 12 | "[error] ", 13 | "[warn] ", 14 | "[info] ", 15 | "[debug] ", 16 | "[trace] " 17 | }; 18 | 19 | if (level <= PL_LOG_WARN) 20 | std::cerr << constants_list[level - 1] << msg << "\n"; 21 | else 22 | std::cout << constants_list[level - 1] << msg << "\n"; 23 | } 24 | 25 | std::unique_ptr avs_libplacebo_init(const VkPhysicalDevice& device, std::string& err_msg) 26 | { 27 | std::unique_ptr p{ std::make_unique() }; 28 | //std::cout.rdbuf(p->log_buffer.rdbuf()); 29 | std::cerr.rdbuf(p->log_buffer.rdbuf()); 30 | pl_log_params log_params{ pl_logging, nullptr, PL_LOG_ERR }; 31 | p->log = pl_log_create(0, &log_params); 32 | 33 | pl_vulkan_params vp{}; 34 | vp.allow_software = true; 35 | 36 | if (device) 37 | { 38 | VkPhysicalDeviceProperties properties{}; 39 | vkGetPhysicalDeviceProperties(device, &properties); 40 | vp.device_name = properties.deviceName; 41 | } 42 | 43 | p->vk = pl_vulkan_create(p->log, &vp); 44 | if (!p->vk) 45 | { 46 | err_msg = p->log_buffer.str(); 47 | pl_log_destroy(&p->log); 48 | return nullptr; 49 | } 50 | // Give this a shorter name for convenience 51 | p->gpu = p->vk->gpu; 52 | 53 | p->dp = pl_dispatch_create(p->log, p->gpu); 54 | if (!p->dp) 55 | { 56 | pl_vulkan_destroy(&p->vk); 57 | 58 | err_msg = p->log_buffer.str(); 59 | pl_log_destroy(&p->log); 60 | return nullptr; 61 | } 62 | 63 | p->rr = pl_renderer_create(p->log, p->gpu); 64 | if (!p->rr) 65 | { 66 | pl_dispatch_destroy(&p->dp); 67 | pl_vulkan_destroy(&p->vk); 68 | 69 | err_msg = p->log_buffer.str(); 70 | pl_log_destroy(&p->log); 71 | return nullptr; 72 | } 73 | 74 | return p; 75 | } 76 | 77 | void avs_libplacebo_uninit(const std::unique_ptr& p) 78 | { 79 | pl_renderer_destroy(&p->rr); 80 | pl_dispatch_destroy(&p->dp); 81 | pl_vulkan_destroy(&p->vk); 82 | pl_log_destroy(&p->log); 83 | } 84 | 85 | AVS_Value devices_info(AVS_Clip* clip, AVS_ScriptEnvironment* env, std::vector& devices, VkInstance& inst, std::string& msg, const std::string& name, const int device, const int list_device) 86 | { 87 | VkInstanceCreateInfo info{}; 88 | info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; 89 | 90 | uint32_t dev_count{ 0 }; 91 | 92 | if (vkCreateInstance(&info, nullptr, &inst)) 93 | { 94 | vkDestroyInstance(inst, nullptr); 95 | avs_release_clip(clip); 96 | 97 | msg = name + ": failed to create instance."; 98 | return avs_new_value_error(msg.c_str()); 99 | } 100 | 101 | if (vkEnumeratePhysicalDevices(inst, &dev_count, nullptr)) 102 | { 103 | vkDestroyInstance(inst, nullptr); 104 | avs_release_clip(clip); 105 | 106 | msg = name + ": failed to get devices number."; 107 | return avs_new_value_error(msg.c_str()); 108 | } 109 | 110 | if (device < -1 || device > static_cast(dev_count) - 1) 111 | { 112 | vkDestroyInstance(inst, nullptr); 113 | avs_release_clip(clip); 114 | 115 | msg = name + ": device must be between -1 and " + std::to_string(dev_count - 1); 116 | return avs_new_value_error(msg.c_str()); 117 | } 118 | 119 | devices.resize(dev_count); 120 | 121 | if (vkEnumeratePhysicalDevices(inst, &dev_count, devices.data())) 122 | { 123 | vkDestroyInstance(inst, nullptr); 124 | avs_release_clip(clip); 125 | 126 | msg = name + ": failed to get devices."; 127 | return avs_new_value_error(msg.c_str()); 128 | } 129 | 130 | if (list_device) 131 | { 132 | for (size_t i{ 0 }; i < devices.size(); ++i) 133 | { 134 | VkPhysicalDeviceProperties properties{}; 135 | vkGetPhysicalDeviceProperties(devices[i], &properties); 136 | 137 | msg += std::to_string(i) + ": " + std::string(properties.deviceName) + "\n"; 138 | } 139 | 140 | vkDestroyInstance(inst, nullptr); 141 | 142 | AVS_Value cl{ avs_new_value_clip(clip) }; 143 | AVS_Value args_[2]{ cl, avs_new_value_string(msg.c_str()) }; 144 | AVS_Value inv{ avs_invoke(env, "Text", avs_new_value_array(args_, 2), 0) }; 145 | 146 | avs_release_value(cl); 147 | avs_release_clip(clip); 148 | 149 | return inv; 150 | } 151 | else 152 | return avs_void; 153 | } 154 | 155 | AVS_Value avs_version(std::string& msg, const std::string& name, AVS_ScriptEnvironment* env) 156 | { 157 | if (!avs_check_version(env, 9)) 158 | { 159 | if (avs_check_version(env, 10)) 160 | { 161 | if (avs_get_env_property(env, AVS_AEP_INTERFACE_BUGFIX) < 2) 162 | { 163 | msg = name + ": AviSynth+ version must be r3688 or later."; 164 | return avs_new_value_error(msg.c_str()); 165 | } 166 | 167 | } 168 | } 169 | else 170 | { 171 | msg = name + ": AviSynth+ version must be r3688 or later."; 172 | return avs_new_value_error(msg.c_str()); 173 | } 174 | 175 | return avs_void; 176 | } 177 | 178 | AVS_Value set_error(AVS_Clip* clip, const char* error_message, const std::unique_ptr& p) 179 | { 180 | avs_release_clip(clip); 181 | 182 | if (p) 183 | avs_libplacebo_uninit(p); 184 | 185 | return avs_new_value_error(error_message); 186 | } 187 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.vspscc 94 | *.vssscc 95 | .builds 96 | *.pidb 97 | *.svclog 98 | *.scc 99 | 100 | # Chutzpah Test files 101 | _Chutzpah* 102 | 103 | # Visual C++ cache files 104 | ipch/ 105 | *.aps 106 | *.ncb 107 | *.opendb 108 | *.opensdf 109 | *.sdf 110 | *.cachefile 111 | *.VC.db 112 | *.VC.VC.opendb 113 | 114 | # Visual Studio profiler 115 | *.psess 116 | *.vsp 117 | *.vspx 118 | *.sap 119 | 120 | # Visual Studio Trace Files 121 | *.e2e 122 | 123 | # TFS 2012 Local Workspace 124 | $tf/ 125 | 126 | # Guidance Automation Toolkit 127 | *.gpState 128 | 129 | # ReSharper is a .NET coding add-in 130 | _ReSharper*/ 131 | *.[Rr]e[Ss]harper 132 | *.DotSettings.user 133 | 134 | # TeamCity is a build add-in 135 | _TeamCity* 136 | 137 | # DotCover is a Code Coverage Tool 138 | *.dotCover 139 | 140 | # AxoCover is a Code Coverage Tool 141 | .axoCover/* 142 | !.axoCover/settings.json 143 | 144 | # Coverlet is a free, cross platform Code Coverage Tool 145 | coverage*.json 146 | coverage*.xml 147 | coverage*.info 148 | 149 | # Visual Studio code coverage results 150 | *.coverage 151 | *.coveragexml 152 | 153 | # NCrunch 154 | _NCrunch_* 155 | .*crunch*.local.xml 156 | nCrunchTemp_* 157 | 158 | # MightyMoose 159 | *.mm.* 160 | AutoTest.Net/ 161 | 162 | # Web workbench (sass) 163 | .sass-cache/ 164 | 165 | # Installshield output folder 166 | [Ee]xpress/ 167 | 168 | # DocProject is a documentation generator add-in 169 | DocProject/buildhelp/ 170 | DocProject/Help/*.HxT 171 | DocProject/Help/*.HxC 172 | DocProject/Help/*.hhc 173 | DocProject/Help/*.hhk 174 | DocProject/Help/*.hhp 175 | DocProject/Help/Html2 176 | DocProject/Help/html 177 | 178 | # Click-Once directory 179 | publish/ 180 | 181 | # Publish Web Output 182 | *.[Pp]ublish.xml 183 | *.azurePubxml 184 | # Note: Comment the next line if you want to checkin your web deploy settings, 185 | # but database connection strings (with potential passwords) will be unencrypted 186 | *.pubxml 187 | *.publishproj 188 | 189 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 190 | # checkin your Azure Web App publish settings, but sensitive information contained 191 | # in these scripts will be unencrypted 192 | PublishScripts/ 193 | 194 | # NuGet Packages 195 | *.nupkg 196 | # NuGet Symbol Packages 197 | *.snupkg 198 | # The packages folder can be ignored because of Package Restore 199 | **/[Pp]ackages/* 200 | # except build/, which is used as an MSBuild target. 201 | !**/[Pp]ackages/build/ 202 | # Uncomment if necessary however generally it will be regenerated when needed 203 | #!**/[Pp]ackages/repositories.config 204 | # NuGet v3's project.json files produces more ignorable files 205 | *.nuget.props 206 | *.nuget.targets 207 | 208 | # Microsoft Azure Build Output 209 | csx/ 210 | *.build.csdef 211 | 212 | # Microsoft Azure Emulator 213 | ecf/ 214 | rcf/ 215 | 216 | # Windows Store app package directories and files 217 | AppPackages/ 218 | BundleArtifacts/ 219 | Package.StoreAssociation.xml 220 | _pkginfo.txt 221 | *.appx 222 | *.appxbundle 223 | *.appxupload 224 | 225 | # Visual Studio cache files 226 | # files ending in .cache can be ignored 227 | *.[Cc]ache 228 | # but keep track of directories ending in .cache 229 | !?*.[Cc]ache/ 230 | 231 | # Others 232 | ClientBin/ 233 | ~$* 234 | *~ 235 | *.dbmdl 236 | *.dbproj.schemaview 237 | *.jfm 238 | *.pfx 239 | *.publishsettings 240 | orleans.codegen.cs 241 | 242 | # Including strong name files can present a security risk 243 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 244 | #*.snk 245 | 246 | # Since there are multiple workflows, uncomment next line to ignore bower_components 247 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 248 | #bower_components/ 249 | 250 | # RIA/Silverlight projects 251 | Generated_Code/ 252 | 253 | # Backup & report files from converting an old project file 254 | # to a newer Visual Studio version. Backup files are not needed, 255 | # because we have git ;-) 256 | _UpgradeReport_Files/ 257 | Backup*/ 258 | UpgradeLog*.XML 259 | UpgradeLog*.htm 260 | ServiceFabricBackup/ 261 | *.rptproj.bak 262 | 263 | # SQL Server files 264 | *.mdf 265 | *.ldf 266 | *.ndf 267 | 268 | # Business Intelligence projects 269 | *.rdl.data 270 | *.bim.layout 271 | *.bim_*.settings 272 | *.rptproj.rsuser 273 | *- [Bb]ackup.rdl 274 | *- [Bb]ackup ([0-9]).rdl 275 | *- [Bb]ackup ([0-9][0-9]).rdl 276 | 277 | # Microsoft Fakes 278 | FakesAssemblies/ 279 | 280 | # GhostDoc plugin setting file 281 | *.GhostDoc.xml 282 | 283 | # Node.js Tools for Visual Studio 284 | .ntvs_analysis.dat 285 | node_modules/ 286 | 287 | # Visual Studio 6 build log 288 | *.plg 289 | 290 | # Visual Studio 6 workspace options file 291 | *.opt 292 | 293 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 294 | *.vbw 295 | 296 | # Visual Studio LightSwitch build output 297 | **/*.HTMLClient/GeneratedArtifacts 298 | **/*.DesktopClient/GeneratedArtifacts 299 | **/*.DesktopClient/ModelManifest.xml 300 | **/*.Server/GeneratedArtifacts 301 | **/*.Server/ModelManifest.xml 302 | _Pvt_Extensions 303 | 304 | # Paket dependency manager 305 | .paket/paket.exe 306 | paket-files/ 307 | 308 | # FAKE - F# Make 309 | .fake/ 310 | 311 | # CodeRush personal settings 312 | .cr/personal 313 | 314 | # Python Tools for Visual Studio (PTVS) 315 | __pycache__/ 316 | *.pyc 317 | 318 | # Cake - Uncomment if you are using it 319 | # tools/** 320 | # !tools/packages.config 321 | 322 | # Tabs Studio 323 | *.tss 324 | 325 | # Telerik's JustMock configuration file 326 | *.jmconfig 327 | 328 | # BizTalk build output 329 | *.btp.cs 330 | *.btm.cs 331 | *.odx.cs 332 | *.xsd.cs 333 | 334 | # OpenCover UI analysis results 335 | OpenCover/ 336 | 337 | # Azure Stream Analytics local run output 338 | ASALocalRun/ 339 | 340 | # MSBuild Binary and Structured Log 341 | *.binlog 342 | 343 | # NVidia Nsight GPU debugger configuration file 344 | *.nvuser 345 | 346 | # MFractors (Xamarin productivity tool) working folder 347 | .mfractor/ 348 | 349 | # Local History for Visual Studio 350 | .localhistory/ 351 | 352 | # BeatPulse healthcheck temp database 353 | healthchecksdb 354 | 355 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 356 | MigrationBackup/ 357 | 358 | # Ionide (cross platform F# VS Code tools) working folder 359 | .ionide/ 360 | 361 | # Fody - auto-generated XML schema 362 | FodyWeavers.xsd 363 | -------------------------------------------------------------------------------- /src/deband.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "avs_libplacebo.h" 4 | 5 | static std::mutex mtx; 6 | 7 | struct deband 8 | { 9 | std::unique_ptr vf; 10 | int process[3]; 11 | int dither; 12 | std::unique_ptr dither_params; 13 | std::unique_ptr deband_params; 14 | std::unique_ptr deband_params1; 15 | uint8_t frame_index; 16 | std::string msg; 17 | 18 | int (*deband_process)(AVS_VideoFrame* dst, AVS_VideoFrame* src, deband* d, const AVS_FilterInfo* vi) noexcept; 19 | }; 20 | 21 | static bool deband_do_plane(deband* d, const int planeIdx) noexcept 22 | { 23 | pl_shader sh{ pl_dispatch_begin(d->vf->dp) }; 24 | 25 | pl_shader_params sh_p{}; 26 | sh_p.gpu = d->vf->gpu; 27 | sh_p.index = d->frame_index++; 28 | 29 | pl_shader_reset(sh, &sh_p); 30 | 31 | pl_sample_src src{}; 32 | src.tex = d->vf->tex_in[0]; 33 | 34 | pl_shader_deband(sh, &src, ((planeIdx == AVS_PLANAR_U || planeIdx == AVS_PLANAR_V) && 35 | d->deband_params1) ? d->deband_params1.get() : d->deband_params.get()); 36 | 37 | if (d->dither) 38 | pl_shader_dither(sh, d->vf->tex_out[0]->params.format->component_depth[0], &d->vf->dither_state, d->dither_params.get()); 39 | 40 | pl_dispatch_params d_p{}; 41 | d_p.target = d->vf->tex_out[0]; 42 | d_p.shader = &sh; 43 | 44 | return pl_dispatch_finish(d->vf->dp, &d_p); 45 | } 46 | 47 | template 48 | static int deband_filter(AVS_VideoFrame* dst, AVS_VideoFrame* src, deband* d, const AVS_FilterInfo* fi) noexcept 49 | { 50 | const int error{ [&]() 51 | { 52 | pl_shader_obj_destroy(&d->vf->dither_state); 53 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_out[0]); 54 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_in[0]); 55 | 56 | return -1; 57 | }() }; 58 | 59 | const pl_fmt fmt{ [&]() 60 | { 61 | if constexpr (std::is_same_v) 62 | return pl_find_named_fmt(d->vf->gpu, "r8"); 63 | else if constexpr (std::is_same_v) 64 | return pl_find_named_fmt(d->vf->gpu, "r16"); 65 | else 66 | return pl_find_named_fmt(d->vf->gpu, "r32f"); 67 | }() }; 68 | if (!fmt) 69 | return error; 70 | 71 | constexpr int planes_y[3]{ AVS_PLANAR_Y, AVS_PLANAR_U, AVS_PLANAR_V }; 72 | constexpr int planes_r[3]{ AVS_PLANAR_R, AVS_PLANAR_G, AVS_PLANAR_B }; 73 | const int* planes{ (avs_is_rgb(&fi->vi)) ? planes_r : planes_y }; 74 | const int num_planes{ std::min(avs_num_components(&fi->vi), 3) }; 75 | 76 | for (int i{ 0 }; i < num_planes; ++i) 77 | { 78 | const int plane{ planes[i] }; 79 | 80 | if (d->process[i] == 2) 81 | avs_bit_blt(fi->env, avs_get_write_ptr_p(dst, plane), avs_get_pitch_p(dst, plane), avs_get_read_ptr_p(src, plane), 82 | avs_get_pitch_p(src, plane), avs_get_row_size_p(src, plane), avs_get_height_p(src, plane)); 83 | else if (d->process[i] == 3) 84 | { 85 | pl_plane_data pl{}; 86 | pl.pixel_stride = sizeof(T); 87 | if constexpr (std::is_same_v) 88 | { 89 | pl.type = PL_FMT_UNORM; 90 | pl.component_size[0] = 8; 91 | } 92 | else if constexpr (std::is_same_v) 93 | { 94 | pl.type = PL_FMT_UNORM; 95 | pl.component_size[0] = 16; 96 | } 97 | else 98 | { 99 | pl.type = PL_FMT_FLOAT; 100 | pl.component_size[0] = 32; 101 | } 102 | pl.width = avs_get_row_size_p(src, plane) / sizeof(T); 103 | pl.height = avs_get_height_p(src, plane); 104 | pl.row_stride = avs_get_pitch_p(src, plane); 105 | pl.pixels = avs_get_read_ptr_p(src, plane); 106 | 107 | std::lock_guard lck(mtx); 108 | 109 | // Upload planes 110 | if (!pl_upload_plane(d->vf->gpu, nullptr, &d->vf->tex_in[0], &pl)) 111 | return error; 112 | 113 | pl_tex_params t_r{}; 114 | t_r.format = fmt; 115 | t_r.w = pl.width; 116 | t_r.h = pl.height; 117 | t_r.sampleable = false; 118 | t_r.host_writable = false; 119 | t_r.renderable = true; 120 | t_r.host_readable = true; 121 | 122 | if (!pl_tex_recreate(d->vf->gpu, &d->vf->tex_out[0], &t_r)) 123 | return error; 124 | 125 | // Process plane 126 | if (!deband_do_plane(d, plane)) 127 | return error; 128 | 129 | const size_t dst_stride{ (avs_get_pitch_p(dst, plane) + (d->vf->gpu->limits.align_tex_xfer_pitch) - 1) & ~((d->vf->gpu->limits.align_tex_xfer_pitch) - 1) }; 130 | pl_buf_params buf_params{}; 131 | buf_params.size = dst_stride * t_r.h; 132 | buf_params.host_mapped = true; 133 | 134 | pl_buf dst_buf{}; 135 | if (!pl_buf_recreate(d->vf->gpu, &dst_buf, &buf_params)) 136 | return error; 137 | 138 | pl_tex_transfer_params ttr{}; 139 | ttr.tex = d->vf->tex_out[0]; 140 | ttr.row_pitch = dst_stride; 141 | ttr.buf = dst_buf; 142 | 143 | // Download planes 144 | if (!pl_tex_download(d->vf->gpu, &ttr)) 145 | { 146 | pl_buf_destroy(d->vf->gpu, &dst_buf); 147 | return error; 148 | } 149 | 150 | pl_shader_obj_destroy(&d->vf->dither_state); 151 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_out[0]); 152 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_in[0]); 153 | 154 | while (pl_buf_poll(d->vf->gpu, dst_buf, 0)); 155 | memcpy(avs_get_write_ptr_p(dst, plane), dst_buf->data, dst_buf->params.size); 156 | pl_buf_destroy(d->vf->gpu, &dst_buf); 157 | } 158 | } 159 | 160 | return 0; 161 | } 162 | 163 | static AVS_VideoFrame* AVSC_CC deband_get_frame(AVS_FilterInfo* fi, int n) 164 | { 165 | deband* d{ reinterpret_cast(fi->user_data) }; 166 | 167 | AVS_VideoFrame* src{ avs_get_frame(fi->child, n) }; 168 | if (!src) 169 | return nullptr; 170 | 171 | AVS_VideoFrame* dst{ avs_new_video_frame_p(fi->env, &fi->vi, src) }; 172 | 173 | if (d->deband_process(dst, src, d, fi)) 174 | { 175 | d->msg = "libplacebo_Deband: " + d->vf->log_buffer.str(); 176 | avs_release_video_frame(src); 177 | avs_release_video_frame(dst); 178 | 179 | fi->error = d->msg.c_str(); 180 | 181 | return nullptr; 182 | } 183 | else 184 | { 185 | if (avs_num_components(&fi->vi) > 3) 186 | avs_bit_blt(fi->env, avs_get_write_ptr_p(dst, AVS_PLANAR_A), avs_get_pitch_p(dst, AVS_PLANAR_A), avs_get_read_ptr_p(src, AVS_PLANAR_A), avs_get_pitch_p(src, AVS_PLANAR_A), 187 | avs_get_row_size_p(src, AVS_PLANAR_A), avs_get_height_p(src, AVS_PLANAR_A)); 188 | 189 | avs_release_video_frame(src); 190 | 191 | return dst; 192 | } 193 | } 194 | 195 | static void AVSC_CC free_deband(AVS_FilterInfo* fi) 196 | { 197 | deband* d{ reinterpret_cast(fi->user_data) }; 198 | 199 | avs_libplacebo_uninit(d->vf); 200 | delete d; 201 | } 202 | 203 | static int AVSC_CC deband_set_cache_hints(AVS_FilterInfo* fi, int cachehints, int frame_range) 204 | { 205 | return cachehints == AVS_CACHE_GET_MTMODE ? 2 : 0; 206 | } 207 | 208 | AVS_Value AVSC_CC create_deband(AVS_ScriptEnvironment* env, AVS_Value args, void* param) 209 | { 210 | enum { Clip, Iterations, Threshold, Radius, Grainy, Grainc, Dither, Lut_size, Temporal, Planes, Device, List_device, Grain_neutral }; 211 | 212 | AVS_FilterInfo* fi; 213 | AVS_Clip* clip{ avs_new_c_filter(env, &fi, avs_array_elt(args, Clip), 1) }; 214 | 215 | deband* params{ new deband() }; 216 | 217 | AVS_Value avs_ver{ avs_version(params->msg, "libplacebo_Deband", env) }; 218 | if (avs_is_error(avs_ver)) 219 | return avs_ver; 220 | 221 | const int bits{ avs_bits_per_component(&fi->vi) }; 222 | 223 | if (!avs_is_planar(&fi->vi)) 224 | return set_error(clip, "libplacebo_Deband: clip must be in planar format.", nullptr); 225 | if (bits != 8 && bits != 16 && bits != 32) 226 | return set_error(clip, "libplacebo_Deband: bit depth must be 8, 16 or 32-bit.", nullptr); 227 | 228 | const int device{ avs_defined(avs_array_elt(args, Device)) ? avs_as_int(avs_array_elt(args, Device)) : -1 }; 229 | const int list_device{ avs_defined(avs_array_elt(args, List_device)) ? avs_as_bool(avs_array_elt(args, List_device)) : 0 }; 230 | 231 | if (list_device || device > -1) 232 | { 233 | std::vector devices{}; 234 | VkInstance inst{}; 235 | 236 | AVS_Value dev_info{ devices_info(clip, fi->env, devices, inst, params->msg, "libplacebo_Deband", device, list_device) }; 237 | if (avs_is_error(dev_info) || avs_is_clip(dev_info)) 238 | return dev_info; 239 | 240 | params->vf = avs_libplacebo_init(devices[device], params->msg); 241 | 242 | vkDestroyInstance(inst, nullptr); 243 | } 244 | else 245 | { 246 | if (device < -1) 247 | return set_error(clip, "libplacebo_Deband: device must be greater than or equal to -1.", nullptr); 248 | 249 | params->vf = avs_libplacebo_init(nullptr, params->msg); 250 | } 251 | 252 | if (params->msg.size()) 253 | { 254 | params->msg = "libplacebo_Deband: " + params->msg; 255 | return set_error(clip, params->msg.c_str(), nullptr); 256 | } 257 | 258 | if (bits == 8) 259 | { 260 | params->dither = avs_defined(avs_array_elt(args, Dither)) ? avs_as_bool(avs_array_elt(args, Dither)) : 1; 261 | 262 | if (params->dither) 263 | { 264 | params->dither_params = std::make_unique(); 265 | params->dither_params->method = static_cast(params->dither - 1); 266 | if (params->dither_params->method < 0 || params->dither_params->method > 4) 267 | return set_error(clip, "libplacebo_Deband: dither must be between 0..4", params->vf); 268 | 269 | params->dither_params->lut_size = (avs_defined(avs_array_elt(args, Lut_size))) ? avs_as_int(avs_array_elt(args, Lut_size)) : 6; 270 | if (params->dither_params->lut_size > 8) 271 | return set_error(clip, "libplacebo_Deband: lut_size must be less than or equal to 8", params->vf); 272 | 273 | params->dither_params->temporal = (avs_defined(avs_array_elt(args, Temporal))) ? avs_as_bool(avs_array_elt(args, Temporal)) : false; 274 | } 275 | } 276 | else 277 | params->dither = false; 278 | 279 | if (avs_is_rgb(&fi->vi)) 280 | { 281 | params->process[0] = 3; 282 | params->process[1] = 3; 283 | params->process[2] = 3; 284 | } 285 | else 286 | { 287 | params->process[0] = 3; 288 | params->process[1] = 2; 289 | params->process[2] = 2; 290 | 291 | const int num_planes{ (avs_defined(avs_array_elt(args, Planes))) ? avs_array_size(avs_array_elt(args, Planes)) : 0 }; 292 | if (num_planes > avs_num_components(&fi->vi)) 293 | return set_error(clip, "libplacebo_Deband: plane index out of range.", params->vf); 294 | 295 | for (int i{ 0 }; i < num_planes; ++i) 296 | { 297 | const int plane_v{ avs_as_int(*(avs_as_array(avs_array_elt(args, Planes)) + i)) }; 298 | if (plane_v < 1 || plane_v > 3) 299 | return set_error(clip, "libplacebo_Deband: plane must be between 1..3.", params->vf); 300 | 301 | params->process[i] = avs_as_int(*(avs_as_array(avs_array_elt(args, Planes)) + i)); 302 | } 303 | } 304 | 305 | params->deband_params = std::make_unique(); 306 | params->deband_params->iterations = (avs_defined(avs_array_elt(args, Iterations))) ? avs_as_int(avs_array_elt(args, Iterations)) : 1; 307 | if (params->deband_params->iterations < 0) 308 | return set_error(clip, "libplacebo_Deband: iterations must be greater than or equal to 0.", params->vf); 309 | 310 | params->deband_params->threshold = (avs_defined(avs_array_elt(args, Threshold))) ? avs_as_float(avs_array_elt(args, Threshold)) : 4.0f; 311 | if (params->deband_params->threshold < 0.0f) 312 | return set_error(clip, "libplacebo_Deband: threshold must be greater than or equal to 0.0", params->vf); 313 | 314 | params->deband_params->radius = (avs_defined(avs_array_elt(args, Radius))) ? avs_as_float(avs_array_elt(args, Radius)) : 16.0f; 315 | if (params->deband_params->radius < 0.0f) 316 | return set_error(clip, "libplacebo_Deband: radius must be greater than or equal to 0.0", params->vf); 317 | 318 | if (avs_defined(avs_array_elt(args, Grain_neutral))) 319 | { 320 | const int grain_neutral_num{ avs_array_size(avs_array_elt(args, Grain_neutral)) }; 321 | if (grain_neutral_num > avs_num_components(&fi->vi)) 322 | return set_error(clip, "libplacebo_Deband: grain_neutral index out of range.", params->vf); 323 | 324 | for (int i{ 0 }; i < grain_neutral_num; ++i) 325 | { 326 | params->deband_params->grain_neutral[i] = avs_as_float(*(avs_as_array(avs_array_elt(args, Grain_neutral)) + i)); 327 | if (params->deband_params->grain_neutral[i] < 0.0f) 328 | return set_error(clip, "libplacebo_Deband: grain_neutral must be greater than or equal to 0.0", params->vf); 329 | } 330 | } 331 | 332 | params->deband_params->grain = (avs_defined(avs_array_elt(args, Grainy))) ? avs_as_float(avs_array_elt(args, Grainy)) : 6.0f; 333 | if (params->deband_params->grain < 0.0f) 334 | return set_error(clip, "libplacebo_Deband: grainY must be greater than or equal to 0.0", params->vf); 335 | 336 | const float grainC{ static_cast((avs_defined(avs_array_elt(args, Grainc))) ? avs_as_float(avs_array_elt(args, Grainc)) : params->deband_params->grain) }; 337 | if (grainC < 0.0f) 338 | return set_error(clip, "libplacebo_Deband: grainC must be greater than or equal to 0.0", params->vf); 339 | 340 | if (params->deband_params->grain != grainC) 341 | { 342 | params->deband_params1 = std::make_unique(); 343 | memcpy(params->deband_params1.get(), params->deband_params.get(), sizeof(pl_deband_params)); 344 | params->deband_params1->grain = grainC; 345 | } 346 | 347 | params->frame_index = 0; 348 | 349 | switch (bits) 350 | { 351 | case 8: params->deband_process = deband_filter; break; 352 | case 16: params->deband_process = deband_filter; break; 353 | default: params->deband_process = deband_filter; break; 354 | } 355 | 356 | AVS_Value v{ avs_new_value_clip(clip) }; 357 | 358 | fi->user_data = reinterpret_cast(params); 359 | fi->get_frame = deband_get_frame; 360 | fi->set_cache_hints = deband_set_cache_hints; 361 | fi->free_filter = free_deband; 362 | 363 | avs_release_clip(clip); 364 | 365 | return v; 366 | } 367 | -------------------------------------------------------------------------------- /src/shader.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #ifdef _WIN32 6 | #include 7 | #endif 8 | 9 | #include "avs_libplacebo.h" 10 | 11 | static std::mutex mtx; 12 | 13 | struct shader 14 | { 15 | std::unique_ptr vf; 16 | const pl_hook* shader; 17 | enum pl_color_system matrix; 18 | enum pl_color_levels range; 19 | enum pl_chroma_location chromaLocation; 20 | std::unique_ptr sample_params; 21 | std::unique_ptr sigmoid_params; 22 | enum pl_color_transfer trc; 23 | int linear; 24 | int subw; 25 | int subh; 26 | std::string msg; 27 | }; 28 | 29 | static bool shader_do_plane(const shader* d, const pl_plane* planes) noexcept 30 | { 31 | pl_color_repr crpr{}; 32 | crpr.bits.bit_shift = 0; 33 | crpr.bits.color_depth = 16; 34 | crpr.bits.sample_depth = 16; 35 | crpr.sys = d->matrix; 36 | crpr.levels = d->range; 37 | 38 | pl_color_space csp{}; 39 | csp.transfer = d->trc; 40 | 41 | pl_frame img{}; 42 | img.num_planes = 3; 43 | img.repr = crpr; 44 | img.planes[0] = planes[0]; 45 | img.planes[1] = planes[1]; 46 | img.planes[2] = planes[2]; 47 | img.color = csp; 48 | 49 | if (d->subw || d->subh) 50 | pl_frame_set_chroma_location(&img, d->chromaLocation); 51 | 52 | pl_frame out{}; 53 | out.num_planes = 3; 54 | out.repr = crpr; 55 | out.color = csp; 56 | 57 | for (int i{ 0 }; i < 3; ++i) 58 | { 59 | out.planes[i].texture = d->vf->tex_out[i]; 60 | out.planes[i].components = 1; 61 | out.planes[i].component_mapping[0] = i; 62 | } 63 | 64 | pl_render_params renderParams{}; 65 | renderParams.hooks = &d->shader; 66 | renderParams.num_hooks = 1; 67 | renderParams.sigmoid_params = d->sigmoid_params.get(); 68 | renderParams.disable_linear_scaling = !d->linear; 69 | renderParams.upscaler = &d->sample_params->filter; 70 | renderParams.downscaler = &d->sample_params->filter; 71 | renderParams.antiringing_strength = d->sample_params->antiring; 72 | 73 | return pl_render_image(d->vf->rr, &img, &out, &renderParams); 74 | } 75 | 76 | static int shader_filter(AVS_VideoFrame* dst, AVS_VideoFrame* src, shader* d, const AVS_FilterInfo* fi) noexcept 77 | { 78 | const int error{ [&]() 79 | { 80 | for (int i{ 0 }; i < 3; ++i) 81 | { 82 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_out[i]); 83 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_in[i]); 84 | } 85 | 86 | return -1; 87 | }() }; 88 | 89 | const pl_fmt fmt{ pl_find_named_fmt(d->vf->gpu, "r16") }; 90 | if (!fmt) 91 | return error; 92 | 93 | pl_tex_params t_r{}; 94 | t_r.w = fi->vi.width; 95 | t_r.h = fi->vi.height; 96 | t_r.format = fmt; 97 | t_r.renderable = true; 98 | t_r.host_readable = true; 99 | 100 | pl_plane pl_planes[3]{}; 101 | constexpr int planes[3]{ AVS_PLANAR_Y, AVS_PLANAR_U, AVS_PLANAR_V }; 102 | 103 | for (int i{ 0 }; i < 3; ++i) 104 | { 105 | const int plane{ planes[i] }; 106 | 107 | pl_plane_data pl{}; 108 | pl.type = PL_FMT_UNORM; 109 | pl.pixel_stride = 2; 110 | pl.component_size[0] = 16; 111 | pl.width = avs_get_row_size_p(src, plane) / avs_component_size(&fi->vi); 112 | pl.height = avs_get_height_p(src, plane); 113 | pl.row_stride = avs_get_pitch_p(src, plane); 114 | pl.pixels = avs_get_read_ptr_p(src, plane); 115 | pl.component_map[0] = i; 116 | 117 | // Upload planes 118 | if (!pl_upload_plane(d->vf->gpu, &pl_planes[i], &d->vf->tex_in[i], &pl)) 119 | return error; 120 | 121 | if (!pl_tex_recreate(d->vf->gpu, &d->vf->tex_out[i], &t_r)) 122 | return error; 123 | } 124 | 125 | // Process plane 126 | if (!shader_do_plane(d, pl_planes)) 127 | return error; 128 | 129 | const int dst_stride = (avs_get_pitch(dst) + (d->vf->gpu->limits.align_tex_xfer_pitch) - 1) & ~((d->vf->gpu->limits.align_tex_xfer_pitch) - 1); 130 | pl_buf_params buf_params{}; 131 | buf_params.size = dst_stride * fi->vi.height; 132 | buf_params.host_mapped = true; 133 | 134 | pl_buf dst_buf{}; 135 | if (!pl_buf_recreate(d->vf->gpu, &dst_buf, &buf_params)) 136 | return error; 137 | 138 | // Download planes 139 | for (int i{ 0 }; i < 3; ++i) 140 | { 141 | pl_tex_transfer_params ttr1{}; 142 | ttr1.row_pitch = dst_stride; 143 | ttr1.buf = dst_buf; 144 | ttr1.tex = d->vf->tex_out[i]; 145 | 146 | if (!pl_tex_download(d->vf->gpu, &ttr1)) 147 | { 148 | pl_buf_destroy(d->vf->gpu, &dst_buf); 149 | return error; 150 | } 151 | 152 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_out[i]); 153 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_in[i]); 154 | 155 | while (pl_buf_poll(d->vf->gpu, dst_buf, 0)); 156 | memcpy(avs_get_write_ptr_p(dst, planes[i]), dst_buf->data, dst_buf->params.size); 157 | } 158 | 159 | pl_buf_destroy(d->vf->gpu, &dst_buf); 160 | 161 | return 0; 162 | } 163 | 164 | static AVS_VideoFrame* AVSC_CC shader_get_frame(AVS_FilterInfo* fi, int n) 165 | { 166 | shader* d{ reinterpret_cast(fi->user_data) }; 167 | 168 | AVS_VideoFrame* src{ avs_get_frame(fi->child, n) }; 169 | if (!src) 170 | return nullptr; 171 | 172 | AVS_VideoFrame* dst{ avs_new_video_frame_p(fi->env, &fi->vi, src) }; 173 | 174 | if (d->range == PL_COLOR_LEVELS_UNKNOWN) 175 | { 176 | const AVS_Map* props{ avs_get_frame_props_ro(fi->env, src) }; 177 | 178 | int err{ 0 }; 179 | const int64_t r{ avs_prop_get_int(fi->env, props, "_ColorRange", 0, &err) }; 180 | if (err) 181 | d->range = PL_COLOR_LEVELS_LIMITED; 182 | else 183 | d->range = (r) ? PL_COLOR_LEVELS_LIMITED : PL_COLOR_LEVELS_FULL; 184 | } 185 | 186 | if (std::lock_guard lck(mtx); shader_filter(dst, src, d, fi)) 187 | { 188 | d->msg = "libplacebo_Shader: " + d->vf->log_buffer.str(); 189 | avs_release_video_frame(src); 190 | avs_release_video_frame(dst); 191 | 192 | fi->error = d->msg.c_str(); 193 | 194 | return nullptr; 195 | } 196 | else 197 | { 198 | avs_release_video_frame(src); 199 | 200 | return dst; 201 | } 202 | } 203 | 204 | static void AVSC_CC free_shader(AVS_FilterInfo* fi) 205 | { 206 | shader* d{ reinterpret_cast(fi->user_data) }; 207 | 208 | pl_mpv_user_shader_destroy(&d->shader); 209 | avs_libplacebo_uninit(d->vf); 210 | delete d; 211 | } 212 | 213 | static int AVSC_CC shader_set_cache_hints(AVS_FilterInfo* fi, int cachehints, int frame_range) 214 | { 215 | return cachehints == AVS_CACHE_GET_MTMODE ? 2 : 0; 216 | } 217 | 218 | AVS_Value AVSC_CC create_shader(AVS_ScriptEnvironment* env, AVS_Value args, void* param) 219 | { 220 | enum { Clip, Shader, Width, Height, Chroma_loc, Matrix, Trc, Filter, Radius, Clamp, Taper, Blur, Param1, Param2, Antiring, Sigmoidize, Linearize, Sigmoid_center, Sigmoid_slope, Shader_param, Device, List_device }; 221 | 222 | AVS_FilterInfo* fi; 223 | AVS_Clip* clip{ avs_new_c_filter(env, &fi, avs_array_elt(args, Clip), 1) }; 224 | 225 | shader* params{ new shader() }; 226 | 227 | AVS_Value avs_ver{ avs_version(params->msg, "libplacebo_Shader", env) }; 228 | if (avs_is_error(avs_ver)) 229 | return avs_ver; 230 | 231 | if (!avs_is_planar(&fi->vi)) 232 | return set_error(clip, "libplacebo_Shader: clip must be in planar format.", nullptr); 233 | if (avs_bits_per_component(&fi->vi) != 16) 234 | return set_error(clip, "libplacebo_Shader: bit depth must be 16-bit.", nullptr); 235 | if (avs_is_rgb(&fi->vi)) 236 | return set_error(clip, "libplacebo_Shader: only YUV formats are supported.", nullptr); 237 | 238 | const int device{ avs_defined(avs_array_elt(args, Device)) ? avs_as_int(avs_array_elt(args, Device)) : -1 }; 239 | const int list_device{ avs_defined(avs_array_elt(args, List_device)) ? avs_as_bool(avs_array_elt(args, List_device)) : 0 }; 240 | 241 | if (list_device || device > -1) 242 | { 243 | std::vector devices{}; 244 | VkInstance inst{}; 245 | 246 | AVS_Value dev_info{ devices_info(clip, fi->env, devices, inst, params->msg, "libplacebo_Shader", device, list_device) }; 247 | if (avs_is_error(dev_info) || avs_is_clip(dev_info)) 248 | return dev_info; 249 | 250 | params->vf = avs_libplacebo_init(devices[device], params->msg); 251 | 252 | vkDestroyInstance(inst, nullptr); 253 | } 254 | else 255 | { 256 | if (device < -1) 257 | return set_error(clip, "libplacebo_Shader: device must be greater than or equal to -1.", nullptr); 258 | 259 | params->vf = avs_libplacebo_init(nullptr, params->msg); 260 | } 261 | 262 | if (params->msg.size()) 263 | { 264 | params->msg = "libplacebo_Shader: " + params->msg; 265 | return set_error(clip, params->msg.c_str(), nullptr); 266 | } 267 | 268 | const char* shader_path{ avs_as_string(avs_array_elt(args, Shader)) }; 269 | FILE* shader_file{ nullptr }; 270 | 271 | #ifdef _WIN32 272 | const int required_size{ MultiByteToWideChar(CP_UTF8, 0, shader_path, -1, nullptr, 0) }; 273 | std::wstring wbuffer(required_size, 0); 274 | MultiByteToWideChar(CP_UTF8, 0, shader_path, -1, wbuffer.data(), required_size); 275 | shader_file = _wfopen(wbuffer.c_str(), L"rb"); 276 | if (!shader_file) 277 | { 278 | const int req_size{ MultiByteToWideChar(CP_ACP, 0, shader_path, -1, nullptr, 0) }; 279 | wbuffer.resize(req_size); 280 | MultiByteToWideChar(CP_ACP, 0, shader_path, -1, wbuffer.data(), req_size); 281 | shader_file = _wfopen(wbuffer.c_str(), L"rb"); 282 | } 283 | #else 284 | shader_file = std::fopen(shader_path, "rb"); 285 | #endif 286 | if (!shader_file) 287 | { 288 | params->msg = "libplacebo_Shader: error opening file " + std::string(shader_path) + " (" + std::strerror(errno) + ")"; 289 | return set_error(clip, params->msg.c_str(), params->vf); 290 | } 291 | 292 | if (std::fseek(shader_file, 0, SEEK_END)) 293 | { 294 | std::fclose(shader_file); 295 | params->msg = "libplacebo_Shader: error seeking to the end of file " + std::string(shader_path) + " (" + std::strerror(errno) + ")"; 296 | return set_error(clip, params->msg.c_str(), params->vf); 297 | } 298 | 299 | const long shader_size{ std::ftell(shader_file) }; 300 | 301 | if (shader_size == -1) 302 | { 303 | std::fclose(shader_file); 304 | params->msg = "libplacebo_Shader: error determining the size of file " + std::string(shader_path) + " (" + std::strerror(errno) + ")"; 305 | return set_error(clip, params->msg.c_str(), params->vf); 306 | } 307 | 308 | std::rewind(shader_file); 309 | 310 | std::string bdata(shader_size, ' '); 311 | std::fread(bdata.data(), 1, shader_size, shader_file); 312 | bdata[shader_size] = '\0'; 313 | 314 | std::fclose(shader_file); 315 | 316 | if (avs_defined(avs_array_elt(args, Shader_param))) 317 | { 318 | std::string shader_p{ avs_as_string(avs_array_elt(args, Shader_param)) }; 319 | 320 | int num_spaces{ 0 }; 321 | int num_equals{ -1 }; 322 | for (auto& string : shader_p) 323 | { 324 | if (string == ' ') 325 | ++num_spaces; 326 | if (string == '=') 327 | ++num_equals; 328 | } 329 | if (num_spaces != num_equals) 330 | return set_error(clip, "libplacebo_Shader: failed parsing shader_param (wrong format).", params->vf); 331 | 332 | std::string reg_parse{ "(\\w+)=([^ >]+)" }; 333 | for (int i{ 0 }; i < num_spaces; ++i) 334 | reg_parse += "(?: (\\w+)=([^ >]+))"; 335 | 336 | std::regex reg(reg_parse); 337 | std::smatch match; 338 | if (!std::regex_match(shader_p.cbegin(), shader_p.cend(), match, reg)) 339 | return set_error(clip, "libplacebo_Shader: regex failed parsing shader_param.", params->vf); 340 | 341 | for (int i = 1; match[i + 1].matched; i += 2) 342 | bdata = std::regex_replace(bdata, std::regex(std::string("(#define\\s") + match[i].str() + std::string("\\s+)(.+?)(?=\\/\\/|\\s)")), "$01" + match[i + 1].str()); 343 | } 344 | 345 | params->shader = pl_mpv_user_shader_parse(params->vf->gpu, bdata.c_str(), bdata.size()); 346 | if (!params->shader) 347 | return set_error(clip, "libplacebo_Shader: failed parsing shader!", params->vf); 348 | 349 | params->range = PL_COLOR_LEVELS_UNKNOWN; 350 | params->matrix = static_cast((avs_defined(avs_array_elt(args, Matrix))) ? avs_as_int(avs_array_elt(args, Matrix)) : 2); 351 | 352 | if (avs_defined(avs_array_elt(args, Width))) 353 | fi->vi.width = avs_as_int(avs_array_elt(args, Width)); 354 | if (avs_defined(avs_array_elt(args, Height))) 355 | fi->vi.height = avs_as_int(avs_array_elt(args, Height)); 356 | 357 | params->chromaLocation = static_cast((avs_defined(avs_array_elt(args, Chroma_loc))) ? avs_as_int(avs_array_elt(args, Chroma_loc)) : 1); 358 | params->linear = (avs_defined(avs_array_elt(args, Linearize))) ? avs_as_bool(avs_array_elt(args, Linearize)) : 1; 359 | params->trc = static_cast((avs_defined(avs_array_elt(args, Trc))) ? avs_as_int(avs_array_elt(args, Trc)) : 1); 360 | const int sigmoid{ (avs_defined(avs_array_elt(args, Sigmoidize))) ? avs_as_bool(avs_array_elt(args, Sigmoidize)) : 1 }; 361 | 362 | if (sigmoid) 363 | { 364 | params->sigmoid_params = std::make_unique(); 365 | 366 | params->sigmoid_params->center = (avs_defined(avs_array_elt(args, Sigmoid_center))) ? avs_as_float(avs_array_elt(args, Sigmoid_center)) : 0.75f; 367 | if (params->sigmoid_params->center < 0.0f || params->sigmoid_params->center > 1.0f) 368 | { 369 | pl_mpv_user_shader_destroy(¶ms->shader); 370 | return set_error(clip, "libplacebo_Shader: sigmoid_center must be between 0.0 and 1.0.", params->vf); 371 | } 372 | 373 | params->sigmoid_params->slope = (avs_defined(avs_array_elt(args, Sigmoid_slope))) ? avs_as_float(avs_array_elt(args, Sigmoid_slope)) : 6.5f; 374 | if (params->sigmoid_params->slope < 1.0f || params->sigmoid_params->slope > 20.0f) 375 | { 376 | pl_mpv_user_shader_destroy(¶ms->shader); 377 | return set_error(clip, "libplacebo_Shader: sigmoid_slope must be between 1.0 and 20.0.", params->vf); 378 | } 379 | } 380 | 381 | params->sample_params = std::make_unique(); 382 | 383 | params->sample_params->antiring = (avs_defined(avs_array_elt(args, Antiring))) ? avs_as_float(avs_array_elt(args, Antiring)) : 0.0f; 384 | if (params->sample_params->antiring < 0.0f || params->sample_params->antiring > 1.0f) 385 | { 386 | pl_mpv_user_shader_destroy(¶ms->shader); 387 | return set_error(clip, "libplacebo_Shader: antiring must be between 0.0 and 1.0.", params->vf); 388 | } 389 | 390 | const pl_filter_config* filter_config{ pl_find_filter_config((avs_defined(avs_array_elt(args, Filter))) ? avs_as_string(avs_array_elt(args, Filter)) : "ewa_lanczos", PL_FILTER_UPSCALING) }; 391 | if (!filter_config) 392 | { 393 | pl_mpv_user_shader_destroy(¶ms->shader); 394 | return set_error(clip, "libplacebo_Shader: not a valid filter.", params->vf); 395 | } 396 | 397 | params->sample_params->filter = *filter_config; 398 | params->sample_params->filter.clamp = (avs_defined(avs_array_elt(args, Clamp))) ? avs_as_float(avs_array_elt(args, Clamp)) : 0.0f; 399 | if (params->sample_params->filter.clamp < 0.0f || params->sample_params->filter.clamp > 1.0f) 400 | { 401 | pl_mpv_user_shader_destroy(¶ms->shader); 402 | return set_error(clip, "libplacebo_Shader: clamp must be between 0.0 and 1.0.", params->vf); 403 | } 404 | 405 | params->sample_params->filter.blur = (avs_defined(avs_array_elt(args, Blur))) ? avs_as_float(avs_array_elt(args, Blur)) : 0.0f; 406 | if (params->sample_params->filter.blur < 0.0f || params->sample_params->filter.blur > 100.0f) 407 | { 408 | pl_mpv_user_shader_destroy(¶ms->shader); 409 | return set_error(clip, "libplacebo_Shader: blur must be between 0.0 and 100.0.", params->vf); 410 | } 411 | 412 | params->sample_params->filter.taper = (avs_defined(avs_array_elt(args, Taper))) ? avs_as_float(avs_array_elt(args, Taper)) : 0.0f; 413 | if (params->sample_params->filter.taper < 0.0f || params->sample_params->filter.taper > 1.0f) 414 | { 415 | pl_mpv_user_shader_destroy(¶ms->shader); 416 | return set_error(clip, "libplacebo_Shader: taper must be between 0.0 and 1.0.", params->vf); 417 | } 418 | 419 | if (avs_defined(avs_array_elt(args, Radius))) 420 | { 421 | params->sample_params->filter.radius = avs_as_float(avs_array_elt(args, Radius)); 422 | if (params->sample_params->filter.radius < 0.0f || params->sample_params->filter.radius > 16.0f) 423 | { 424 | pl_mpv_user_shader_destroy(¶ms->shader); 425 | return set_error(clip, "libplacebo_Shader: radius must be between 0.0 and 16.0.", params->vf); 426 | } 427 | } 428 | 429 | if (avs_defined(avs_array_elt(args, Param1))) 430 | params->sample_params->filter.params[0] = avs_as_float(avs_array_elt(args, Param1)); 431 | if (avs_defined(avs_array_elt(args, Param2))) 432 | params->sample_params->filter.params[1] = avs_as_float(avs_array_elt(args, Param2)); 433 | 434 | params->subw = avs_get_plane_width_subsampling(&fi->vi, AVS_PLANAR_U); 435 | params->subh = avs_get_plane_height_subsampling(&fi->vi, AVS_PLANAR_U); 436 | 437 | fi->vi.pixel_type = AVS_CS_YUV444P16; 438 | 439 | AVS_Value v{ avs_new_value_clip(clip) }; 440 | 441 | fi->user_data = reinterpret_cast(params); 442 | fi->get_frame = shader_get_frame; 443 | fi->set_cache_hints = shader_set_cache_hints; 444 | fi->free_filter = free_shader; 445 | 446 | avs_release_clip(clip); 447 | 448 | return v; 449 | } 450 | -------------------------------------------------------------------------------- /src/resample.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "avs_libplacebo.h" 4 | 5 | static std::mutex mtx; 6 | 7 | struct resample 8 | { 9 | std::unique_ptr vf; 10 | float src_x; 11 | float src_y; 12 | std::unique_ptr sample_params; 13 | std::unique_ptr sigmoid_params; 14 | pl_color_transfer trc; 15 | int linear; 16 | std::string msg; 17 | int subw; 18 | int subh; 19 | float shift_w; 20 | float shift_h; 21 | int cplace; 22 | float src_width; 23 | float src_height; 24 | 25 | int (*resample_process)(AVS_VideoFrame* dst, AVS_VideoFrame* src, resample* d, const AVS_FilterInfo* fi) noexcept; 26 | }; 27 | 28 | static int resample_do_plane(const resample* d, pl_shader_obj* lut, const int w, const int h, const float sx, const float sy, const int planeIdx) noexcept 29 | { 30 | pl_shader sh{ pl_dispatch_begin(d->vf->dp) }; 31 | pl_tex sample_fbo{}; 32 | pl_tex sep_fbo{}; 33 | 34 | pl_sample_filter_params* sample_params{ d->sample_params.get() }; 35 | sample_params->lut = lut; 36 | 37 | pl_color_space cs{}; 38 | cs.transfer = d->trc; 39 | 40 | pl_sample_src src{}; 41 | src.tex = d->vf->tex_in[0]; 42 | 43 | // 44 | // linearization and sigmoidization 45 | // 46 | 47 | pl_shader ish{ pl_dispatch_begin(d->vf->dp) }; 48 | pl_tex_params tp{}; 49 | tp.w = src.tex->params.w; 50 | tp.h = src.tex->params.h; 51 | tp.renderable = true; 52 | tp.sampleable = true; 53 | tp.format = src.tex->params.format; 54 | 55 | if (!pl_tex_recreate(d->vf->gpu, &sample_fbo, &tp)) 56 | return -1; 57 | 58 | pl_shader_sample_direct(ish, &src); 59 | 60 | if (d->linear) 61 | pl_shader_linearize(ish, &cs); 62 | 63 | if (d->sigmoid_params.get()) 64 | pl_shader_sigmoidize(ish, d->sigmoid_params.get()); 65 | 66 | pl_dispatch_params dp{}; 67 | dp.target = sample_fbo; 68 | dp.shader = &ish; 69 | 70 | if (!pl_dispatch_finish(d->vf->dp, &dp)) 71 | return -1; 72 | 73 | // 74 | // sampling 75 | // 76 | 77 | const float src_w{ [&]() 78 | { 79 | if (d->src_width > -1.0f) 80 | return (planeIdx == AVS_PLANAR_U || planeIdx == AVS_PLANAR_V) ? (d->src_width / d->subw) : d->src_width; 81 | else 82 | return static_cast(d->vf->tex_in[0]->params.w); 83 | }() }; 84 | 85 | const float src_h{ [&]() 86 | { 87 | if (d->src_height > -1.0f) 88 | return (planeIdx == AVS_PLANAR_U || planeIdx == AVS_PLANAR_V) ? (d->src_height / d->subh) : d->src_height; 89 | else 90 | return static_cast(d->vf->tex_in[0]->params.h); 91 | }() }; 92 | 93 | pl_rect2df rect{ sx, sy, src_w + sx, src_h + sy, }; 94 | 95 | src.tex = sample_fbo; 96 | src.rect = rect; 97 | src.new_h = h; 98 | src.new_w = w; 99 | 100 | if (d->sample_params->filter.polar) 101 | { 102 | if (!pl_shader_sample_polar(sh, &src, sample_params)) 103 | return -1; 104 | } 105 | else 106 | { 107 | pl_sample_src src1 = src; 108 | src.new_w = src.tex->params.w; 109 | src.rect.x0 = 0; 110 | src.rect.x1 = src.new_w; 111 | src1.rect.y0 = 0; 112 | src1.rect.y1 = src.new_h; 113 | 114 | pl_shader tsh{ pl_dispatch_begin(d->vf->dp) }; 115 | 116 | if (!pl_shader_sample_ortho2(tsh, &src, sample_params)) 117 | { 118 | pl_dispatch_abort(d->vf->dp, &tsh); 119 | return -1; 120 | } 121 | 122 | tp.w = src.new_w; 123 | tp.h = src.new_h; 124 | 125 | if (!pl_tex_recreate(d->vf->gpu, &sep_fbo, &tp)) 126 | return -1; 127 | 128 | dp.target = sep_fbo; 129 | dp.shader = &tsh; 130 | 131 | if (!pl_dispatch_finish(d->vf->dp, &dp)) 132 | return -1; 133 | 134 | src1.tex = sep_fbo; 135 | src1.scale = 1.0f; 136 | 137 | if (!pl_shader_sample_ortho2(sh, &src1, sample_params)) 138 | return -1; 139 | } 140 | 141 | if (d->sigmoid_params.get()) 142 | pl_shader_unsigmoidize(sh, d->sigmoid_params.get()); 143 | 144 | if (d->linear) 145 | pl_shader_delinearize(sh, &cs); 146 | 147 | dp.target = d->vf->tex_out[0]; 148 | dp.shader = &sh; 149 | 150 | if (!pl_dispatch_finish(d->vf->dp, &dp)) 151 | return -1; 152 | 153 | pl_tex_destroy(d->vf->gpu, &sep_fbo); 154 | pl_tex_destroy(d->vf->gpu, &sample_fbo); 155 | 156 | return 0; 157 | } 158 | 159 | template 160 | static int resample_filter(AVS_VideoFrame* dst, AVS_VideoFrame* src, resample* d, const AVS_FilterInfo* fi) noexcept 161 | { 162 | const auto error{ [&](pl_shader_obj lut) 163 | { 164 | pl_shader_obj_destroy(&lut); 165 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_out[0]); 166 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_in[0]); 167 | 168 | return -1; 169 | } }; 170 | 171 | const pl_fmt fmt{ [&]() 172 | { 173 | if constexpr (std::is_same_v) 174 | return pl_find_named_fmt(d->vf->gpu, "r8"); 175 | else if constexpr (std::is_same_v) 176 | return pl_find_named_fmt(d->vf->gpu, "r16"); 177 | else 178 | return pl_find_named_fmt(d->vf->gpu, "r32f"); 179 | }() }; 180 | if (!fmt) 181 | return error(nullptr); 182 | 183 | constexpr int planes_y[4]{ AVS_PLANAR_Y, AVS_PLANAR_U, AVS_PLANAR_V, AVS_PLANAR_A }; 184 | constexpr int planes_r[4]{ AVS_PLANAR_R, AVS_PLANAR_G, AVS_PLANAR_B, AVS_PLANAR_A }; 185 | const int* planes{ (avs_is_rgb(&fi->vi)) ? planes_r : planes_y }; 186 | const int num_planes{ avs_num_components(&fi->vi) }; 187 | 188 | for (int i{ 0 }; i < num_planes; ++i) 189 | { 190 | const int plane{ planes[i] }; 191 | 192 | const size_t dst_width{ avs_get_row_size_p(dst, plane) / sizeof(T) }; 193 | const int dst_height = avs_get_height_p(dst, plane); 194 | 195 | pl_plane_data pl{}; 196 | pl.pixel_stride = sizeof(T); 197 | if constexpr (std::is_same_v) 198 | { 199 | pl.type = PL_FMT_UNORM; 200 | pl.component_size[0] = 8; 201 | } 202 | else if constexpr (std::is_same_v) 203 | { 204 | pl.type = PL_FMT_UNORM; 205 | pl.component_size[0] = 16; 206 | } 207 | else 208 | { 209 | pl.type = PL_FMT_FLOAT; 210 | pl.component_size[0] = 32; 211 | } 212 | pl.width = avs_get_row_size_p(src, plane) / sizeof(T); 213 | pl.height = avs_get_height_p(src, plane); 214 | pl.row_stride = avs_get_pitch_p(src, plane); 215 | pl.pixels = avs_get_read_ptr_p(src, plane); 216 | 217 | std::lock_guard lck(mtx); 218 | 219 | pl_shader_obj lut{}; 220 | 221 | // Upload planes 222 | if (!pl_upload_plane(d->vf->gpu, nullptr, &d->vf->tex_in[0], &pl)) 223 | return error(lut); 224 | 225 | pl_tex_params t_r{}; 226 | t_r.format = fmt; 227 | t_r.w = dst_width; 228 | t_r.h = dst_height; 229 | t_r.sampleable = false; 230 | t_r.host_writable = false; 231 | t_r.renderable = true; 232 | t_r.host_readable = true; 233 | t_r.storable = true; 234 | 235 | if (!pl_tex_recreate(d->vf->gpu, &d->vf->tex_out[0], &t_r)) 236 | return error(lut); 237 | 238 | // Process plane 239 | if (resample_do_plane(d, &lut, dst_width, dst_height, (i > 0) ? (d->shift_w + d->src_x / d->subw) : d->src_x, 240 | (i > 0) ? (d->shift_h + d->src_y / d->subh) : d->src_y, plane)) 241 | return error(lut); 242 | 243 | const size_t dst_stride{ (avs_get_pitch_p(dst, plane) + (d->vf->gpu->limits.align_tex_xfer_pitch) - 1) & ~((d->vf->gpu->limits.align_tex_xfer_pitch) - 1) }; 244 | pl_buf_params buf_params{}; 245 | buf_params.size = dst_stride * t_r.h; 246 | buf_params.host_mapped = true; 247 | 248 | pl_buf dst_buf{}; 249 | if (!pl_buf_recreate(d->vf->gpu, &dst_buf, &buf_params)) 250 | return error(lut); 251 | 252 | pl_tex_transfer_params ttr{}; 253 | ttr.tex = d->vf->tex_out[0]; 254 | ttr.row_pitch = dst_stride; 255 | ttr.buf = dst_buf; 256 | 257 | // Download planes 258 | if (!pl_tex_download(d->vf->gpu, &ttr)) 259 | { 260 | pl_buf_destroy(d->vf->gpu, &dst_buf); 261 | return error(lut); 262 | } 263 | 264 | pl_shader_obj_destroy(&lut); 265 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_out[0]); 266 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_in[0]); 267 | 268 | while (pl_buf_poll(d->vf->gpu, dst_buf, 0)); 269 | memcpy(avs_get_write_ptr_p(dst, plane), dst_buf->data, dst_buf->params.size); 270 | pl_buf_destroy(d->vf->gpu, &dst_buf); 271 | } 272 | 273 | return 0; 274 | } 275 | 276 | static AVS_VideoFrame* AVSC_CC resample_get_frame(AVS_FilterInfo* fi, int n) 277 | { 278 | resample* d{ reinterpret_cast(fi->user_data) }; 279 | 280 | AVS_VideoFrame* src{ avs_get_frame(fi->child, n) }; 281 | if (!src) 282 | return nullptr; 283 | 284 | AVS_VideoFrame* dst{ avs_new_video_frame_p(fi->env, &fi->vi, src) }; 285 | 286 | if (d->resample_process(dst, src, d, fi)) 287 | { 288 | d->msg = "libplacebo_Resample: " + d->vf->log_buffer.str(); 289 | avs_release_video_frame(src); 290 | avs_release_video_frame(dst); 291 | 292 | fi->error = d->msg.c_str(); 293 | 294 | return nullptr; 295 | } 296 | else 297 | { 298 | avs_prop_set_int(fi->env, avs_get_frame_props_rw(fi->env, dst), "_ChromaLocation", d->cplace, 0); 299 | 300 | avs_release_video_frame(src); 301 | 302 | return dst; 303 | } 304 | } 305 | 306 | static void AVSC_CC free_resample(AVS_FilterInfo* fi) 307 | { 308 | resample* d{ reinterpret_cast(fi->user_data) }; 309 | 310 | avs_libplacebo_uninit(d->vf); 311 | delete d; 312 | } 313 | 314 | static int AVSC_CC resample_set_cache_hints(AVS_FilterInfo* fi, int cachehints, int frame_range) 315 | { 316 | return cachehints == AVS_CACHE_GET_MTMODE ? 2 : 0; 317 | } 318 | 319 | AVS_Value AVSC_CC create_resample(AVS_ScriptEnvironment* env, AVS_Value args, void* param) 320 | { 321 | enum { Clip, Width, Height, Filter, Radius, Clamp, Taper, Blur, Param1, Param2, Sx, Sy, Antiring, Sigmoidize, Linearize, Sigmoid_center, Sigmoid_slope, Trc, Cplace, Device, List_device, Src_width, Src_height }; 322 | 323 | AVS_FilterInfo* fi; 324 | AVS_Clip* clip{ avs_new_c_filter(env, &fi, avs_array_elt(args, Clip), 1) }; 325 | 326 | resample* params{ new resample() }; 327 | 328 | AVS_Value avs_ver{ avs_version(params->msg, "libplacebo_Resample", env) }; 329 | if (avs_is_error(avs_ver)) 330 | return avs_ver; 331 | 332 | const int bits{ avs_bits_per_component(&fi->vi) }; 333 | 334 | if (!avs_is_planar(&fi->vi)) 335 | return set_error(clip, "libplacebo_Resample: clip must be in planar format.", nullptr); 336 | if (bits != 8 && bits != 16 && bits != 32) 337 | return set_error(clip, "libplacebo_Resample: bit depth must be 8, 16 or 32-bit.", nullptr); 338 | 339 | const int w{ fi->vi.width }; 340 | const int h{ fi->vi.height }; 341 | 342 | const int device{ avs_defined(avs_array_elt(args, Device)) ? avs_as_int(avs_array_elt(args, Device)) : -1 }; 343 | const int list_device{ avs_defined(avs_array_elt(args, List_device)) ? avs_as_bool(avs_array_elt(args, List_device)) : 0 }; 344 | 345 | if (list_device || device > -1) 346 | { 347 | std::vector devices{}; 348 | VkInstance inst{}; 349 | 350 | AVS_Value dev_info{ devices_info(clip, fi->env, devices, inst, params->msg, "libplacebo_Resample", device, list_device) }; 351 | if (avs_is_error(dev_info) || avs_is_clip(dev_info)) 352 | return dev_info; 353 | 354 | params->vf = avs_libplacebo_init(devices[device], params->msg); 355 | 356 | vkDestroyInstance(inst, nullptr); 357 | } 358 | else 359 | { 360 | if (device < -1) 361 | return set_error(clip, "libplacebo_Resample: device must be greater than or equal to -1.", nullptr); 362 | 363 | params->vf = avs_libplacebo_init(nullptr, params->msg); 364 | } 365 | 366 | if (params->msg.size()) 367 | { 368 | params->msg = "libplacebo_Resample: " + params->msg; 369 | return set_error(clip, params->msg.c_str(), nullptr); 370 | } 371 | 372 | fi->vi.width = avs_as_int(avs_array_elt(args, Width)); 373 | fi->vi.height = avs_as_int(avs_array_elt(args, Height)); 374 | 375 | params->src_x = (avs_defined(avs_array_elt(args, Sx))) ? avs_as_float(avs_array_elt(args, Sx)) : 0.0f; 376 | params->src_y = (avs_defined(avs_array_elt(args, Sy))) ? avs_as_float(avs_array_elt(args, Sy)) : 0.0f; 377 | 378 | params->trc = static_cast((avs_defined(avs_array_elt(args, Trc))) ? avs_as_int(avs_array_elt(args, Trc)) : 1); 379 | 380 | if (avs_is_rgb(&fi->vi)) 381 | { 382 | params->linear = (avs_defined(avs_array_elt(args, Linearize))) ? avs_as_bool(avs_array_elt(args, Linearize)) : 1; 383 | 384 | if (params->linear) 385 | { 386 | const int sigmoid{ (avs_defined(avs_array_elt(args, Sigmoidize))) ? avs_as_bool(avs_array_elt(args, Sigmoidize)) : 1 }; 387 | 388 | if (sigmoid) 389 | { 390 | params->sigmoid_params = std::make_unique(); 391 | 392 | params->sigmoid_params->center = (avs_defined(avs_array_elt(args, Sigmoid_center))) ? avs_as_float(avs_array_elt(args, Sigmoid_center)) : 0.75f; 393 | if (params->sigmoid_params->center < 0.0f || params->sigmoid_params->center > 1.0f) 394 | return set_error(clip, "libplacebo_Resample: sigmoid_center must be between 0.0 and 1.0.", params->vf); 395 | 396 | params->sigmoid_params->slope = (avs_defined(avs_array_elt(args, Sigmoid_slope))) ? avs_as_float(avs_array_elt(args, Sigmoid_slope)) : 6.5f; 397 | if (params->sigmoid_params->slope < 1.0f || params->sigmoid_params->slope > 20.0f) 398 | return set_error(clip, "libplacebo_Resample: sigmoid_slope must be between 1.0 and 20.0.", params->vf); 399 | } 400 | } 401 | } 402 | else 403 | params->linear = 0; 404 | 405 | params->sample_params = std::make_unique(); 406 | params->sample_params->no_widening = false; 407 | params->sample_params->no_compute = false; 408 | params->sample_params->antiring = (avs_defined(avs_array_elt(args, Antiring))) ? avs_as_float(avs_array_elt(args, Antiring)) : 0.0f; 409 | if (params->sample_params->antiring < 0.0f || params->sample_params->antiring > 1.0f) 410 | return set_error(clip, "libplacebo_Resample: antiring must be between 0.0 and 1.0.", params->vf); 411 | 412 | const pl_filter_config* filter_config{ pl_find_filter_config((avs_defined(avs_array_elt(args, Filter))) ? avs_as_string(avs_array_elt(args, Filter)) : "ewa_lanczos", PL_FILTER_UPSCALING) }; 413 | if (!filter_config) 414 | return set_error(clip, "libplacebo_Resample: not a valid filter.", params->vf); 415 | 416 | params->sample_params->filter = *filter_config; 417 | params->sample_params->filter.clamp = (avs_defined(avs_array_elt(args, Clamp))) ? avs_as_float(avs_array_elt(args, Clamp)) : 0.0f; 418 | if (params->sample_params->filter.clamp < 0.0f || params->sample_params->filter.clamp > 1.0f) 419 | return set_error(clip, "libplacebo_Resample: clamp must be between 0.0 and 1.0.", params->vf); 420 | 421 | params->sample_params->filter.blur = (avs_defined(avs_array_elt(args, Blur))) ? avs_as_float(avs_array_elt(args, Blur)) : 0.0f; 422 | if (params->sample_params->filter.blur < 0.0f || params->sample_params->filter.blur > 100.0f) 423 | return set_error(clip, "libplacebo_Resample: blur must be between 0.0 and 100.0.", params->vf); 424 | 425 | params->sample_params->filter.taper = (avs_defined(avs_array_elt(args, Taper))) ? avs_as_float(avs_array_elt(args, Taper)) : 0.0f; 426 | if (params->sample_params->filter.taper < 0.0f || params->sample_params->filter.taper > 1.0f) 427 | return set_error(clip, "libplacebo_Resample: taper must be between 0.0 and 1.0.", params->vf); 428 | 429 | if (avs_defined(avs_array_elt(args, Radius))) 430 | { 431 | params->sample_params->filter.radius = avs_as_float(avs_array_elt(args, Radius)); 432 | if (params->sample_params->filter.radius < 0.0f || params->sample_params->filter.radius > 16.0f) 433 | return set_error(clip, "libplacebo_Resample: radius must be between 0.0 and 16.0.", params->vf); 434 | } 435 | 436 | if (avs_defined(avs_array_elt(args, Param1))) 437 | params->sample_params->filter.params[0] = avs_as_float(avs_array_elt(args, Param1)); 438 | if (avs_defined(avs_array_elt(args, Param2))) 439 | params->sample_params->filter.params[1] = avs_as_float(avs_array_elt(args, Param2)); 440 | 441 | if (avs_is_420(&fi->vi) || avs_is_422(&fi->vi)) 442 | { 443 | params->cplace = (avs_defined(avs_array_elt(args, Cplace))) ? avs_as_int(avs_array_elt(args, Cplace)) : 0; 444 | if (params->cplace < 0 || params->cplace > 2) 445 | return set_error(clip, "libplacebo_Resample: cplace must be between 0 and 2.", params->vf); 446 | 447 | params->subw = (1 << avs_get_plane_width_subsampling(&fi->vi, AVS_PLANAR_U)); 448 | params->subh = (1 << avs_get_plane_height_subsampling(&fi->vi, AVS_PLANAR_U)); 449 | 450 | params->shift_w = (params->cplace == 0 || params->cplace == 2) ? (0.5f * (1.0f - static_cast(w) / fi->vi.width)) / params->subw : 0.0f; 451 | params->shift_h = (params->cplace == 2) ? (0.5f * (1.0f - static_cast(h) / fi->vi.height)) / params->subh : 0.0f; 452 | } 453 | else 454 | { 455 | params->subw = 1; 456 | params->subh = 1; 457 | params->shift_w = 0.0f; 458 | params->shift_h = 0.0f; 459 | } 460 | 461 | if (avs_defined(avs_array_elt(args, Src_width))) 462 | { 463 | params->src_width = avs_as_float(avs_array_elt(args, Src_width)); 464 | if (params->src_width <= 0.0f) 465 | return set_error(clip, "libplacebo_Resample: src_width must be greater than 0.0.", params->vf); 466 | } 467 | else 468 | params->src_width = -1.0f; 469 | 470 | if (avs_defined(avs_array_elt(args, Src_height))) 471 | { 472 | params->src_height = avs_as_float(avs_array_elt(args, Src_height)); 473 | if (params->src_height <= 0.0f) 474 | return set_error(clip, "libplacebo_Resample: src_height must be greater than 0.0.", params->vf); 475 | } 476 | else 477 | params->src_height = -1.0f; 478 | 479 | switch (bits) 480 | { 481 | case 8: params->resample_process = resample_filter; break; 482 | case 16: params->resample_process = resample_filter; break; 483 | default:params->resample_process = resample_filter; break; 484 | } 485 | 486 | AVS_Value v{ avs_new_value_clip(clip) }; 487 | 488 | fi->user_data = reinterpret_cast(params); 489 | fi->get_frame = resample_get_frame; 490 | fi->set_cache_hints = resample_set_cache_hints; 491 | fi->free_filter = free_resample; 492 | 493 | avs_release_clip(clip); 494 | 495 | return v; 496 | } 497 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | An AviSynth+ plugin interface to [libplacebo](https://code.videolan.org/videolan/libplacebo) - a reusable library for GPU-accelerated image/video processing primitives and shaders. 4 | 5 | This is [a port of the VapourSynth plugin vs-placebo](https://github.com/Lypheo/vs-placebo). 6 | 7 | ### Requirements: 8 | 9 | - Vulkan device 10 | 11 | - AviSynth+ r3688 (can be downloaded from [here](https://gitlab.com/uvz/AviSynthPlus-Builds) until official release is uploaded) or later 12 | 13 | - Microsoft VisualC++ Redistributable Package 2022 (can be downloaded from [here](https://github.com/abbodi1406/vcredist/releases)) 14 | 15 | ### Filters 16 | 17 | [Debanding](#debanding)
18 | [Resampling](#resampling)
19 | [Shader](#shader)
20 | [Tone mapping](#tone-mapping) 21 | 22 | ### Debanding 23 | 24 | #### Usage: 25 | 26 | ``` 27 | libplacebo_Deband(clip input, int "iterations", float "threshold", float "radius", float "grainY", float "grainC", int "dither", int "lut_size", bool "temporal", int[] "planes", int "device", bool "list_device", float[] "grain_neutral") 28 | ``` 29 | 30 | #### Parameters: 31 | 32 | - input
33 | A clip to process.
34 | It must be in 8, 16 or 32-bit planar format. 35 | 36 | - iterations
37 | The number of debanding steps to perform per sample.
38 | Each step reduces a bit more banding, but takes time to compute.
39 | Note that the strength of each step falls off very quickly, so high numbers (>4) are practically useless.
40 | Must be greater than or equal to 0.
41 | Default: 1. 42 | 43 | - threshold
44 | The debanding filter's cut-off threshold.
45 | Higher numbers increase the debanding strength dramatically, but progressively diminish image details.
46 | Must be greater than or equal to 0.0.
47 | Default: 4.0. 48 | 49 | - radius
50 | The debanding filter's initial radius.
51 | The radius increases linearly for each iteration.
52 | A higher radius will find more gradients, but a lower radius will smooth more aggressively.
53 | Must be radius must be greater than or equal to 0.0.
54 | Default: 16.0. 55 | 56 | - grainY, grainC
57 | Add some extra noise respectively to the luma and chroma plane.
58 | This significantly helps cover up remaining quantization artifacts.
59 | Higher numbers add more noise.
60 | Note: When debanding HDR sources, even a small amount of grain can result in a very big change to the brightness level.
61 | It's recommended to either scale this value down or disable it entirely for HDR.
62 | Must be greater than or equal to 0.0.
63 | When the clip is RGB, grainC doesn't have effect.
64 | Default: grainY = 6.0; grainC = grainY. 65 | 66 | - dither
67 | It's valid only for 8-bit clips.
68 | 0: Disabled. 69 | 70 | 1: PL_DITHER_BLUE_NOISE
71 | Dither with blue noise.
72 | Very high quality, but requires the use of a LUT.
73 | Warning: Computing a blue noise texture with a large size can be very slow, however this only needs to be performed once. Even so, using this with a `lut_size` greater than `6` is generally ill-advised. 74 | 75 | 2: PL_DITHER_ORDERED_LUT
76 | Dither with an ordered (bayer) dither matrix, using a LUT.
77 | Low quality, and since this also uses a LUT, there's generally no advantage to picking this instead of `PL_DITHER_BLUE_NOISE`.
78 | It's mainly there for testing. 79 | 80 | 3: PL_DITHER_ORDERED_FIXED
81 | The same as `PL_DITHER_ORDERED_LUT`, but uses fixed function math instead of a LUT.
82 | This is faster, but only supports a fixed dither matrix size of 16x16 (equal to a `lut_size` of 4). 83 | 84 | 4: PL_DITHER_WHITE_NOISE
85 | Dither with white noise.
86 | This does not require a LUT and is fairly cheap to compute.
87 | Unlike the other modes it doesn't show any repeating patterns either spatially or temporally, but the downside is that this is visually fairly jarring due to the presence of low frequencies in the noise spectrum. 88 | 89 | Default: 1. 90 | 91 | - lut_size
92 | For the dither methods which require the use of a LUT.
93 | This controls the size of the LUT (base 2).
94 | Must be less than or equal to 8.
95 | Default: 6 (64x64). 96 | 97 | - temporal
98 | Enables temporal dithering.
99 | his reduces the persistence of dithering artifacts by perturbing the dithering matrix per frame.
100 | Warning: This can cause nasty aliasing artifacts on some LCD screens.
101 | Default: False. 102 | 103 | - planes
104 | Planes to process.
105 | 1: Return garbage.
106 | 2: Copy plane.
107 | 3: Process plane. Always process planes when the clip is RGB.
108 | Format is [y, u, v].
109 | Default: [3, 2, 2]. 110 | 111 | - device
112 | Sets target Vulkan device.
113 | Use list_device to get the index of the available devices.
114 | By default the default device is selected. 115 | 116 | - list_device
117 | Whether to draw the devices list on the frame.
118 | Default: False. 119 | 120 | - grain_neutral
121 | "Neutral" grain value for each channel being debanded.
122 | Grain application will be modulated to avoid disturbing colors close to this value.
123 | Set this to a value corresponding to black in the relevant colorspace.
124 | Must be greater than 0.0
125 | Default: [0, 0, 0]. 126 | 127 | [Back to filters](#filters) 128 | 129 | ### Resampling 130 | 131 | #### Usage: 132 | 133 | ``` 134 | libplacebo_Resample(clip input, int width, int height, string "filter", float "radius", float "clamp", float "taper", float "blur", float "param1", float "param2", float "sx", float "sy", float "antiring", bool "sigmoidize", bool "linearize", float "sigmoid_center", float "sigmoid_slope", int "trc", int "cplace", int "device", bool "list_device", float "src_width", float "src_height") 135 | ``` 136 | 137 | #### Parameters: 138 | 139 | - input
140 | A clip to process.
141 | It must be in 8, 16 or 32-bit planar format. 142 | 143 | - width
144 | The width of the output. 145 | 146 | - height
147 | The height of the output. 148 | 149 | - filter 150 | The used filter function. 151 | 152 | * `spline16` (2 taps) 153 | * `spline36` (3 taps) 154 | * `spline64` (4 taps) 155 | * `nearest` (AKA box) 156 | * `bilinear` (AKA triangle) (resizable) 157 | * `gaussian` (resizable) 158 | 159 | Sinc family (all configured to 3 taps): 160 | * `sinc` (unwindowed) (resizable) 161 | * `lanczos` (sinc-sinc) (resizable) 162 | * `ginseng` (sinc-jinc) (resizable) 163 | * `ewa_jinc` (unwindowed) (resizable) 164 | * `ewa_lanczos` (jinc-jinc) (resizable) 165 | * `ewa_lanczossharp` (jinc-jinc) (resizable) 166 | * `ewa_lanczos4sharpest` (jinc-jinc) (resizable) 167 | * `ewa_ginseng` (jinc-sinc) (resizable) 168 | * `ewa_hann` (jinc-hann) (resizable) 169 | * `ewa_hanning` (ewa_hann alias) 170 | 171 | Spline family: 172 | * `bicubic` 173 | * `triangle` (bicubic alias) 174 | * `hermite` 175 | * `catmull_rom` 176 | * `mitchell` 177 | * `mitchell_clamp` 178 | * `robidoux` 179 | * `robidouxsharp` 180 | * `ewa_robidoux` 181 | * `ewa_robidouxsharp` 182 | 183 | Default: `ewa_lanczos` 184 | 185 | - radius
186 | It may be used to adjust the function's radius.
187 | Defaults to the the radius needed to represent a single filter lobe (tap).
188 | If the function is not resizable, this doesn't have effect.
189 | Must be between 0.0..16.0. 190 | 191 | - clamp
192 | Represents a clamping coefficient for negative weights:
193 | 0.0: No clamping.
194 | 1.0: Full clamping, i.e. all negative weights will be clamped to 0.
195 | Values between 0.0 and 1.0 can be specified to apply only a moderate diminishment of negative weights.
196 | Higher values would lead to more blur.
197 | Default: 0.0. 198 | 199 | - taper
200 | Additional taper coefficient.
201 | This essentially flattens the function's center.
202 | The values within `[-taper, taper]` will return 1.0, with the actual function being squished into the remainder of `[taper, radius]`.
203 | Must be between 0.0..1.0.
204 | Default: 0.0. 205 | 206 | - blur
207 | Additional blur coefficient.
208 | This effectively stretches the kernel, without changing the effective radius of the filter radius.
209 | Values significantly below 1.0 may seriously degrade the visual output, and should be used with care.
210 | Must be between 0.0..100.0.
211 | Default: 0.0. 212 | 213 | - param1, param2
214 | These may be used to adjust the function.
215 | Defaults to the function's preferred defaults. if the relevant setting is not tunable, they are ignored entirely. 216 | 217 | - sx
218 | Cropping of the left edge.
219 | Default: 0.0. 220 | 221 | - sy
222 | Cropping of the top edge.
223 | Default: 0.0. 224 | 225 | - antiring
226 | Antiringing strength.
227 | A value of 0.0 disables antiringing, and a value of 1.0 enables full-strength antiringing.
228 | Only relevant for separated/orthogonal filters.
229 | Default: 0.0. 230 | 231 | - sigmoidize, linearize
232 | Whether to linearize/sigmoidize before scaling.
233 | Only relevant for RGB formats.
234 | When sigmodizing, `linearize` should be `true`
235 | Default: True. 236 | 237 | - sigmoid_center
238 | The center (bias) of the sigmoid curve.
239 | Must be between 0.0 and 1.0.
240 | Default: 0.75. 241 | 242 | - sigmoid_slope
243 | The slope (steepness) of the sigmoid curve.
244 | Must be between 1.0 and 20.0.
245 | Default: 6.5. 246 | 247 | - trc
248 | The colorspace's transfer function (gamma / EOTF) to use for linearizing.
249 | 0: UNKNOWN 250 | 251 | Standard dynamic range:
252 | 1: BT_1886 (ITU-R Rec. BT.1886 (CRT emulation + OOTF))
253 | 2: SRGB (IEC 61966-2-4 sRGB (CRT emulation))
254 | 3: LINEAR (Linear light content)
255 | 4: GAMMA18 (Pure power gamma 1.8)
256 | 5: GAMMA20 (Pure power gamma 2.0)
257 | 6: GAMMA22 (Pure power gamma 2.2)
258 | 7: GAMMA24 (Pure power gamma 2.4)
259 | 8: GAMMA26 (Pure power gamma 2.6)
260 | 9: GAMMA28 (Pure power gamma 2.8)
261 | 10: PRO_PHOTO (ProPhoto RGB (ROMM))
262 | 11: ST428 (Digital Cinema Distribution Master (XYZ)) 263 | 264 | High dynamic range:
265 | 12: PQ (ITU-R BT.2100 PQ (perceptual quantizer), aka SMPTE ST2048)
266 | 13: HLG (ITU-R BT.2100 HLG (hybrid log-gamma), aka ARIB STD-B67)
267 | 14: V_LOG (Panasonic V-Log (VARICAM))
268 | 15: S_LOG1 (Sony S-Log1)
269 | 16: S_LOG2 (Sony S-Log2) 270 | 271 | Default: 1. 272 | 273 | - cplace
274 | Chroma sample position in YUV formats.
275 | 0: left
276 | 1: center
277 | 2: topleft
278 | Default: 0. 279 | 280 | - device
281 | Sets target Vulkan device.
282 | Use list_device to get the index of the available devices.
283 | By default the default device is selected. 284 | 285 | - list_device
286 | Whether to draw the devices list on the frame.
287 | Default: False. 288 | 289 | - src_width
290 | Sets the width of the clip before resizing.
291 | Must be greater than 0.0.
292 | Default: Source width. 293 | 294 | - src_height
295 | Sets the height of the clip before resizing.
296 | Must be greater than 0.0.
297 | Default: Source height. 298 | 299 | [Back to filters](#filters) 300 | 301 | ### Shader 302 | 303 | #### Usage: 304 | 305 | ``` 306 | libplacebo_Shader(clip input, string shader, int "width", int "height", int "chroma_loc", int "matrix", int "trc", string "filter", float "radius", float "clamp", float "taper", float "blur", float "param1", float "param2", float "antiring", bool "sigmoidize", bool "linearize", float "sigmoid_center", float "sigmoid_slope", string "shader_param", int "device", bool "list_device") 307 | ``` 308 | 309 | #### Parameters: 310 | 311 | - input
312 | A clip to process.
313 | It must be YUV 16-bit planar format.
314 | The output is YUV444P16. This is necessitated by the fundamental design of libplacebo/mpv’s custom shader feature: the shaders aren’t meant (nor written) to be run by themselves, but to be injected at arbitrary points into a [rendering pipeline](https://github.com/mpv-player/mpv/wiki/Video-output---shader-stage-diagram) with RGB output.
315 | As such, the user needs to specify the output frame properties, and libplacebo will produce a conforming image, only running the supplied shader if the texture it hooks into is actually rendered. For example, if a shader hooks into the LINEAR texture, it will only be executed when `linearize = true`. 316 | 317 | - shader
318 | Path to the shader file. 319 | 320 | - width
321 | The width of the output.
322 | Default: Source width. 323 | 324 | - height
325 | The height of the output.
326 | Default: Source height. 327 | 328 | - chroma_loc
329 | Chroma location to derive chroma shift from.
330 | 0: UNKNOWN
331 | 1: LEFT
332 | 2: CENTER
333 | 3: TOP_LEFT
334 | 4: TOP_CENTER
335 | 5: BOTTOM_LEFT
336 | 6: BOTTOM_CENTER
337 | Default: 1. 338 | 339 | - matrix
340 | 0: UNKNOWN
341 | 1: BT_601 (ITU-R Rec. BT.601 (SD))
342 | 2: BT_709 (ITU-R Rec. BT.709 (HD))
343 | 3: SMPTE_240M (SMPTE-240M)
344 | 4: BT_2020_NC (ITU-R Rec. BT.2020 (non-constant luminance))
345 | 5: BT_2020_C (ITU-R Rec. BT.2020 (constant luminance))
346 | 6: BT_2100_PQ (ITU-R Rec. BT.2100 ICtCp PQ variant)
347 | 7: BT_2100_HLG (ITU-R Rec. BT.2100 ICtCp HLG variant)
348 | 8: YCGCO (YCgCo (derived from RGB)) 349 | Default: 2. 350 | 351 | - trc
352 | The colorspace's transfer function (gamma / EOTF) to use for linearizing.
353 | 0: UNKNOWN 354 | 355 | Standard dynamic range:
356 | 1: BT_1886 (ITU-R Rec. BT.1886 (CRT emulation + OOTF))
357 | 2: SRGB (IEC 61966-2-4 sRGB (CRT emulation))
358 | 3: LINEAR (Linear light content)
359 | 4: GAMMA18 (Pure power gamma 1.8)
360 | 5: GAMMA20 (Pure power gamma 2.0)
361 | 6: GAMMA22 (Pure power gamma 2.2)
362 | 7: GAMMA24 (Pure power gamma 2.4)
363 | 8: GAMMA26 (Pure power gamma 2.6)
364 | 9: GAMMA28 (Pure power gamma 2.8)
365 | 10: PRO_PHOTO (ProPhoto RGB (ROMM))
366 | 11: ST428 (Digital Cinema Distribution Master (XYZ)) 367 | 368 | High dynamic range:
369 | 12: PQ (ITU-R BT.2100 PQ (perceptual quantizer), aka SMPTE ST2048)
370 | 13: HLG (ITU-R BT.2100 HLG (hybrid log-gamma), aka ARIB STD-B67)
371 | 14: V_LOG (Panasonic V-Log (VARICAM))
372 | 15: S_LOG1 (Sony S-Log1)
373 | 16: S_LOG2 (Sony S-Log2) 374 | 375 | Default: 1. 376 | 377 | - filter 378 | The used filter function. 379 | 380 | * `spline16` (2 taps) 381 | * `spline36` (3 taps) 382 | * `spline64` (4 taps) 383 | * `nearest` (AKA box) 384 | * `bilinear` (AKA triangle) (resizable) 385 | * `gaussian` (resizable) 386 | 387 | Sinc family (all configured to 3 taps): 388 | * `sinc` (unwindowed) (resizable) 389 | * `lanczos` (sinc-sinc) (resizable) 390 | * `ginseng` (sinc-jinc) (resizable) 391 | * `ewa_jinc` (unwindowed) (resizable) 392 | * `ewa_lanczos` (jinc-jinc) (resizable) 393 | * `ewa_lanczossharp` (jinc-jinc) (resizable) 394 | * `ewa_lanczos4sharpest` (jinc-jinc) (resizable) 395 | * `ewa_ginseng` (jinc-sinc) (resizable) 396 | * `ewa_hann` (jinc-hann) (resizable) 397 | * `ewa_hanning` (ewa_hann alias) 398 | 399 | Spline family: 400 | * `bicubic` 401 | * `triangle` (bicubic alias) 402 | * `hermite` 403 | * `catmull_rom` 404 | * `mitchell` 405 | * `mitchell_clamp` 406 | * `robidoux` 407 | * `robidouxsharp` 408 | * `ewa_robidoux` 409 | * `ewa_robidouxsharp` 410 | 411 | Default: `ewa_lanczos` 412 | 413 | - radius
414 | It may be used to adjust the function's radius.
415 | Defaults to the the radius needed to represent a single filter lobe (tap).
416 | If the function is not resizable, this doesn't have effect.
417 | Must be between 0.0..16.0. 418 | 419 | - clamp
420 | Represents a clamping coefficient for negative weights:
421 | 0.0: No clamping.
422 | 1.0: Full clamping, i.e. all negative weights will be clamped to 0.
423 | Values between 0.0 and 1.0 can be specified to apply only a moderate diminishment of negative weights.
424 | Higher values would lead to more blur.
425 | Default: 0.0. 426 | 427 | - taper
428 | Additional taper coefficient.
429 | This essentially flattens the function's center.
430 | The values within `[-taper, taper]` will return 1.0, with the actual function being squished into the remainder of `[taper, radius]`.
431 | Must be between 0.0..1.0.
432 | Default: 0.0. 433 | 434 | - blur
435 | Additional blur coefficient.
436 | This effectively stretches the kernel, without changing the effective radius of the filter radius.
437 | Values significantly below 1.0 may seriously degrade the visual output, and should be used with care.
438 | Must be between 0.0..100.0.
439 | Default: 0.0. 440 | 441 | - param1, param2
442 | These may be used to adjust the function.
443 | Defaults to the function's preferred defaults. if the relevant setting is not tunable, they are ignored entirely. 444 | 445 | - antiring
446 | Antiringing strength.
447 | A value of 0.0 disables antiringing, and a value of 1.0 enables full-strength antiringing.
448 | Only relevant for separated/orthogonal filters.
449 | Default: 0.0. 450 | 451 | - sigmoidize, linearize
452 | Whether to linearize/sigmoidize before scaling.
453 | Only relevant for RGB formats.
454 | When sigmodizing, `linearize` should be `true`
455 | Default: True. 456 | 457 | - sigmoid_center
458 | The center (bias) of the sigmoid curve.
459 | Must be between 0.0 and 1.0.
460 | Default: 0.75. 461 | 462 | - sigmoid_slope
463 | The slope (steepness) of the sigmoid curve.
464 | Must be between 1.0 and 20.0.
465 | Default: 6.5. 466 | 467 | - shader_param
468 | This changes shader's parameter set by `#define XXXX YYYY` on the fly.
469 | Format is: `param=value`.
470 | The parameter is case sensitive and must be the same as in the shader file.
471 | If more than one parameter is specified, the parameters must be separated by space. 472 | 473 | Usage example: if the shader has the following parameters: 474 | * #define INTENSITY_SIGMA 0.1 //Intensity window size, higher is stronger denoise, must be a positive real number 475 | * #define SPATIAL_SIGMA 1.0 //Spatial window size, higher is stronger denoise, must be a positive real number 476 | 477 | `shader_param="INTENSITY_SIGMA=0.15 SPATIAL_SIGMA=1.1"` 478 | 479 | - device
480 | Sets target Vulkan device.
481 | Use list_device to get the index of the available devices.
482 | By default the default device is selected. 483 | 484 | - list_device
485 | Whether to draw the devices list on the frame.
486 | Default: False. 487 | 488 | [Back to filters](#filters) 489 | 490 | ### Tone mapping 491 | 492 | #### Usage: 493 | 494 | ``` 495 | libplacebo_Tonemap(clip input, int "src_csp", float "dst_csp", float "src_max", float "src_min", float "dst_max", float "dst_min", bool "dynamic_peak_detection", float "smoothing_period", float "scene_threshold_low", float "scene_threshold_high", float "percentile", float "black_cutoff", string "gamut_mapping_mode", string "tone_mapping_function", string[] "tone_constants", int "metadata", float "contrast_recovery", float "contrast_smoothness", bool "visualize_lut", bool "show_clipping", bool "use_dovi", int "device", bool "list_device", string "cscale", string "lut", int "lut_type", int "dst_prim", int "dst_trc", int "dst_sys") 496 | ``` 497 | 498 | #### Parameters: 499 | 500 | - input
501 | A clip to process.
502 | It must be 16-bit planar format. (min. 3 planes)
503 | The output is YUV444P16 if the input is YUV. 504 | 505 | - src_csp, dst_csp
506 | Respectively source and output color space.
507 | 0: SDR
508 | 1: HDR10
509 | 2: HLG
510 | 3: DOVI
511 | Default: src_csp = 1; dst_csp = 0. 512 | 513 | For example, to map from [BT.2020, PQ] (HDR) to traditional [BT.709, BT.1886] (SDR), pass `src_csp=1, dst_csp=0`. 514 | 515 | - src_max, src_min, dst_max, dst_min
516 | Source max/min and output max/min in nits (cd/m^2).
517 | The source values can be derived from props if available.
518 | Default: max = 1000 (HDR)/203 (SDR); min = 0.005 (HDR)/0.2023 (SDR) 519 | 520 | - dynamic_peak_detection
521 | Enables computation of signal stats to optimize HDR tonemapping quality.
522 | Default: True. 523 | 524 | - smoothing_period
525 | Smoothing coefficient for the detected values.
526 | This controls the time parameter (tau) of an IIR low pass filter. In other words, it represent the cutoff period (= 1 / cutoff frequency) in frames. Frequencies below this length will be suppressed.
527 | This helps block out annoying "sparkling" or "flickering" due to small variations in frame-to-frame brightness.
528 | Default: 20.0. 529 | 530 | - scene_threshold_low, scene_threshold_high
531 | In order to avoid reacting sluggishly on scene changes as a result of the low-pass filter, we disable it when the difference between the current frame brightness and the average frame brightness exceeds a given threshold difference.
532 | But rather than a single hard cutoff, which would lead to weird discontinuities on fades, we gradually disable it over a small window of brightness ranges. These parameters control the lower and upper bounds of this window, in dB.
533 | To disable this logic entirely, set either one to a negative value.
534 | Default: scene_threshold_low = 1.0; scene_threshold_high = 3.0 535 | 536 | - percentile
537 | Which percentile of the input image brightness histogram to consider as the true peak of the scene.
538 | If this is set to 100 (or 0), the brightest pixel is measured. Otherwise, the top of the frequency distribution is progressively cut off.
539 | Setting this too low will cause clipping of very bright details, but can improve the dynamic brightness range of scenes with very bright isolated highlights.
540 | The default of 99.995% is very conservative and should cause no major issues in typical content. 541 | 542 | - black_cutoff
543 | Black cutoff strength.
544 | To prevent unnatural pixel shimmer and excessive darkness in mostly black scenes, as well as avoid black bars from affecting the content, (smoothly) cut off any value below this (PQ%) threshold.
545 | Setting this to 0.0 (or a negative value) disables this functionality.
546 | Default: 1.0 (1% PQ). 547 | 548 | - gamut_mapping_mode
549 | Specifies the algorithm used for reducing the gamut of images for the target display, after any tone mapping is done.
550 | 551 | * `clip`: Hard-clip to the gamut (per-channel). Very low quality, but free. 552 | 553 | * `perceptual`: Performs a perceptually balanced gamut mapping using a soft knee function to roll-off clipped regions, and a hue shifting function to preserve saturation. 554 | 555 | * `softclip`: Performs a perceptually balanced gamut mapping using a soft knee function to roll-off clipped regions, and a hue shifting function to preserve saturation. 556 | 557 | * `relative`: Performs relative colorimetric clipping, while maintaining an exponential relationship between brightness and chromaticity. 558 | 559 | * `saturation`: Performs simple RGB->RGB saturation mapping. The input R/G/B channels are mapped directly onto the output R/G/B channels. Will never clip, but will distort all hues and/or result in a faded look. 560 | 561 | * `absolute`: Performs absolute colorimetric clipping. Like `relative`, but does not adapt the white point. 562 | 563 | * `desaturate`: Performs constant-luminance colorimetric clipping, desaturing colors towards white until they're in-range. 564 | 565 | * `darken`: Uniformly darkens the input slightly to prevent clipping on blown-out highlights, then clamps colorimetrically to the input gamut boundary, biased slightly to preserve chromaticity over luminance. 566 | 567 | * `highlight`: Performs no gamut mapping, but simply highlights out-of-gamut pixels. 568 | 569 | * `linear`: Linearly/uniformly desaturates the image in order to bring the entire image into the target gamut. 570 | 571 | Default: `perceptual`. 572 | 573 | - tone_mapping_function 574 | 575 | * `clip`: Performs no tone-mapping, just clips out-of-range colors.
576 | Retains perfect color accuracy for in-range colors but completely destroys out-of-range information.
577 | Does not perform any black point adaptation. 578 | 579 | * `st2094-40`: EETF from SMPTE ST 2094-40 Annex B, which uses the provided OOTF based on Bezier curves to perform tone-mapping.
580 | The OOTF used is adjusted based on the ratio between the targeted and actual display peak luminances.
581 | In the absence of HDR10+ metadata, falls back to a simple constant bezier curve.
582 | 583 | * `st2094-10`: EETF from SMPTE ST 2094-10 Annex B.2, which takes into account the input signal average luminance in addition to the maximum/minimum.
584 | Note: This does *not* currently include the subjective gain/offset/gamma controls defined in Annex B.3. 585 | 586 | * `bt2390`: EETF from the ITU-R Report BT.2390, a hermite spline roll-off with linear segment.
587 | 588 | * `bt2446a`: EETF from ITU-R Report BT.2446, method A.
589 | Can be used for both forward and inverse tone mapping. 590 | 591 | * `spline`: Simple spline consisting of two polynomials, joined by a single pivot point.
592 | Simple spline consisting of two polynomials, joined by a single pivot point, which is tuned based on the source scene average brightness (taking into account HDR10+ metadata if available).
593 | This function can be used for both forward and inverse tone mapping. 594 | 595 | * `reinhard`: Very simple non-linear curve.
596 | Named after Erik Reinhard.
597 | 598 | * `mobius`: Generalization of the `reinhard` tone mapping algorithm to support an additional linear slope near black.
599 | The name is derived from its function shape `(ax+b)/(cx+d)`, which is known as a Möbius transformation.
600 | This function is considered legacy/low-quality, and should not be used. 601 | 602 | * `hable`: Piece-wise, filmic tone-mapping algorithm developed by John Hable for use in Uncharted 2, inspired by a similar tone-mapping algorithm used by Kodak.
603 | Popularized by its use in video games with HDR rendering.
604 | Preserves both dark and bright details very well, but comes with the drawback of changing the average brightness quite significantly.
605 | This is sort of similar to `reinhard` with `reinhard_contrast=0.24`.
606 | This function is considered legacy/low-quality, and should not be used. 607 | 608 | * `gamma`: Fits a gamma (power) function to transfer between the source and target color spaces, effectively resulting in a perceptual hard-knee joining two roughly linear sections.
609 | This preserves details at all scales fairly accurately, but can result in an image with a muted or dull appearance.
610 | This function is considered legacy/low-quality and should not be used. 611 | 612 | * `linear`: Linearly stretches the input range to the output range, in PQ space.
613 | This will preserve all details accurately, but results in a significantly different average brightness.
614 | Can be used for inverse tone-mapping in addition to regular tone-mapping.
615 | 616 | * `linearlight`: Like `linear`, but in linear light (instead of PQ).
617 | Works well for small range adjustments but may cause severe darkening when downconverting from e.g. 10k nits to SDR. 618 | 619 | Default: `bt2390`. 620 | 621 | - tone_constants
622 | Tone mapping constants for tuning `tone_mapping_function`.
623 | Format is `tone_constants=["option=xxx", "option1=xxx", "option2=xxx"]`. For example, `tone_constants=["exposure=0.25"]`. 624 | 625 | * `knee_adaptation`: Configures the knee point, as a ratio between the source average and target average (in PQ space).
626 | An adaptation of 1.0 always adapts the source scene average brightness to the (scaled) target average, while a value of 0.0 never modifies scene brightness.
627 | Must be between 0.0..1.0.
628 | Affects all methods that use the ST2094 knee point determination (currently ST2094-40, ST2094-10 and spline).
629 | Default: 0.4. 630 | 631 | * `knee_minimum`, `knee_maximum`: Configures the knee point minimum and maximum, respectively, as a percentage of the PQ luminance range.
632 | Provides a hard limit on the knee point chosen by `knee_adaptation`.
633 | `knee_minimum` must be between 0.0..0.5.
634 | `knee_maximum` must be between 0.5..1.0.
635 | Default: `knee_minimum` 0.1; `knee_maximum` 0.8. 636 | 637 | * `knee_default`: Default knee point to use in the absence of source scene average metadata.
638 | Normally, this is ignored in favor of picking the knee point as the (relative) source scene average brightness level.
639 | Must be between `knee_minimum` and `knee_maximum`.
640 | Default: 0.4. 641 | 642 | * `knee_offset`: Knee point offset (for BT.2390 only).
643 | Note that a value of 0.5 is the spec-defined default behavior, which differs from the libplacebo default of 1.0.
644 | Must be between 0.5..2.0. 645 | 646 | * `slope_tuning`, `slope_offset`: For the single-pivot polynomial (spline) function, this controls the coefficients used to tune the slope of the curve.
647 | This tuning is designed to make the slope closer to 1.0 when the difference in peaks is low, and closer to linear when the difference between peaks is high.
648 | `slope_tuning` must be between 0.0..10.0.
649 | `slope_offset` must be between 0.0..1.0.
650 | Default: `slope_tuning` 1.5; `slope_offset` 0.2. 651 | 652 | * `spline_contrast`: Contrast setting for the spline function.
653 | Higher values make the curve steeper (closer to `clip`), preserving midtones at the cost of losing shadow/highlight details, while lower values make the curve shallowed (closer to `linear`), preserving highlights at the cost of losing midtone contrast.
654 | Values above 1.0 are possible, resulting in an output with more contrast than the input.
655 | Must be between 0.0..1.5.
656 | Default: 0.5. 657 | 658 | * `reinhard_contrast`: For the reinhard function, this specifies the local contrast coefficient at the display peak.
659 | Essentially, a value of 0.5 implies that the reference white will be about half as bright as when clipping. (0,1). 660 | Must be between 0.0..1.0.
661 | Default: 0.5. 662 | 663 | * `linear_knee`: For legacy functions (`mobius`, `gamma`) which operate on linear light, this directly sets the corresponding knee point.
664 | Must be between 0.0..1.0
665 | Default: 0.3. 666 | 667 | * `exposure`: For linear methods (`linear`, `linearlight`), this controls the linear exposure/gain applied to the image.
668 | Must be between 0.0..10.0.
669 | Default: 1.0. 670 | 671 | - metadata
672 | Data source to use when tone-mapping.
673 | Setting this to a specific value allows overriding the default metadata preference logic.
674 | 0: ANY
675 | 1: NONE
676 | 2: HDR10 (HDR10 static mastering display metadata)
677 | 3: HDR10PLUS (HDR10+ dynamic metadata)
678 | 4: CIE_Y (CIE Y derived dynamic luminance metadata) 679 | 680 | - contrast_recovery
681 | Contrast recovery strength.
682 | If set to a value above 0.0, the source image will be divided into high-frequency and low-frequency components, and a portion of the high-frequency image is added back onto the tone-mapped output.
683 | May cause excessive ringing artifacts for some HDR sources, but can improve the subjective sharpness and detail left over in the image after tone-mapping.
684 | Must be equal to or greater than 0.0.
685 | Default: 0.3. 686 | 687 | - contrast_smoothness
688 | Contrast recovery lowpass kernel size.
689 | Increasing or decreasing this will affect the visual appearance substantially.
690 | Must be equal to or greater than 0.0.
691 | Default: 3.5. 692 | 693 | - visualize_lut
694 | Visualize the tone-mapping curve / LUT. (PQ-PQ graph)
695 | Default: False. 696 | 697 | - show_clipping
698 | Graphically highlight hard-clipped pixels during tone-mapping (i.e. pixels that exceed the claimed source luminance range).
699 | Note that the difference between this and `gamut_mode=1` is that the latter only shows out-of-gamut colors (that are inside the monitor brightness range), while this shows out-of-range colors (regardless of whether or not they're in-gamut).
700 | Default: False. 701 | 702 | - use_dovi
703 | Whether to use the Dolby Vision RPU for ST2086 metadata.
704 | Defaults to true when tonemapping from Dolby Vision. 705 | 706 | - device
707 | Sets target Vulkan device.
708 | Use list_device to get the index of the available devices.
709 | By default the default device is selected. 710 | 711 | - list_device
712 | Whether to draw the devices list on the frame.
713 | Default: False. 714 | 715 | - cscale
716 | The scaler for chroma planes.
717 | This is used when the input is YUV420/YUV422. 718 | 719 | * `spline16` (2 taps) 720 | * `spline36` (3 taps) 721 | * `spline64` (4 taps) 722 | * `nearest` (AKA box) 723 | * `bilinear` (AKA triangle) (resizable) 724 | * `gaussian` (resizable) 725 | 726 | Sinc family (all configured to 3 taps): 727 | * `sinc` (unwindowed) (resizable) 728 | * `lanczos` (sinc-sinc) (resizable) 729 | * `ginseng` (sinc-jinc) (resizable) 730 | * `ewa_jinc` (unwindowed) (resizable) 731 | * `ewa_lanczos` (jinc-jinc) (resizable) 732 | * `ewa_lanczossharp` (jinc-jinc) (resizable) 733 | * `ewa_lanczos4sharpest` (jinc-jinc) (resizable) 734 | * `ewa_ginseng` (jinc-sinc) (resizable) 735 | * `ewa_hann` (jinc-hann) (resizable) 736 | * `ewa_hanning` (ewa_hann alias) 737 | 738 | Spline family: 739 | * `bicubic` 740 | * `triangle` (bicubic alias) 741 | * `hermite` 742 | * `catmull_rom` 743 | * `mitchell` 744 | * `mitchell_clamp` 745 | * `robidoux` 746 | * `robidouxsharp` 747 | * `ewa_robidoux` 748 | * `ewa_robidouxsharp` 749 | 750 | Default: `spline36`. 751 | 752 | - lut
753 | Path to the color mapping LUT.
754 | If present, this will be applied as part of the image being rendered.
755 | `src_csp` and `dst_csp` should be used to indicate the color spaces.
756 | Default: not specified. 757 | 758 | - lut_type
759 | Controls the interpretation of color values fed to and from the LUT.
760 | 1: native (Applied to raw image contents in its native RGB colorspace (non-linear light), before conversion to the output color space.)
761 | 2: normalized (Applied to the normalized RGB image contents, in linear light, before conversion to the output color space.)
762 | 3: conversion (Fully replaces the conversion from the input color space to the output color space. It overrides options related to tone mapping and output colorimetry (dst_prim, dst_trc etc.))
763 | Default: 3. 764 | 765 | - dst_prim
766 | Target primaries.
767 | `dst_trc` must be also specified.
768 | `dst_csp` has no effect. 769 | 770 | Standard gamut:
771 | 1: BT_601_525 (ITU-R Rec. BT.601 (525-line = NTSC, SMPTE-C))
772 | 2: BT_601_625 (ITU-R Rec. BT.601 (625-line = PAL, SECAM))
773 | 3: BT_709 (ITU-R Rec. BT.709 (HD), also sRGB)
774 | 4: BT_470M (ITU-R Rec. BT.470 M)
775 | 5: EBU_3213 (EBU Tech. 3213-E / JEDEC P22 phosphors)
776 | Wide gamut:
777 | 6: BT_2020 (ITU-R Rec. BT.2020 (UltraHD))
778 | 7: APPLE (Apple RGB)
779 | 8: ADOBE (Adobe RGB (1998))
780 | 9: PRO_PHOTO (ProPhoto RGB (ROMM))
781 | 10: CIE_1931 (CIE 1931 RGB primaries)
782 | 11: DCI_P3 (DCI-P3 (Digital Cinema))
783 | 12: DISPLAY_P3 (DCI-P3 (Digital Cinema) with D65 white point)
784 | 13: V_GAMUT (Panasonic V-Gamut (VARICAM))
785 | 14: S_GAMUT (Sony S-Gamut)
786 | 15: FILM_C (Traditional film primaries with Illuminant C)
787 | 16: ACES_AP0 (ACES Primaries #0 (ultra wide))
788 | 17: ACES_AP1 (ACES Primaries #1) 789 | 790 | Default: not specified. 791 | 792 | - dst_trc
793 | Target transfer function.
794 | `dst_prim` must be also specified.
795 | `dst_csp` has no effect. 796 | 797 | Standard dynamic range:
798 | 1: BT_1886 (ITU-R Rec. BT.1886 (CRT emulation + OOTF))
799 | 2: SRGB (IEC 61966-2-4 sRGB (CRT emulation))
800 | 3: LINEAR (Linear light content)
801 | 4: GAMMA18 (Pure power gamma 1.8)
802 | 5: GAMMA20 (Pure power gamma 2.0)
803 | 6: GAMMA22 (Pure power gamma 2.2)
804 | 7: GAMMA24 (Pure power gamma 2.4)
805 | 8: GAMMA26 (Pure power gamma 2.6)
806 | 9: GAMMA28 (Pure power gamma 2.8)
807 | 10: PRO_PHOTO (ProPhoto RGB (ROMM))
808 | 11: ST428 (Digital Cinema Distribution Master (XYZ))
809 | High dynamic range:
810 | 12: PQ (ITU-R BT.2100 PQ (perceptual quantizer), aka SMPTE ST2048)
811 | 13: HLG (ITU-R BT.2100 HLG (hybrid log-gamma), aka ARIB STD-B67)
812 | 14: V_LOG (Panasonic V-Log (VARICAM))
813 | 15: S_LOG1 (Sony S-Log1)
814 | 16: S_LOG2 (Sony S-Log2)
815 | 816 | Default: not specified. 817 | 818 | - dst_sys
819 | The underlying color representation.
820 | This has no effect if both `dst_prim` and `dst_trc` are not specified.
821 | This has effect only for YUV input.
822 | 1: BT_601 (ITU-R Rec. BT.601 (SD))
823 | 2: BT_709 (ITU-R Rec. BT.709 (HD))
824 | 3: SMPTE_240M (SMPTE-240M)
825 | 4: BT_2020_NC (ITU-R Rec. BT.2020 (non-constant luminance))
826 | 5: BT_2020_C (ITU-R Rec. BT.2020 (constant luminance))
827 | 6: BT_2100_PQ (ITU-R Rec. BT.2100 ICtCp PQ variant)
828 | 7: BT_2100_HLG (ITU-R Rec. BT.2100 ICtCp HLG variant)
829 | 8: DOLBYVISION (Dolby Vision (see pl_dovi_metadata))
830 | 9: YCGCO (YCgCo (derived from RGB))
831 | Default: not specified. 832 | 833 | [Back to filters](#filters) 834 | 835 | ### Building: 836 | 837 | ``` 838 | Requirements: 839 | - CMake 840 | - Ninja 841 | - Vulkan SDK (https://vulkan.lunarg.com/sdk) 842 | - Clang-cl (https://github.com/llvm/llvm-project/releases) (Windows) 843 | ``` 844 | 845 | ``` 846 | Steps: 847 | Install Vulkan SDk. 848 | 849 | Clone the repo: 850 | git clone --recurse-submodules --depth 1 --shallow-submodules https://github.com/Asd-g/avslibplacebo 851 | 852 | Set prefix: 853 | cd avslibplacebo 854 | set prefix="%cd%\deps" (Windows) 855 | prefix="$(pwd)/deps" (Linux) 856 | 857 | Build dolby_vision: 858 | cd dovi_tool/dolby_vision 859 | cargo install cargo-c 860 | cargo cinstall --release --prefix %prefix% (Windows) 861 | cargo cinstall --release --prefix $prefix (Linux) 862 | 863 | Building libplacebo: 864 | cd ../../libplacebo 865 | set LIB=%LIB%;C:\VulkanSDK\1.3.268.0\Lib (Windows) 866 | meson setup build -Dvulkan-registry=C:\VulkanSDK\1.3.283.0\share\vulkan\registry\vk.xml --default-library=static --buildtype=release -Ddemos=false -Dopengl=disabled -Dd3d11=disabled --prefix=%prefix% (Windows) 867 | meson setup build --default-library=static --buildtype=release -Ddemos=false -Dopengl=disabled -Dd3d11=disabled --prefix=$prefix (Linux) 868 | ninja -C build 869 | ninja -C build install 870 | 871 | Building plugin: 872 | cd ../ 873 | cmake -B build -G Ninja -DCMAKE_PREFIX_PATH="c:\VulkanSDK\1.3.283.0;%prefix%" (Windows) 874 | cmake -B build -G Ninja -DCMAKE_PREFIX_PATH=$prefix (Linux) 875 | ninja -C build 876 | ``` 877 | 878 | [Back to top](#description) 879 | -------------------------------------------------------------------------------- /src/tonemap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #ifdef _WIN32 9 | #include 10 | #endif 11 | 12 | #include "avs_libplacebo.h" 13 | 14 | extern "C" 15 | #include "libdovi/rpu_parser.h" 16 | 17 | static std::mutex mtx; 18 | 19 | static std::unique_ptr create_dovi_meta(DoviRpuOpaque& rpu, const DoviRpuDataHeader& hdr) 20 | { 21 | std::unique_ptr dovi_meta{ std::make_unique() }; // persist state 22 | if (hdr.use_prev_vdr_rpu_flag) 23 | goto done; 24 | 25 | { 26 | const DoviRpuDataMapping* mapping = dovi_rpu_get_data_mapping(&rpu); 27 | if (!mapping) 28 | goto skip_mapping; 29 | 30 | { 31 | const uint64_t bits{ hdr.bl_bit_depth_minus8 + 8 }; 32 | const float scale{ 1.0f / (1 << hdr.coefficient_log2_denom) }; 33 | 34 | for (int c{ 0 }; c < 3; ++c) 35 | { 36 | const DoviReshapingCurve curve{ mapping->curves[c] }; 37 | 38 | pl_dovi_metadata::pl_reshape_data* cmp{ &dovi_meta->comp[c] }; 39 | cmp->num_pivots = curve.pivots.len; 40 | memset(cmp->method, curve.mapping_idc, sizeof(cmp->method)); 41 | 42 | uint16_t pivot{ 0 }; 43 | for (int pivot_idx{ 0 }; pivot_idx < cmp->num_pivots; ++pivot_idx) 44 | { 45 | pivot += curve.pivots.data[pivot_idx]; 46 | cmp->pivots[pivot_idx] = static_cast(pivot) / ((1 << bits) - 1); 47 | } 48 | 49 | for (int i{ 0 }; i < cmp->num_pivots - 1; ++i) 50 | { 51 | memset(cmp->poly_coeffs[i], 0, sizeof(cmp->poly_coeffs[i])); 52 | 53 | if (curve.polynomial) 54 | { 55 | const DoviPolynomialCurve* poly_curve = curve.polynomial; 56 | 57 | for (int k{ 0 }; k <= poly_curve->poly_order_minus1.data[i] + 1; ++k) 58 | { 59 | int64_t ipart{ poly_curve->poly_coef_int.list[i]->data[k] }; 60 | uint64_t fpart{ poly_curve->poly_coef.list[i]->data[k] }; 61 | cmp->poly_coeffs[i][k] = ipart + scale * fpart; 62 | } 63 | } 64 | else if (curve.mmr) 65 | { 66 | const DoviMMRCurve* mmr_curve = curve.mmr; 67 | 68 | int64_t ipart{ mmr_curve->mmr_constant_int.data[i] }; 69 | uint64_t fpart{ mmr_curve->mmr_constant.data[i] }; 70 | cmp->mmr_constant[i] = ipart + scale * fpart; 71 | cmp->mmr_order[i] = mmr_curve->mmr_order_minus1.data[i] + 1; 72 | 73 | for (int j{ 0 }; j < cmp->mmr_order[i]; ++j) 74 | { 75 | for (int k{ 0 }; k < 7; ++k) 76 | { 77 | ipart = mmr_curve->mmr_coef_int.list[i]->list[j]->data[k]; 78 | fpart = mmr_curve->mmr_coef.list[i]->list[j]->data[k]; 79 | cmp->mmr_coeffs[i][j][k] = ipart + scale * fpart; 80 | } 81 | } 82 | } 83 | } 84 | } 85 | } 86 | 87 | dovi_rpu_free_data_mapping(mapping); 88 | } 89 | skip_mapping: 90 | 91 | if (hdr.vdr_dm_metadata_present_flag) 92 | { 93 | const DoviVdrDmData* dm_data{ dovi_rpu_get_vdr_dm_data(&rpu) }; 94 | if (!dm_data) 95 | goto done; 96 | 97 | const uint32_t* off{ &dm_data->ycc_to_rgb_offset0 }; 98 | for (int i{ 0 }; i < 3; ++i) 99 | dovi_meta->nonlinear_offset[i] = static_cast(off[i]) / (1 << 28); 100 | 101 | const int16_t* src{ &dm_data->ycc_to_rgb_coef0 }; 102 | float* dst{ &dovi_meta->nonlinear.m[0][0] }; 103 | for (int i{ 0 }; i < 9; ++i) 104 | dst[i] = src[i] / 8192.0f; 105 | 106 | src = &dm_data->rgb_to_lms_coef0; 107 | dst = &dovi_meta->linear.m[0][0]; 108 | for (int i{ 0 }; i < 9; ++i) 109 | dst[i] = src[i] / 16384.0f; 110 | 111 | dovi_rpu_free_vdr_dm_data(dm_data); 112 | } 113 | 114 | done: 115 | return dovi_meta; 116 | } 117 | 118 | enum class supported_colorspace 119 | { 120 | CSP_SDR = 0, 121 | CSP_HDR10, 122 | CSP_HLG, 123 | CSP_DOVI, 124 | }; 125 | 126 | template 127 | struct Map 128 | { 129 | std::array, Size> data; 130 | constexpr Value at(const Key& key) const 131 | { 132 | const auto itr{ std::find_if(begin(data), end(data), [&key](const auto& v) { return v.first == key; }) }; 133 | 134 | if (itr != end(data)) 135 | return itr->second; 136 | if constexpr (std::is_same_v) 137 | return 2; 138 | else 139 | return std::make_tuple(nullptr, -1.0f, -1.0f); 140 | } 141 | }; 142 | 143 | static constexpr std::array, 7> frame_prop_matrix 144 | { 145 | std::make_pair(PL_COLOR_SYSTEM_BT_709, 1), 146 | std::make_pair(PL_COLOR_SYSTEM_BT_601, 5), 147 | std::make_pair(PL_COLOR_SYSTEM_SMPTE_240M, 7), 148 | std::make_pair(PL_COLOR_SYSTEM_YCGCO, 8), 149 | std::make_pair(PL_COLOR_SYSTEM_BT_2020_NC, 9), 150 | std::make_pair(PL_COLOR_SYSTEM_BT_2020_C, 10), 151 | std::make_pair(PL_COLOR_SYSTEM_BT_2100_PQ, 14) 152 | }; 153 | 154 | static constexpr std::array, 6> frame_prop_transfer 155 | { 156 | std::make_pair(PL_COLOR_TRC_BT_1886, 1), 157 | std::make_pair(PL_COLOR_TRC_LINEAR, 8), 158 | std::make_pair(PL_COLOR_TRC_SRGB, 13), 159 | std::make_pair(PL_COLOR_TRC_PQ, 16), 160 | std::make_pair(PL_COLOR_TRC_HLG, 18), 161 | std::make_pair(PL_COLOR_TRC_PRO_PHOTO, 30) 162 | }; 163 | 164 | static constexpr std::array, 10> frame_prop_primaries 165 | { 166 | std::make_pair(PL_COLOR_PRIM_BT_709, 1), 167 | std::make_pair(PL_COLOR_PRIM_BT_470M, 4), 168 | std::make_pair(PL_COLOR_PRIM_BT_601_625, 5), 169 | std::make_pair(PL_COLOR_PRIM_BT_601_525, 6), 170 | std::make_pair(PL_COLOR_PRIM_FILM_C, 8), 171 | std::make_pair(PL_COLOR_PRIM_BT_2020, 9), 172 | std::make_pair(PL_COLOR_PRIM_DCI_P3, 11), 173 | std::make_pair(PL_COLOR_PRIM_DISPLAY_P3, 12), 174 | std::make_pair(PL_COLOR_PRIM_EBU_3213, 22), 175 | std::make_pair(PL_COLOR_PRIM_PRO_PHOTO, 30) 176 | }; 177 | 178 | static constexpr auto map_matrix{ Map{ { frame_prop_matrix } } }; 179 | static constexpr auto map_transfer{ Map{ { frame_prop_transfer } } }; 180 | static constexpr auto map_primaries{ Map{ { frame_prop_primaries } } }; 181 | 182 | struct tonemap 183 | { 184 | std::unique_ptr vf; 185 | std::unique_ptr render_params; 186 | enum supported_colorspace src_csp; 187 | enum supported_colorspace dst_csp; 188 | std::unique_ptr src_pl_csp; 189 | std::unique_ptr dst_pl_csp; 190 | float original_src_max; 191 | float original_src_min; 192 | int is_subsampled; 193 | enum pl_chroma_location chromaLocation; 194 | std::string msg; 195 | std::unique_ptr src_repr; 196 | std::unique_ptr dst_repr; 197 | int use_dovi; 198 | std::unique_ptr colorMapParams; 199 | std::unique_ptr peakDetectParams; 200 | std::unique_ptr dovi_meta; 201 | }; 202 | 203 | static bool tonemap_do_plane(tonemap* d, const pl_plane* planes) noexcept 204 | { 205 | pl_frame img{}; 206 | img.num_planes = 3; 207 | img.repr = *d->src_repr; 208 | img.planes[0] = planes[0]; 209 | img.planes[1] = planes[1]; 210 | img.planes[2] = planes[2]; 211 | img.color = *d->src_pl_csp; 212 | 213 | if (d->is_subsampled) 214 | pl_frame_set_chroma_location(&img, d->chromaLocation); 215 | 216 | pl_frame out{}; 217 | out.num_planes = 3; 218 | out.repr = *d->dst_repr; 219 | out.color = *d->dst_pl_csp; 220 | 221 | for (int i{ 0 }; i < 3; ++i) 222 | { 223 | out.planes[i].texture = d->vf->tex_out[i]; 224 | out.planes[i].components = 1; 225 | out.planes[i].component_mapping[0] = i; 226 | } 227 | 228 | return pl_render_image(d->vf->rr, &img, &out, d->render_params.get()); 229 | } 230 | 231 | static int tonemap_filter(AVS_VideoFrame* dst, AVS_VideoFrame* src, tonemap* d, const AVS_FilterInfo* fi) noexcept 232 | { 233 | const int error{ [&]() 234 | { 235 | for (int i{ 0 }; i < 3; ++i) 236 | { 237 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_out[i]); 238 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_in[i]); 239 | } 240 | 241 | return -1; 242 | }() }; 243 | 244 | const pl_fmt fmt{ pl_find_named_fmt(d->vf->gpu, "r16") }; 245 | if (!fmt) 246 | return error; 247 | 248 | pl_tex_params t_r{}; 249 | t_r.w = fi->vi.width; 250 | t_r.h = fi->vi.height; 251 | t_r.format = fmt; 252 | t_r.renderable = true; 253 | t_r.host_readable = true; 254 | 255 | pl_plane pl_planes[3]{}; 256 | constexpr int planes_y[3]{ AVS_PLANAR_Y, AVS_PLANAR_U, AVS_PLANAR_V }; 257 | constexpr int planes_r[3]{ AVS_PLANAR_R, AVS_PLANAR_G, AVS_PLANAR_B }; 258 | const int* planes{ (avs_is_rgb(&fi->vi)) ? planes_r : planes_y }; 259 | 260 | for (int i{ 0 }; i < 3; ++i) 261 | { 262 | const int plane{ planes[i] }; 263 | 264 | pl_plane_data pl{}; 265 | pl.type = PL_FMT_UNORM; 266 | pl.pixel_stride = 2; 267 | pl.component_size[0] = 16; 268 | pl.width = avs_get_row_size_p(src, plane) / avs_component_size(&fi->vi); 269 | pl.height = avs_get_height_p(src, plane); 270 | pl.row_stride = avs_get_pitch_p(src, plane); 271 | pl.pixels = avs_get_read_ptr_p(src, plane); 272 | pl.component_map[0] = i; 273 | 274 | // Upload planes 275 | if (!pl_upload_plane(d->vf->gpu, &pl_planes[i], &d->vf->tex_in[i], &pl)) 276 | return error; 277 | if (!pl_tex_recreate(d->vf->gpu, &d->vf->tex_out[i], &t_r)) 278 | return error; 279 | } 280 | 281 | // Process plane 282 | if (!tonemap_do_plane(d, pl_planes)) 283 | return error; 284 | 285 | const int dst_stride = (avs_get_pitch(dst) + (d->vf->gpu->limits.align_tex_xfer_pitch) - 1) & ~((d->vf->gpu->limits.align_tex_xfer_pitch) - 1); 286 | pl_buf_params buf_params{}; 287 | buf_params.size = dst_stride * fi->vi.height; 288 | buf_params.host_mapped = true; 289 | 290 | pl_buf dst_buf{}; 291 | if (!pl_buf_recreate(d->vf->gpu, &dst_buf, &buf_params)) 292 | return error; 293 | 294 | // Download planes 295 | for (int i{ 0 }; i < 3; ++i) 296 | { 297 | pl_tex_transfer_params ttr1{}; 298 | ttr1.row_pitch = dst_stride; 299 | ttr1.buf = dst_buf; 300 | ttr1.tex = d->vf->tex_out[i]; 301 | 302 | if (!pl_tex_download(d->vf->gpu, &ttr1)) 303 | return error; 304 | 305 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_out[i]); 306 | pl_tex_destroy(d->vf->gpu, &d->vf->tex_in[i]); 307 | 308 | while (pl_buf_poll(d->vf->gpu, dst_buf, 0)); 309 | memcpy(avs_get_write_ptr_p(dst, planes[i]), dst_buf->data, dst_buf->params.size); 310 | } 311 | 312 | pl_buf_destroy(d->vf->gpu, &dst_buf); 313 | 314 | return 0; 315 | } 316 | 317 | static AVS_VideoFrame* AVSC_CC tonemap_get_frame(AVS_FilterInfo* fi, int n) 318 | { 319 | tonemap* d{ reinterpret_cast(fi->user_data) }; 320 | 321 | AVS_VideoFrame* src{ avs_get_frame(fi->child, n) }; 322 | if (!src) 323 | return nullptr; 324 | 325 | AVS_VideoFrame* dst{ avs_new_video_frame_p(fi->env, &fi->vi, src) }; 326 | 327 | const auto error{ [&](const std::string& msg) 328 | { 329 | avs_release_video_frame(src); 330 | avs_release_video_frame(dst); 331 | 332 | d->msg = msg; 333 | fi->error = d->msg.c_str(); 334 | 335 | return nullptr; 336 | } }; 337 | 338 | int err; 339 | const AVS_Map* props{ avs_get_frame_props_ro(fi->env, src) }; 340 | 341 | int64_t props_levels{ avs_prop_get_int(fi->env, props, "_ColorRange", 0, &err) }; 342 | if (!err) 343 | // Existing range prop 344 | d->src_repr->levels = (props_levels) ? PL_COLOR_LEVELS_LIMITED : PL_COLOR_LEVELS_FULL; 345 | 346 | if (!avs_is_rgb(&fi->vi)) 347 | { 348 | if (!err && !props_levels) 349 | // Existing range & not limited 350 | d->dst_repr->levels = PL_COLOR_LEVELS_FULL; 351 | } 352 | 353 | // ST2086 metadata 354 | // Update metadata from props 355 | 356 | const double maxCll{ avs_prop_get_float(fi->env, props, "ContentLightLevelMax", 0, &err) }; 357 | const double maxFall{ avs_prop_get_float(fi->env, props, "ContentLightLevelAverage", 0, &err) }; 358 | 359 | d->src_pl_csp->hdr.max_cll = maxCll; 360 | d->src_pl_csp->hdr.max_fall = maxFall; 361 | 362 | if (d->original_src_max < 1) 363 | d->src_pl_csp->hdr.max_luma = avs_prop_get_float(fi->env, props, "MasteringDisplayMaxLuminance", 0, &err); 364 | if (d->original_src_min <= 0) 365 | d->src_pl_csp->hdr.min_luma = avs_prop_get_float(fi->env, props, "MasteringDisplayMinLuminance", 0, &err); 366 | 367 | const double* primariesX{ avs_prop_get_float_array(fi->env, props, "MasteringDisplayPrimariesX", &err) }; 368 | const double* primariesY{ avs_prop_get_float_array(fi->env, props, "MasteringDisplayPrimariesY", &err) }; 369 | 370 | if (primariesX && primariesY && avs_prop_num_elements(fi->env, props, "MasteringDisplayPrimariesX") == 3 && avs_prop_num_elements(fi->env, props, "MasteringDisplayPrimariesY") == 3) 371 | { 372 | d->src_pl_csp->hdr.prim.red.x = primariesX[0]; 373 | d->src_pl_csp->hdr.prim.red.y = primariesY[0]; 374 | d->src_pl_csp->hdr.prim.green.x = primariesX[1]; 375 | d->src_pl_csp->hdr.prim.green.y = primariesY[1]; 376 | d->src_pl_csp->hdr.prim.blue.x = primariesX[2]; 377 | d->src_pl_csp->hdr.prim.blue.y = primariesY[2]; 378 | 379 | // White point comes with primaries 380 | const double whitePointX{ avs_prop_get_float(fi->env, props, "MasteringDisplayWhitePointX", 0, &err) }; 381 | const double whitePointY{ avs_prop_get_float(fi->env, props, "MasteringDisplayWhitePointY", 0, &err) }; 382 | 383 | if (whitePointX && whitePointY) 384 | { 385 | d->src_pl_csp->hdr.prim.white.x = whitePointX; 386 | d->src_pl_csp->hdr.prim.white.y = whitePointY; 387 | } 388 | } 389 | else 390 | // Assume DCI-P3 D65 default? 391 | pl_raw_primaries_merge(&d->src_pl_csp->hdr.prim, pl_raw_primaries_get((d->src_csp == supported_colorspace::CSP_SDR) ? d->src_pl_csp->primaries : PL_COLOR_PRIM_DISPLAY_P3)); 392 | 393 | d->chromaLocation = static_cast(avs_prop_get_int(fi->env, props, "_ChromaLocation", 0, &err)); 394 | if (!err) 395 | d->chromaLocation = static_cast(static_cast(d->chromaLocation) + 1); 396 | 397 | // DOVI 398 | if (d->src_csp == supported_colorspace::CSP_DOVI) 399 | { 400 | if (avs_prop_num_elements(fi->env, props, "DolbyVisionRPU") > -1) 401 | { 402 | if (d->use_dovi) 403 | { 404 | uint8_t dovi_profile{ 0 }; 405 | const uint8_t* doviRpu{ reinterpret_cast(avs_prop_get_data(fi->env, props, "DolbyVisionRPU", 0, &err)) }; 406 | size_t doviRpuSize{ static_cast(avs_prop_get_data_size(fi->env, props, "DolbyVisionRPU", 0, &err)) }; 407 | 408 | if (doviRpu && doviRpuSize) 409 | { 410 | DoviRpuOpaque* rpu{ dovi_parse_unspec62_nalu(doviRpu, doviRpuSize) }; 411 | const DoviRpuDataHeader* header{ dovi_rpu_get_header(rpu) }; 412 | 413 | if (!header) 414 | { 415 | std::string err{ dovi_rpu_get_error(rpu) }; 416 | dovi_rpu_free(rpu); 417 | return error("libplacebo_Tonemap: failed parsing RPU: " + err); 418 | } 419 | else 420 | { 421 | dovi_profile = header->guessed_profile; 422 | d->dovi_meta = create_dovi_meta(*rpu, *header); 423 | dovi_rpu_free_header(header); 424 | } 425 | 426 | // Profile 5, 7 or 8 mapping 427 | d->src_repr->sys = PL_COLOR_SYSTEM_DOLBYVISION; 428 | d->src_repr->dovi = d->dovi_meta.get(); 429 | 430 | if (dovi_profile == 5) 431 | d->dst_repr->levels = PL_COLOR_LEVELS_FULL; 432 | 433 | // Update mastering display from RPU 434 | if (header->vdr_dm_metadata_present_flag) 435 | { 436 | const DoviVdrDmData* vdr_dm_data{ dovi_rpu_get_vdr_dm_data(rpu) }; 437 | 438 | // Should avoid changing the source black point when mapping to PQ 439 | // As the source image already has a specific black point, 440 | // and the RPU isn't necessarily ground truth on the actual coded values 441 | 442 | // Set target black point to the same as source 443 | if (d->dst_csp == supported_colorspace::CSP_HDR10) 444 | d->dst_pl_csp->hdr.min_luma = d->src_pl_csp->hdr.min_luma; 445 | else 446 | d->src_pl_csp->hdr.min_luma = pl_hdr_rescale(PL_HDR_PQ, PL_HDR_NITS, vdr_dm_data->source_min_pq / 4095.0f); 447 | 448 | d->src_pl_csp->hdr.max_luma = pl_hdr_rescale(PL_HDR_PQ, PL_HDR_NITS, vdr_dm_data->source_max_pq / 4095.0f); 449 | 450 | if (vdr_dm_data->dm_data.level1) 451 | { 452 | const DoviExtMetadataBlockLevel1* l1{ vdr_dm_data->dm_data.level1 }; 453 | d->src_pl_csp->hdr.avg_pq_y = l1->avg_pq / 4095.0f; 454 | d->src_pl_csp->hdr.max_pq_y = l1->max_pq / 4095.0f; 455 | d->src_pl_csp->hdr.scene_avg = pl_hdr_rescale(PL_HDR_PQ, PL_HDR_NITS, l1->avg_pq / 4095.0f); 456 | d->src_pl_csp->hdr.scene_max[0] = d->src_pl_csp->hdr.scene_max[1] = d->src_pl_csp->hdr.scene_max[2] = pl_hdr_rescale(PL_HDR_PQ, PL_HDR_NITS, l1->max_pq / 4095.0f); 457 | } 458 | 459 | if (vdr_dm_data->dm_data.level6) 460 | { 461 | const DoviExtMetadataBlockLevel6* meta{ vdr_dm_data->dm_data.level6 }; 462 | 463 | if (!maxCll || !maxFall) 464 | { 465 | d->src_pl_csp->hdr.max_cll = meta->max_content_light_level; 466 | d->src_pl_csp->hdr.max_fall = meta->max_frame_average_light_level; 467 | } 468 | } 469 | 470 | dovi_rpu_free_vdr_dm_data(vdr_dm_data); 471 | } 472 | 473 | dovi_rpu_free(rpu); 474 | } 475 | else 476 | return error("libplacebo_Tonemap: invlid DolbyVisionRPU frame property!"); 477 | } 478 | } 479 | else 480 | return error("libplacebo_Tonemap: DolbyVisionRPU frame property is required for src_csp=3!"); 481 | } 482 | 483 | pl_color_space_infer_map(d->src_pl_csp.get(), d->dst_pl_csp.get()); 484 | 485 | if (std::lock_guard lck(mtx); tonemap_filter(dst, src, d, fi)) 486 | return error("libplacebo_Tonemap: " + d->vf->log_buffer.str()); 487 | 488 | AVS_Map* dst_props{ avs_get_frame_props_rw(fi->env, dst) }; 489 | avs_prop_set_int(fi->env, dst_props, "_ColorRange", (d->dst_repr->levels == PL_COLOR_LEVELS_FULL) ? 0 : 1, 0); 490 | avs_prop_set_int(fi->env, dst_props, "_Matrix", (d->dst_repr->sys == PL_COLOR_SYSTEM_RGB) ? 0 : map_matrix.at(d->dst_repr->sys), 0); 491 | avs_prop_set_int(fi->env, dst_props, "_Transfer", map_transfer.at(d->dst_pl_csp->transfer), 0); 492 | avs_prop_set_int(fi->env, dst_props, "_Primaries", map_primaries.at(d->dst_pl_csp->primaries), 0); 493 | 494 | if (d->dst_pl_csp->transfer <= PL_COLOR_TRC_ST428) 495 | { 496 | avs_prop_delete_key(fi->env, dst_props, "ContentLightLevelMax"); 497 | avs_prop_delete_key(fi->env, dst_props, "ContentLightLevelAverage"); 498 | avs_prop_delete_key(fi->env, dst_props, "MasteringDisplayMaxLuminance"); 499 | avs_prop_delete_key(fi->env, dst_props, "MasteringDisplayMinLuminance"); 500 | avs_prop_delete_key(fi->env, dst_props, "MasteringDisplayPrimariesX"); 501 | avs_prop_delete_key(fi->env, dst_props, "MasteringDisplayPrimariesY"); 502 | avs_prop_delete_key(fi->env, dst_props, "MasteringDisplayWhitePointX"); 503 | avs_prop_delete_key(fi->env, dst_props, "MasteringDisplayWhitePointY"); 504 | } 505 | else 506 | { 507 | avs_prop_set_float(fi->env, dst_props, "ContentLightLevelMax", d->dst_pl_csp->hdr.max_cll, 0); 508 | avs_prop_set_float(fi->env, dst_props, "ContentLightLevelAverage", d->dst_pl_csp->hdr.max_fall, 0); 509 | avs_prop_set_float(fi->env, dst_props, "MasteringDisplayMaxLuminance", d->dst_pl_csp->hdr.max_luma, 0); 510 | avs_prop_set_float(fi->env, dst_props, "MasteringDisplayMinLuminance", d->dst_pl_csp->hdr.min_luma, 0); 511 | 512 | const std::array prims_x{ d->dst_pl_csp->hdr.prim.red.x, d->dst_pl_csp->hdr.prim.green.x, d->dst_pl_csp->hdr.prim.blue.x }; 513 | const std::arrayprims_y{ d->dst_pl_csp->hdr.prim.red.y, d->dst_pl_csp->hdr.prim.green.y, d->dst_pl_csp->hdr.prim.blue.y }; 514 | 515 | avs_prop_set_float_array(fi->env, dst_props, "MasteringDisplayPrimariesX", prims_x.data(), 3); 516 | avs_prop_set_float_array(fi->env, dst_props, "MasteringDisplayPrimariesY", prims_y.data(), 3); 517 | avs_prop_set_float(fi->env, dst_props, "MasteringDisplayWhitePointX", d->dst_pl_csp->hdr.prim.white.x, 0); 518 | avs_prop_set_float(fi->env, dst_props, "MasteringDisplayWhitePointY", d->dst_pl_csp->hdr.prim.white.y, 0); 519 | } 520 | 521 | if (avs_num_components(&fi->vi) > 3) 522 | avs_bit_blt(fi->env, avs_get_write_ptr_p(dst, AVS_PLANAR_A), avs_get_pitch_p(dst, AVS_PLANAR_A), avs_get_read_ptr_p(src, AVS_PLANAR_A), avs_get_pitch_p(src, AVS_PLANAR_A), 523 | avs_get_row_size_p(src, AVS_PLANAR_A), avs_get_height_p(src, AVS_PLANAR_A)); 524 | 525 | avs_release_video_frame(src); 526 | 527 | return dst; 528 | } 529 | 530 | static void AVSC_CC free_tonemap(AVS_FilterInfo* fi) 531 | { 532 | tonemap* d{ reinterpret_cast(fi->user_data) }; 533 | 534 | if (d->render_params->lut) 535 | pl_lut_free(const_cast(&d->render_params->lut)); 536 | 537 | avs_libplacebo_uninit(d->vf); 538 | delete d; 539 | } 540 | 541 | static int AVSC_CC tonemap_set_cache_hints(AVS_FilterInfo* fi, int cachehints, int frame_range) 542 | { 543 | return cachehints == AVS_CACHE_GET_MTMODE ? 2 : 0; 544 | } 545 | 546 | AVS_Value AVSC_CC create_tonemap(AVS_ScriptEnvironment* env, AVS_Value args, void* param) 547 | { 548 | enum 549 | { 550 | Clip, Src_csp, Dst_csp, Src_max, Src_min, Dst_max, Dst_min, Dynamic_peak_detection, Smoothing_period, 551 | Scene_threshold_low, Scene_threshold_high, Percentile, Black_cutoff, Gamut_mapping_mode, Tone_mapping_function, 552 | Tone_constants, Metadata, Contrast_recovery, Contrast_smoothness, Visualize_lut, Show_clipping, Use_dovi, 553 | Device, List_device, Cscale, Lut, Lut_type, Dst_prim, Dst_trc, Dst_sys 554 | }; 555 | 556 | AVS_FilterInfo* fi; 557 | AVS_Clip* clip{ avs_new_c_filter(env, &fi, avs_array_elt(args, Clip), 1) }; 558 | 559 | tonemap* params{ new tonemap() }; 560 | const int srcIsRGB{ avs_is_rgb(&fi->vi) }; 561 | 562 | AVS_Value avs_ver{ avs_version(params->msg, "libplacebo_Tonemap", env) }; 563 | if (avs_is_error(avs_ver)) 564 | return avs_ver; 565 | 566 | if (!avs_is_planar(&fi->vi)) 567 | return set_error(clip, "libplacebo_Tonemap: clip must be in planar format.", nullptr); 568 | if (avs_bits_per_component(&fi->vi) != 16) 569 | return set_error(clip, "libplacebo_Tonemap: bit depth must be 16-bit.", nullptr); 570 | if (avs_num_components(&fi->vi) < 3) 571 | return set_error(clip, "libplacebo_Tonemap: the clip must have at least three planes.", nullptr); 572 | 573 | const int device{ avs_defined(avs_array_elt(args, Device)) ? avs_as_int(avs_array_elt(args, Device)) : -1 }; 574 | const int list_device{ avs_defined(avs_array_elt(args, List_device)) ? avs_as_bool(avs_array_elt(args, List_device)) : 0 }; 575 | 576 | if (list_device || device > -1) 577 | { 578 | std::vector devices{}; 579 | VkInstance inst{}; 580 | 581 | AVS_Value dev_info{ devices_info(clip, fi->env, devices, inst, params->msg, "libplacebo_Tonemap", device, list_device) }; 582 | if (avs_is_error(dev_info) || avs_is_clip(dev_info)) 583 | return dev_info; 584 | 585 | params->vf = avs_libplacebo_init(devices[device], params->msg); 586 | 587 | vkDestroyInstance(inst, nullptr); 588 | } 589 | else 590 | { 591 | if (device < -1) 592 | return set_error(clip, "libplacebo_Tonemap: device must be greater than or equal to -1.", nullptr); 593 | 594 | params->vf = avs_libplacebo_init(nullptr, params->msg); 595 | } 596 | 597 | if (params->msg.size()) 598 | { 599 | params->msg = "libplacebo_Tonemap: " + params->msg; 600 | return set_error(clip, params->msg.c_str(), nullptr); 601 | } 602 | 603 | params->src_pl_csp = std::make_unique(); 604 | params->src_csp = static_cast(avs_defined(avs_array_elt(args, Src_csp)) ? avs_as_int(avs_array_elt(args, Src_csp)) : 1); 605 | if (params->src_csp == supported_colorspace::CSP_DOVI && srcIsRGB) 606 | return set_error(clip, "libplacebo_Tonemap: Dolby Vision source colorspace must be a YUV clip!", params->vf); 607 | 608 | switch (params->src_csp) 609 | { 610 | case supported_colorspace::CSP_SDR: *params->src_pl_csp = pl_color_space_bt709; break; 611 | case supported_colorspace::CSP_HDR10: 612 | case supported_colorspace::CSP_DOVI: *params->src_pl_csp = pl_color_space_hdr10; break; 613 | case supported_colorspace::CSP_HLG: *params->src_pl_csp = pl_color_space_bt2020_hlg; break; 614 | default: return set_error(clip, "libplacebo_Tonemap: Invalid source colorspace for tonemapping.", params->vf); 615 | } 616 | 617 | params->dst_pl_csp = std::make_unique(); 618 | 619 | const int dst_prim_defined{ avs_defined(avs_array_elt(args, Dst_prim)) }; 620 | const int dst_trc_defined{ avs_defined(avs_array_elt(args, Dst_trc)) }; 621 | if (dst_prim_defined && dst_trc_defined) 622 | { 623 | const int dst_prim{ avs_as_int(avs_array_elt(args, Dst_prim)) }; 624 | const int dst_trc{ avs_as_int(avs_array_elt(args, Dst_trc)) }; 625 | 626 | if (dst_prim < 1 || dst_prim > 17) 627 | return set_error(clip, "libplacebo_Tonemap: dst_prim must be between 1 and 17.", params->vf); 628 | if (dst_trc < 1 || dst_trc > 16) 629 | return set_error(clip, "libplacebo_Tonemap: dst_trc must be between 1 and 16.", params->vf); 630 | 631 | params->dst_pl_csp->primaries = static_cast(dst_prim); 632 | params->dst_pl_csp->transfer = static_cast(dst_trc); 633 | } 634 | else if (!dst_prim_defined && !dst_trc_defined) 635 | { 636 | params->dst_csp = static_cast(avs_defined(avs_array_elt(args, Dst_csp)) ? avs_as_int(avs_array_elt(args, Dst_csp)) : 0); 637 | switch (params->dst_csp) 638 | { 639 | case supported_colorspace::CSP_SDR: *params->dst_pl_csp = pl_color_space_bt709; break; 640 | case supported_colorspace::CSP_HDR10: *params->dst_pl_csp = pl_color_space_hdr10; break; 641 | case supported_colorspace::CSP_HLG: *params->dst_pl_csp = pl_color_space_bt2020_hlg; break; 642 | default: return set_error(clip, "libplacebo_Tonemap: Invalid target colorspace for tonemapping.", params->vf); 643 | } 644 | } 645 | else 646 | return set_error(clip, "libplacebo_Tonemap: dst_prim/dst_trc must be defined.", params->vf); 647 | 648 | const int lut_defined{ avs_defined(avs_array_elt(args, Lut)) }; 649 | 650 | if (lut_defined) 651 | { 652 | params->render_params = std::make_unique(); 653 | 654 | const char* lut_path{ avs_as_string(avs_array_elt(args, Lut)) }; 655 | FILE* lut_file{ nullptr }; 656 | 657 | #ifdef _WIN32 658 | const int required_size{ MultiByteToWideChar(CP_UTF8, 0, lut_path, -1, nullptr, 0) }; 659 | std::wstring wbuffer(required_size, 0); 660 | MultiByteToWideChar(CP_UTF8, 0, lut_path, -1, wbuffer.data(), required_size); 661 | lut_file = _wfopen(wbuffer.c_str(), L"rb"); 662 | if (!lut_file) 663 | { 664 | const int req_size{ MultiByteToWideChar(CP_ACP, 0, lut_path, -1, nullptr, 0) }; 665 | std::wstring wbuffer(req_size, 0); 666 | MultiByteToWideChar(CP_ACP, 0, lut_path, -1, wbuffer.data(), req_size); 667 | lut_file = _wfopen(wbuffer.c_str(), L"rb"); 668 | } 669 | #else 670 | lut_file = std::fopen(lut_path, "rb"); 671 | #endif 672 | if (!lut_file) 673 | { 674 | params->msg = "libplacebo_Tonemap: error opening file " + std::string(lut_path) + " (" + std::strerror(errno) + ")"; 675 | return set_error(clip, params->msg.c_str(), params->vf); 676 | } 677 | if (std::fseek(lut_file, 0, SEEK_END)) 678 | { 679 | std::fclose(lut_file); 680 | params->msg = "libplacebo_Tonemap: error seeking to the end of file " + std::string(lut_path) + " (" + std::strerror(errno) + ")"; 681 | return set_error(clip, params->msg.c_str(), params->vf); 682 | } 683 | const long lut_size{ std::ftell(lut_file) }; 684 | if (lut_size == -1) 685 | { 686 | std::fclose(lut_file); 687 | params->msg = "libplacebo_Tonemap: error determining the size of file " + std::string(lut_path) + " (" + std::strerror(errno) + ")"; 688 | return set_error(clip, params->msg.c_str(), params->vf); 689 | } 690 | 691 | std::rewind(lut_file); 692 | 693 | std::string bdata; 694 | bdata.resize(lut_size); 695 | std::fread(bdata.data(), 1, lut_size, lut_file); 696 | bdata[lut_size] = '\0'; 697 | 698 | std::fclose(lut_file); 699 | 700 | params->render_params->lut = pl_lut_parse_cube(nullptr, bdata.c_str(), bdata.size()); 701 | if (!params->render_params->lut) 702 | return set_error(clip, "libplacebo_Tonemap: failed lut parsing.", params->vf); 703 | 704 | const int lut_type{ (avs_defined(avs_array_elt(args, Lut_type))) ? avs_as_int(avs_array_elt(args, Lut_type)) : 3 }; 705 | if (lut_type < 1 || lut_type > 3) 706 | { 707 | pl_lut_free(const_cast(¶ms->render_params->lut)); 708 | return set_error(clip, "libplacebo_Tonemap: lut_type must be between 1 and 3.", params->vf); 709 | } 710 | 711 | params->render_params->lut_type = static_cast(lut_type); 712 | } 713 | else 714 | { 715 | if (params->src_csp == supported_colorspace::CSP_DOVI) 716 | params->dovi_meta = std::make_unique(); 717 | 718 | params->colorMapParams = std::make_unique(pl_color_map_default_params); 719 | 720 | // Tone mapping function 721 | params->colorMapParams->tone_mapping_function = pl_find_tone_map_function(avs_defined(avs_array_elt(args, Tone_mapping_function)) ? avs_as_string(avs_array_elt(args, Tone_mapping_function)) : "bt2390"); 722 | if (!params->colorMapParams->tone_mapping_function) 723 | return set_error(clip, "libplacebo_Tonemap: wrong tone_mapping_function.", params->vf); 724 | 725 | if (avs_defined(avs_array_elt(args, Tone_constants))) 726 | { 727 | constexpr std::array constants_list 728 | { 729 | "knee_adaptation", 730 | "knee_minimum", 731 | "knee_maximum", 732 | "knee_default", 733 | "knee_offset", 734 | "slope_tuning", 735 | "slope_offset", 736 | "spline_contrast", 737 | "reinhard_contrast", 738 | "linear_knee", 739 | "exposure" 740 | }; 741 | 742 | constexpr std::array>, 11> constants_array 743 | { 744 | std::make_pair(constants_list[0], std::make_tuple(&pl_tone_map_constants::knee_adaptation, 0.0f, 1.0f)), 745 | std::make_pair(constants_list[1], std::make_tuple(&pl_tone_map_constants::knee_minimum, 0.0f, 0.5f)), 746 | std::make_pair(constants_list[2], std::make_tuple(&pl_tone_map_constants::knee_maximum, 0.5f, 1.0f)), 747 | std::make_pair(constants_list[3], std::make_tuple(&pl_tone_map_constants::knee_default, 0.0f, 1.0f)), 748 | std::make_pair(constants_list[4], std::make_tuple(&pl_tone_map_constants::knee_offset, 0.5f, 2.0f)), 749 | std::make_pair(constants_list[5], std::make_tuple(&pl_tone_map_constants::slope_tuning, 0.0f, 10.0f)), 750 | std::make_pair(constants_list[6], std::make_tuple(&pl_tone_map_constants::slope_offset, 0.0f, 1.0f)), 751 | std::make_pair(constants_list[7], std::make_tuple(&pl_tone_map_constants::spline_contrast, 0.0f, 1.5f)), 752 | std::make_pair(constants_list[8], std::make_tuple(&pl_tone_map_constants::reinhard_contrast, 0.0f, 1.0f)), 753 | std::make_pair(constants_list[9], std::make_tuple(&pl_tone_map_constants::linear_knee, 0.0f, 1.0f)), 754 | std::make_pair(constants_list[10], std::make_tuple(&pl_tone_map_constants::exposure, 0.0f, 10.0f)) 755 | }; 756 | 757 | constexpr auto constants_map{ Map, 11 >{ { constants_array } } }; 758 | 759 | const int constants_size{ avs_array_size(avs_array_elt(args, Tone_constants)) }; 760 | if (constants_size > 11) 761 | return set_error(clip, "libplacebo_Tonemap: tone_constants must be equal to or less than 11.", params->vf); 762 | 763 | for (int i{ 0 }; i < constants_size; ++i) 764 | { 765 | std::string constants{ avs_as_string(*(avs_as_array(avs_array_elt(args, Tone_constants)) + i)) }; 766 | transform(constants.begin(), constants.end(), constants.begin(), [](unsigned char c) { return std::tolower(c); }); 767 | 768 | std::regex reg("(\\w+)=(\\d+(?:\\.\\d+)?)"); 769 | std::smatch match; 770 | if (!std::regex_match(constants.cbegin(), constants.cend(), match, reg)) 771 | return set_error(clip, "libplacebo_Tonemap: regex failed parsing tone_constants.", params->vf); 772 | if (std::find(std::begin(constants_list), std::end(constants_list), match[1].str()) == std::end(constants_list)) 773 | { 774 | params->msg = "libplacebo_Tonemap: wrong tone_constant " + match[1].str() + "."; 775 | return set_error(clip, params->msg.c_str(), params->vf); 776 | } 777 | 778 | const float constant_value{ std::stof(match[2].str()) }; 779 | if (constant_value < std::get<1>(constants_map.at(match[1].str())) || constant_value > std::get<2>(constants_map.at(match[1].str()))) 780 | { 781 | params->msg = "libplacebo_Tonemap: " + match[1].str() + " must be between " + std::to_string(std::get<1>(constants_map.at(match[1].str()))) + 782 | ".." + std::to_string(std::get<2>(constants_map.at(match[1].str()))) + "."; 783 | return set_error(clip, params->msg.c_str(), params->vf); 784 | } 785 | 786 | params->colorMapParams->tone_constants.*std::get<0>(constants_map.at(match[1].str())) = constant_value; 787 | } 788 | } 789 | if (avs_defined(avs_array_elt(args, Gamut_mapping_mode))) 790 | { 791 | params->colorMapParams->gamut_mapping = pl_find_gamut_map_function(avs_as_string(avs_array_elt(args, Gamut_mapping_mode))); 792 | if (!params->colorMapParams->gamut_mapping) 793 | return set_error(clip, "libplacebo_Tonemap: wrong gamut_mapping_mode.", params->vf); 794 | } 795 | if (avs_defined(avs_array_elt(args, Metadata))) 796 | params->colorMapParams->metadata = static_cast(avs_as_int(avs_array_elt(args, Metadata))); 797 | if (avs_defined(avs_array_elt(args, Visualize_lut))) 798 | params->colorMapParams->visualize_lut = avs_as_bool(avs_array_elt(args, Visualize_lut)); 799 | if (avs_defined(avs_array_elt(args, Show_clipping))) 800 | params->colorMapParams->show_clipping = avs_as_bool(avs_array_elt(args, Show_clipping)); 801 | 802 | params->colorMapParams->contrast_recovery = (avs_defined(avs_array_elt(args, Contrast_recovery))) ? avs_as_float(avs_array_elt(args, Contrast_recovery)) : 0.30f; 803 | params->colorMapParams->contrast_smoothness = (avs_defined(avs_array_elt(args, Contrast_smoothness))) ? avs_as_float(avs_array_elt(args, Contrast_smoothness)) : 3.5f; 804 | 805 | if (params->colorMapParams->contrast_recovery < 0.0f) 806 | return set_error(clip, "libplacebo_Tonemap: contrast_recovery must be equal to or greater than 0.0f.", params->vf); 807 | if (params->colorMapParams->contrast_smoothness < 0.0f) 808 | return set_error(clip, "libplacebo_Tonemap: contrast_smoothness must be equal to or greater than 0.0f.", params->vf); 809 | 810 | params->peakDetectParams = std::make_unique(pl_peak_detect_default_params); 811 | if (avs_defined(avs_array_elt(args, Smoothing_period))) 812 | params->peakDetectParams->smoothing_period = avs_as_float(avs_array_elt(args, Smoothing_period)); 813 | if (avs_defined(avs_array_elt(args, Scene_threshold_low))) 814 | params->peakDetectParams->scene_threshold_low = avs_as_float(avs_array_elt(args, Scene_threshold_low)); 815 | if (avs_defined(avs_array_elt(args, Scene_threshold_high))) 816 | params->peakDetectParams->scene_threshold_high = avs_as_float(avs_array_elt(args, Scene_threshold_high)); 817 | if (avs_defined(avs_array_elt(args, Percentile))) 818 | params->peakDetectParams->percentile = avs_as_float(avs_array_elt(args, Percentile)); 819 | if (avs_defined(avs_array_elt(args, Black_cutoff))) 820 | params->peakDetectParams->black_cutoff = avs_as_float(avs_array_elt(args, Black_cutoff)); 821 | 822 | if (avs_defined(avs_array_elt(args, Src_max))) 823 | { 824 | params->original_src_max = avs_as_float(avs_array_elt(args, Src_max)); 825 | params->src_pl_csp->hdr.max_luma = params->original_src_max; 826 | } 827 | if (avs_defined(avs_array_elt(args, Src_min))) 828 | { 829 | params->original_src_min = avs_as_float(avs_array_elt(args, Src_min)); 830 | params->src_pl_csp->hdr.min_luma = params->original_src_min; 831 | } 832 | 833 | if (avs_defined(avs_array_elt(args, Dst_max))) 834 | params->dst_pl_csp->hdr.max_luma = avs_as_float(avs_array_elt(args, Dst_max)); 835 | if (avs_defined(avs_array_elt(args, Dst_min))) 836 | params->dst_pl_csp->hdr.min_luma = avs_as_float(avs_array_elt(args, Dst_min)); 837 | 838 | const int peak_detection{ avs_defined(avs_array_elt(args, Dynamic_peak_detection)) ? avs_as_bool(avs_array_elt(args, Dynamic_peak_detection)) : 1 }; 839 | params->use_dovi = avs_defined(avs_array_elt(args, Use_dovi)) ? avs_as_bool(avs_array_elt(args, Use_dovi)) : params->src_csp == supported_colorspace::CSP_DOVI; 840 | 841 | params->render_params = std::make_unique(pl_render_default_params); 842 | params->render_params->color_map_params = params->colorMapParams.get(); 843 | params->render_params->peak_detect_params = (peak_detection) ? params->peakDetectParams.get() : nullptr; 844 | params->render_params->sigmoid_params = &pl_sigmoid_default_params; 845 | params->render_params->dither_params = &pl_dither_default_params; 846 | params->render_params->cone_params = nullptr; 847 | params->render_params->color_adjustment = nullptr; 848 | params->render_params->deband_params = nullptr; 849 | } 850 | 851 | const pl_filter_config* cscaler{ pl_find_filter_config((avs_defined(avs_array_elt(args, Cscale))) ? avs_as_string(avs_array_elt(args, Cscale)) : "spline36", PL_FILTER_UPSCALING) }; 852 | if (!cscaler) 853 | { 854 | if (lut_defined) 855 | pl_lut_free(const_cast(¶ms->render_params->lut)); 856 | 857 | return set_error(clip, "libplacebo_Tonemap: not a valid cscale.", params->vf); 858 | } 859 | 860 | params->render_params->plane_upscaler = cscaler; 861 | 862 | if (srcIsRGB) 863 | params->is_subsampled = 0; 864 | else 865 | params->is_subsampled = avs_get_plane_width_subsampling(&fi->vi, AVS_PLANAR_U) | avs_get_plane_height_subsampling(&fi->vi, AVS_PLANAR_U); 866 | 867 | params->src_repr = std::make_unique(); 868 | params->src_repr->bits.sample_depth = 16; 869 | params->src_repr->bits.color_depth = 16; 870 | params->src_repr->bits.bit_shift = 0; 871 | 872 | params->dst_repr = std::make_unique< pl_color_repr>(); 873 | params->dst_repr->bits.sample_depth = 16; 874 | params->dst_repr->bits.color_depth = 16; 875 | params->dst_repr->bits.bit_shift = 0; 876 | params->dst_repr->alpha = PL_ALPHA_PREMULTIPLIED; 877 | 878 | if (!srcIsRGB) 879 | { 880 | params->src_repr->sys = PL_COLOR_SYSTEM_BT_2020_NC; 881 | params->dst_repr->levels = PL_COLOR_LEVELS_LIMITED; 882 | 883 | if (dst_prim_defined && avs_defined(avs_array_elt(args, Dst_sys))) 884 | { 885 | const int dst_sys{ avs_as_int(avs_array_elt(args, Dst_sys)) }; 886 | if (dst_sys < 1 || dst_sys > 9) 887 | { 888 | if (lut_defined) 889 | pl_lut_free(const_cast(¶ms->render_params->lut)); 890 | 891 | return set_error(clip, "libplacebo_Tonemap: dst_sys must be between 1 and 9.", params->vf); 892 | } 893 | 894 | params->dst_repr->sys = static_cast(dst_sys); 895 | } 896 | else 897 | { 898 | switch (params->dst_pl_csp->transfer) 899 | { 900 | case PL_COLOR_TRC_BT_1886: 901 | case PL_COLOR_TRC_SRGB: 902 | case PL_COLOR_TRC_LINEAR: 903 | case PL_COLOR_TRC_GAMMA18: 904 | case PL_COLOR_TRC_GAMMA20: 905 | case PL_COLOR_TRC_GAMMA22: 906 | case PL_COLOR_TRC_GAMMA24: 907 | case PL_COLOR_TRC_GAMMA26: 908 | case PL_COLOR_TRC_GAMMA28: 909 | case PL_COLOR_TRC_PRO_PHOTO: 910 | case PL_COLOR_TRC_ST428: params->dst_repr->sys = PL_COLOR_SYSTEM_BT_709; break; 911 | case PL_COLOR_TRC_PQ: 912 | case PL_COLOR_TRC_HLG: 913 | case PL_COLOR_TRC_V_LOG: 914 | case PL_COLOR_TRC_S_LOG1: 915 | case PL_COLOR_TRC_S_LOG2: params->dst_repr->sys = PL_COLOR_SYSTEM_BT_2020_NC; break; 916 | } 917 | } 918 | 919 | fi->vi.pixel_type = AVS_CS_YUV444P16; 920 | } 921 | else 922 | { 923 | params->src_repr->sys = PL_COLOR_SYSTEM_RGB; 924 | 925 | params->dst_repr->levels = PL_COLOR_LEVELS_FULL; 926 | params->dst_repr->sys = PL_COLOR_SYSTEM_RGB; 927 | } 928 | 929 | AVS_Value v{ avs_new_value_clip(clip) }; 930 | 931 | fi->user_data = reinterpret_cast(params); 932 | fi->get_frame = tonemap_get_frame; 933 | fi->set_cache_hints = tonemap_set_cache_hints; 934 | fi->free_filter = free_tonemap; 935 | 936 | avs_release_clip(clip); 937 | 938 | return v; 939 | } 940 | --------------------------------------------------------------------------------