Second Lua script for mpv resolution & quality output when using YTFZF searches

Share part of my personal project for the YTZF youtube searching tool (from terminal in Mabox when you look for youtube vids/music by typing: ytfzf -t your query) so as to have youtube or other similar music/video streams display playing in mpv player.

Problem: whenever you use from terminal ytfzf (using also ytdlp) to search for & play youtube videos… you can’t get a specific resolution quality or size simply, cause you need to tweak or be savy of tricks to modify mpv settings or ytdlp settings after a long google search trip.

So what if you could add to your mpv’s folder named as scripts (/home/mabox/.config/mpv/scripts) a simply 81 lines lua script to preset the resolution quality & sizing to be displayed by mpv output whenever you use ytfzf as youtube searches.

You don’t need extra packages to add to Mabox, all dependencies are installed by default.
You just need to add this 85 lines lua script in the mpv’s scripts folder, or add this scripts folder in case you don’t have it created in /home/mabox/.config/mpv/.
Maybe you already created this folder for my previous lua script (notify-lua), if so just add this new one accompanying notify-lua script as shown in this picture: https://i.imgur.com/QNiP1Ew.png

I named this new script as ytfzfmpvsetting.lua if you want to keep the same name.
There are important information 13 lines to check at the beginning of this new script with sections which can be modified by the user at one’s taste. Please read them.


I have incorporated some new stream sources between lines 23-24 after a month testing the script as requested by some testing guys team ( youtu.be, twitch.tv, yewtu.be) so as to get more choices to find your musical video queries.
https://i.imgur.com/hJ06uFm.png

I have preset this new script with the smallest quality resolution (240) set as default. In case you want to modify it , follow the instructions inside the info script file lines after Options.


Finally, if you don’t know much of lua scripting I recommend that you keep the rest of this script as it is to have it functional for your system.
Copy all lines from the script below and paste it in a new file named ytfzfmpvsettings.lua inside /home/mabox/.config/mpv/scripts in you Mabox OS
Have fun & good luck.

--[[
- Part of personal video project in November-December 2022, Nick0bre Chile shared for Maboxlinux users. Maboxlinux.org Forum.
Mpv lua script to automatically change ytdl-format (for yt-dlp) when using/running ytfzf script from terminal (e.g. ytfzf -t The Beatles / e.g. ytfzf
 -m The Rolling Stones, so as to watch/listen Youtube tunes/channels from Mpv player & presetting your best resolution manually).

Options:
- To add more domains, simply add them to the StreamSource set between 'xxx.com' & separated by a comma excepting for the last domain added in line 24.
- To adjust quality, edit local changedQuality value in line 28 from the options stated above in line 27 (240, 360, 480, 720, 1080, 1440, or 2160).
- It is recommended to set VP9 codec as false to keep video framerate solid & running most of the time. But if you want to enable VP9 codec, 
change enableVP9 to true in line 31.
- To change frame rate, adjust FPSLimit in line 32 at your own risk, default is 30 & works great.
- I recommend to keep the rest of this script as it is so as to have it 100% functional, in case you have not used/ or worked lua scripting before.
--]]

local function Set (t)
	local set = {}
	for _, v in pairs(t) do set[v] = true end
	return set
end

-- Domains list for custom quality
local StreamSource = Set {
	'youtu.be', 'youtube.com', 'www.youtube.com', 
	'twitch.tv', 'yewtu.be', 'www.twitch.tv'
}

-- Accepts: (240, 360, 480, 720, 1080, 1440, 2160) ( The smallest quality is set as deafult now)
local changedQuality = 240

-- Affects matched and non-matched domains
local enableVP9 = false
local FPSLimit = 30

-- Do not edit from here on
local msg = require 'mp.msg'
local utils = require 'mp.utils'

local VP9value = ""

if enableVP9 == false then
	VP9value = "[vcodec!=?vp9]"
end

