mpv-player / mpv

🎥 Command line video player
https://mpv.io
Other
28.04k stars 2.88k forks source link

Event for when a Lua script is loaded/removed due to auto profile #14240

Closed CrendKing closed 4 months ago

CrendKing commented 4 months ago

Expected behavior of the wanted feature

Suppose I have the auto prifle:

[conditional_hwdec]
profile-cond=speed > 1
profile-restore=copy-equal
scripts-append=may_enable_hwdec.lua

and Lua script

local proc_ret = mp.command_native({
    name = 'subprocess',
    capture_stdout = true,
    args = {'hwdec_speed_test')},
})
if proc_ret.status == 0 and proc_test.stdout == 'yes' then
    mp.commandv('set', 'hwdec', 'auto')
end

When the playback speed increases, the Lua script may turn on hwdec depending on some external factor (that's why the script is needed). However, when the speed drops back to 1, the script does not have a mechanism to know that it is removed by the auto profile. The script makes side effect but no easy way to clean it up.

Alternative behavior of the wanted feature

Currently the workaround I come up with is to observe the scripts property change, which is ugly:

local this_script_path = debug.getinfo(1, 'S').source:sub(2)

mp.observe_property('scripts', 'native', function(name, scripts)
    for i = 1, #scripts do
        if scripts[i] == this_script_path then
            -- script is (re-)loaded 
            return
        end
    end

    -- cleanup here
end)

Imagine this could become as simple as

-- only the unloaded script receives this event
mp.register_event('script_change', function(is_loaded)
    -- code
end)

This is possible because even the script is removed from scripts, the script itself will keep running until the player terminates.

Log File

No response

Sample Files

No response

guidocella commented 4 months ago

scripts-append doesn't work at all at runtime, hence the load-script command. You should observe speed in your script instead of loading it and unloading it.

CrendKing commented 4 months ago

scripts-append doesn't work at all at runtime

Oops. You are right. I have a script that observe scripts changes at runtime and call load-script. I forgot I had it.

Sorry about this.

guidocella commented 4 months ago

For what it's worth you can now do input-commands=load-script foo.lua, but it's still better to modify your script because that loads another instance of the script everytime the condition becomes true.