local ytdlChange = "bestvideo[height<=?"..changedQuality.."][fps<=?"..FPSLimit.."]"..VP9value.."+bestaudio/best[height<="..changedQuality.."]"
local ytdlDefault = "bestvideo[fps<=?"..FPSLimit.."]"..VP9value.."+bestaudio/best"

local function getStreamSource(path)
	local hostname = path:match '^%a+://([^/]+)/' or ''
	return hostname:match '([%w%.]+%w+)$'
end

local function ytdlAutoChange(name, value)
	local path = value

	if StreamSource[getStreamSource(string.lower(path))] then
		mp.set_property("ytdl-format", ytdlChange)
		msg.info("Domain match found, ytdl-format has been changed.")
		msg.info("Changed ytdl-format: "..mp.get_property("ytdl-format"))
	else
		msg.info("No domain match, ytdl-format unchanged.")
	end

	mp.unobserve_property(ytdlAutoChange)
	msg.info("Finished check, script no longer running.")
end

local function ytdlCheck()
	local path = mp.get_property("path", "")
	
	if string.match(string.lower(path), "^(%a+://)") then
		mp.set_property("ytdl-format", ytdlDefault)
		msg.info("Current ytdl-format: "..mp.get_property("ytdl-format"))
		
		mp.observe_property("path", "string", ytdlAutoChange)
		msg.info("Observing path to determine ytdlAutoChange status...")
	else
		msg.info("Not a URL/Stream, script did not run.")
	end
end

mp.register_event("start-file", ytdlCheck)
2 Likes

excellent I have since yesterday solving some details
which apparently I have no idea how to solve


aqui me muestra la linea de error

1 Like

No pude reproducir tu error aqui y seleccione el mismo episodio / I could not reproduce the same error you showed in your report. Sorry Everardo. Todo bien aquí. Please check maybe you added some extra in the script lines.

pues yo tambien estoy asi desconsertado si todo lo hice alpie del tutorial / Well, I am also confused if I did everything at the bottom of the tutorial

Thanks I could see what you meant…there were extra lines at the end…lines were deleted.
Gracias Pude darme cuenta de esas lineas extras ya las borre. :face_with_hand_over_mouth:

1 Like


era esa linea que estaba de mas pero es sencilla la solución / It was that line that was unnecessary but the solution is simple

1 Like

Excellent! That worked perfectly. I didn’t bother to look into LUA scripts yet because I thought they might be quite a hassle and I’m a bit overwhelmed by all the options available in mpv.
But that was super easy. Playback with 240p runs nice. However, I got an error from mpv which might have more to do with my hardware or my hardware-decoding. Is it possible that the script overrides the settings in mpv.conf?

Here is the output:

[ytfzfmpvsettings] Current ytdl-format: bestvideo[fps<=?30][vcodec!=?vp9]+bestaudio/best 
[ytfzfmpvsettings] Observing path to determine ytdlAutoChange status... 
[ytfzfmpvsettings] Domain match found, ytdl-format has been changed. 
[ytfzfmpvsettings] Changed ytdl-format: bestvideo[height<=?240][fps<=?30][vcodec!=?vp9]+bestaudio/best[height<=240] 
[ytfzfmpvsettings] Finished check, script no longer running. 
 (+) Video --vid=1 (*) (h264 426x240 25.000fps)
 (+) Audio --aid=1 --alang=eng (*) (opus 2ch 48000Hz)
File tags:
 Uploader: Shybits
 Channel_URL: https://www.youtube.com/channel/UC3ik4h-bY20b_jJnFN2yMpA
Cannot load libcuda.so.1
[ffmpeg] AVHWDeviceContext: Cannot load libcuda.so.1
[ffmpeg] AVHWDeviceContext: Could not dynamically load CUDA
Failed to open VDPAU backend libvdpau_va_gl.so: cannot open shared object file: No such file or directory
AO: [pulse] 48000Hz stereo 2ch float
VO: [gpu] 426x240 yuv420p
Title: Shybits - Neighbours (Official Video)
AV: 00:00:03 / 00:02:45 (2%) A-V:  0.000 Cache: 161s/12MB

Audio/Video desynchronisation detected! Possible reasons include too slow
hardware, temporary CPU spikes, broken drivers, and broken files. Audio
position will not match to the video (see A-V status field).

AV: 00:02:45 / 00:02:45 (100%) A-V:  0.000 Dropped: 21 Cache: 0.0s

Here’s my mpv.conf. The hardware decoder in video settings worked nice before, but I don’t now anything about hardware decoding or what these options really mean :sweat_smile: .

        # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
        #                                                                       #
        #   888b     d8888888888b. 888     888                          .d888   #
        #   8888b   d8888888   Y88b888     888                         d88P"    #
        #   88888b.d88888888    888888     888                         888      #
        #   888Y88888P888888   d88PY88b   d88P  .d8888b .d88b. 88888b. 888888   #
        #   888 Y888P 8888888888P"  Y88b d88P  d88P"   d88""88b888 "88b888      #
        #   888  Y8P  888888         Y88o88P   888     888  888888  888888      #
        #   888   "   888888          Y888P d8bY88b.   Y88..88P888  888888      #
        #   888       888888           Y8P  Y8P "Y8888P "Y88P" 888  888888      #
        #                                                                       #
        # # MPV-Config, stefan - Dec 03, 2022, 22:31:12 # # # # # # # # # # # # #



#  Der Befehl 'mpv --list-options | less' zeigt alle verfügbaren Optionen für MPV an.
#+ Diese können hier ohne '--' am Anfang und mit '=' und dem dazugehörigen Wert eingefügt
#+ werden.
#+ Mit 'man mpv' kann das Handbuch angesehen werden, welches übersichtlicher auf
#+ https://mpv.io/manual/master zu finden ist.

#  Zeilen mit '#' am Anfang werden von MPV nicht mitgelesen. So können auch Optionen deakti-
#+ viert und durch entfernen von '#' reaktiviert, sowie Kommentare hinzugefügt werden.



                                    ##################
                                    # video settings #
                                    ##################


#  Ein neues Videofenster nimmt maximal n% des Bildschirms ein, auch wenn das Videoformat
#+ die Bildschirmauflösung überschreitet.
autofit-larger=90%x90%

#  Startet das Videofenster sofort, ohne auf den Videostream zu warten.
#+ Andere Werte: 'no' (default), 'yes'
force-window=no

# Legt fest ob das Videofenster im Vordergrund geöffnet wird, oder nicht ('no'/'yes')
focus-on-open=no


hwdec=auto-safe
#hwdec=auto
#hwdec=no
#hwdec=vaapi


                                    ##################
                                    # audio settings #
                                    ##################



                                    ##################
                                    # other settings #
                                    ##################


#  Zeigt beim Abspielen von MPV im Terminal den Titel eines Internet-Streams an.
#+ Besonders nützlich, wenn mit der Option --no-video nur der Audiostream wiedergegeben wird.
term-playing-msg='Title: ${media-title}'

#  Zielordner für Screenshots und Format (jpg jpeg png webp)
screenshot-directory=/home/stefan2/Bilder/Video-screenshots
screenshot-format=png

#  Namenskonvention für Screenshots. Standard ist: 'mpv-shot%n'.
#+ Im MPV-Manual werden alle Optionen beschrieben: https://mpv.io/manual/master/#screenshot
#screenshot-template=mpv-%F-%P
screenshot-template=mpv-%{media-title}-%P



                                    ############
                                    # Profiles #
                                    ############

# The options declared as part of profiles override global default settings,
# but only take effect when the profile is active.
# mpv --profile=xyz

[pyradio]
volume=100

[audio]
video=no
force-window=no

Thanks!

1 Like