fresh init
This commit is contained in:
1 parent
13b961f148
commit
d50317cdcf
166 files changed
+30282
No files matched your search
@@ -0,0 +1,13 @@
|
||||
local mp = require "mp"
|
||||
|
||||
local function set_clipboard(text)
|
||||
os.execute("echo -n "..text.." | xclip -selection clipboard")
|
||||
end
|
||||
|
||||
local function copy_path()
|
||||
local path_url = mp.get_property("path")
|
||||
mp.osd_message(string.format("Copied to Clipboard: %s", path_url))
|
||||
set_clipboard(path_url)
|
||||
end
|
||||
|
||||
mp.add_key_binding("y-p", "copy_path", copy_path)
|
||||
@@ -0,0 +1,38 @@
|
||||
-- Allow changing a property with by zoom-adjusted amount
|
||||
function zoom_invariant_add(prop, amt)
|
||||
amt = amt / 2 ^ mp.get_property_number("video-zoom")
|
||||
mp.set_property_number(prop, mp.get_property_number(prop) + amt)
|
||||
end
|
||||
|
||||
-- Resets the pan if the entire image would be visible
|
||||
function zoom_check_center()
|
||||
local zoom = mp.get_property_number("video-zoom")
|
||||
local rot = mp.get_property_number("video-rotate") * math.pi / 180
|
||||
local scaled = not mp.get_property_bool("video-unscaled")
|
||||
local dw = mp.get_property_number("dwidth") * 2 ^ zoom
|
||||
local dh = mp.get_property_number("dheight") * 2 ^ zoom
|
||||
|
||||
-- Adjust for rotation
|
||||
local asr = math.abs(math.sin(rot)); acr = math.abs(math.cos(rot))
|
||||
dw, dh = dw*acr + dh*asr, dh*acr + dw*asr
|
||||
|
||||
-- No property seems to exist for the actual window size, try this instead
|
||||
local ow = mp.get_property_number("osd-width")
|
||||
local oh = mp.get_property_number("osd-height")
|
||||
|
||||
if (dw <= ow and dh <= oh) or (scaled and zoom <= 0.0) then
|
||||
mp.set_property_number("video-pan-x", 0)
|
||||
mp.set_property_number("video-pan-y", 0)
|
||||
end
|
||||
end
|
||||
|
||||
-- Rotates the video while maintaining 0 <= prop < 360
|
||||
function rotate_video(amt)
|
||||
local rot = mp.get_property_number("video-rotate")
|
||||
rot = (rot + amt) % 360
|
||||
mp.set_property_number("video-rotate", rot)
|
||||
end
|
||||
|
||||
mp.add_key_binding(nil, "zoom-invariant-add", zoom_invariant_add)
|
||||
mp.add_key_binding(nil, "zoom-check-center", zoom_check_center)
|
||||
mp.add_key_binding(nil, "rotate-video", rotate_video)
|
||||
@@ -0,0 +1,228 @@
|
||||
-- mpvconcat
|
||||
-- interactively create concat input for ffmpeg
|
||||
-- forked from https://github.com/pvpscript/mpv-video-splice
|
||||
|
||||
local mp = require 'mp'
|
||||
local msg = require 'mp.msg'
|
||||
|
||||
local preview_count = 0
|
||||
local timer = nil
|
||||
local file_name = "concat.txt"
|
||||
local concat_file = string.format("%s/%s", mp.get_property("working-directory"), file_name)
|
||||
local times = {}
|
||||
local start_time = nil
|
||||
local remove_val = ""
|
||||
local exit_time = 0
|
||||
|
||||
function notify(duration, ...)
|
||||
local args = {...}
|
||||
local text = ""
|
||||
|
||||
for i, v in ipairs(args) do
|
||||
text = text .. tostring(v)
|
||||
end
|
||||
|
||||
msg.info(text)
|
||||
mp.command(string.format("show-text \"%s\" %d 1",
|
||||
text, duration))
|
||||
end
|
||||
|
||||
local function time_to_str(time)
|
||||
local hours = math.floor(time / 3600)
|
||||
local mins = math.floor((time - hours * 3600) / 60)
|
||||
local secs = time - hours * 3600 - mins * 60
|
||||
|
||||
local fmt_time = string.format('%02d:%02d:%05.2f', hours, mins, secs)
|
||||
|
||||
return fmt_time
|
||||
end
|
||||
|
||||
local function add_time(obj)
|
||||
table.insert(times, obj)
|
||||
end
|
||||
|
||||
local function del_time(num)
|
||||
table.remove(times, num)
|
||||
end
|
||||
|
||||
function put_time()
|
||||
local time = mp.get_property_number('time-pos')
|
||||
local message = ""
|
||||
|
||||
if not start_time then
|
||||
start_time = time
|
||||
message = "[START TIMESTAMP]"
|
||||
else
|
||||
add_time({
|
||||
t_file = mp.get_property("path"),
|
||||
t_start = start_time,
|
||||
t_starts = time_to_str(start_time),
|
||||
t_end = time,
|
||||
t_ends = time_to_str(time)
|
||||
})
|
||||
start_time = nil
|
||||
|
||||
message = "[END TIMESTAMP]"
|
||||
end
|
||||
|
||||
notify(2000, message, ": ", time_to_str(time))
|
||||
end
|
||||
|
||||
function show_times()
|
||||
notify(2000, "Total cuts: ", #times)
|
||||
|
||||
for i, obj in ipairs(times) do
|
||||
msg.info("Segment", "#" .. i, obj.t_file .. ":", obj.t_starts, "-", obj.t_ends)
|
||||
end
|
||||
if start_time then
|
||||
notify(2000, "Segment ", #times+1, " in progress.")
|
||||
end
|
||||
end
|
||||
|
||||
function reset_segment()
|
||||
if start_time then
|
||||
notify(2000, "Segment ", #times+1, " reseted.")
|
||||
|
||||
start_time = nil
|
||||
end
|
||||
end
|
||||
|
||||
function delete_segment()
|
||||
if remove_val == "" then
|
||||
notify(2000, "Entered segment deletion mode.")
|
||||
|
||||
-- Add shortcut keys to the interval {0..9}.
|
||||
for i=0,9,1 do
|
||||
mp.add_key_binding("ctrl+" .. i, "num_key_" .. i,
|
||||
function()
|
||||
remove_val = remove_val .. i
|
||||
notify(1000, "Segment to remove: "
|
||||
.. remove_val)
|
||||
end
|
||||
)
|
||||
end
|
||||
else
|
||||
-- Remove previously added shortcut keys.
|
||||
for i=0,9,1 do
|
||||
mp.remove_key_binding("num_key_" .. i)
|
||||
end
|
||||
|
||||
remove_num = tonumber(remove_val)
|
||||
if #times >= remove_num and remove_num > 0 then
|
||||
del_time(remove_num)
|
||||
notify(2000, "Removed segment ", remove_num)
|
||||
end
|
||||
|
||||
remove_val = ""
|
||||
|
||||
msg.info("Exited segment deletion mode.")
|
||||
end
|
||||
end
|
||||
|
||||
function prevent_quit(name)
|
||||
if start_time then
|
||||
if os.time() - exit_time <= 2 then
|
||||
mp.command(name)
|
||||
else
|
||||
exit_time = os.time()
|
||||
end
|
||||
notify(3000, "Segment has been marked. Press again to quit")
|
||||
else
|
||||
mp.command(name)
|
||||
end
|
||||
end
|
||||
|
||||
function get_concat_arg(line)
|
||||
local arg = string.sub(string.match(line, " .*$"), 2)
|
||||
if arg:match("^[\"'].*[\"']$") then
|
||||
arg = arg:sub(2, -2)
|
||||
end
|
||||
return arg
|
||||
end
|
||||
|
||||
function read_concat()
|
||||
local concat_file_ptr = io.open(concat_file, "r")
|
||||
|
||||
if concat_file_ptr then
|
||||
obj = {t_file = nil, t_start = nil, t_end = nil}
|
||||
for line in concat_file_ptr:lines() do
|
||||
if string.match(line, "^file ") then
|
||||
obj.t_file = get_concat_arg(line)
|
||||
elseif string.match(line, "^inpoint ") then
|
||||
obj.t_start = tonumber(get_concat_arg(line))
|
||||
obj.t_starts = time_to_str(obj.t_start)
|
||||
elseif string.match(line, "^outpoint ") then
|
||||
obj.t_end = tonumber(get_concat_arg(line))
|
||||
obj.t_ends = time_to_str(obj.t_end)
|
||||
end
|
||||
if obj.t_file and obj.t_start and obj.t_end then
|
||||
add_time(obj)
|
||||
obj = {t_file = nil, t_start = nil, t_end = nil}
|
||||
end
|
||||
end
|
||||
concat_file_ptr:close()
|
||||
end
|
||||
end
|
||||
|
||||
function write_concat()
|
||||
local concat_file_ptr = io.open(concat_file, "w")
|
||||
|
||||
for i, obj in ipairs(times) do
|
||||
if i > 1 then
|
||||
concat_file_ptr:write("\n")
|
||||
end
|
||||
concat_file_ptr:write(string.format("# Segment #%d: %s - %s\n", i, obj.t_starts, obj.t_ends))
|
||||
concat_file_ptr:write(string.format("file '%s'\n", obj.t_file))
|
||||
concat_file_ptr:write(string.format("inpoint %s\n", obj.t_start))
|
||||
concat_file_ptr:write(string.format("outpoint %s\n", obj.t_end))
|
||||
end
|
||||
|
||||
concat_file_ptr:close()
|
||||
|
||||
notify(10000, "concat file saved as: ", concat_file)
|
||||
end
|
||||
|
||||
function preview_kill()
|
||||
mp.set_property_native("pause", true)
|
||||
mp.unobserve_property(preview_handler)
|
||||
preview_count = 0
|
||||
notify(10000, "Exited preview mode")
|
||||
end
|
||||
|
||||
function preview_handler()
|
||||
if mp.get_property_number("time-pos") >= times[preview_count].t_end then
|
||||
if preview_count < #times then
|
||||
preview_count = preview_count + 1
|
||||
else
|
||||
preview_kill()
|
||||
return
|
||||
end
|
||||
mp.commandv("seek", times[preview_count].t_start, "absolute", "exact")
|
||||
end
|
||||
end
|
||||
|
||||
function preview_concat()
|
||||
if preview_count == 0 then
|
||||
notify(10000, "Entered preview mode")
|
||||
preview_count = 1
|
||||
mp.commandv("seek", times[preview_count].t_start, "absolute", "exact")
|
||||
mp.set_property_native("pause", false)
|
||||
mp.observe_property("time-pos", number, preview_handler)
|
||||
else
|
||||
preview_kill()
|
||||
end
|
||||
end
|
||||
|
||||
mp.set_property("keep-open", "yes") -- Prevent mpv from exiting when the video ends
|
||||
mp.set_property("quiet", "yes") -- Silence terminal.
|
||||
|
||||
mp.add_key_binding('q', "quit", function() prevent_quit("quit") end)
|
||||
mp.add_key_binding('Shift+q', "quit-watch-later", function() prevent_quit("quit-watch-later") end)
|
||||
mp.add_key_binding('ctrl+t', "put_time", put_time)
|
||||
mp.add_key_binding('ctrl+s', "show_times", show_times)
|
||||
mp.add_key_binding('ctrl+r', "reset_segment", reset_segment)
|
||||
mp.add_key_binding('ctrl+d', "delete_segment", delete_segment)
|
||||
mp.add_key_binding('ctrl+p', "preview_concat", preview_concat)
|
||||
mp.add_key_binding('ctrl+w', "write_concat", write_concat)
|
||||
|
||||
read_concat()
|
||||
@@ -0,0 +1,986 @@
|
||||
local settings = {
|
||||
|
||||
-- #### FUNCTIONALITY SETTINGS
|
||||
|
||||
--navigation keybindings force override only while playlist is visible
|
||||
--if "no" then you can display the playlist by any of the navigation keys
|
||||
dynamic_binds = true,
|
||||
|
||||
-- to bind multiple keys separate them by a space
|
||||
key_moveup = "UP",
|
||||
key_movedown = "DOWN",
|
||||
key_selectfile = "RIGHT LEFT",
|
||||
key_unselectfile = "",
|
||||
key_playfile = "ENTER",
|
||||
key_removefile = "BS",
|
||||
key_closeplaylist = "ESC",
|
||||
|
||||
--replaces matches on filenames based on extension, put as empty string to not replace anything
|
||||
--replace rules are executed in provided order
|
||||
--replace rule key is the pattern and value is the replace value
|
||||
--uses :gsub('pattern', 'replace'), read more http://lua-users.org/wiki/StringLibraryTutorial
|
||||
--'all' will match any extension or protocol if it has one
|
||||
--uses json and parses it into a lua table to be able to support .conf file
|
||||
|
||||
filename_replace = "",
|
||||
|
||||
--[=====[ START OF SAMPLE REPLACE, to use remove start and end line
|
||||
--Sample replace: replaces underscore to space on all files
|
||||
--for mp4 and webm; remove extension, remove brackets and surrounding whitespace, change dot between alphanumeric to space
|
||||
filename_replace = [[
|
||||
[
|
||||
{
|
||||
"ext": { "all": true},
|
||||
"rules": [
|
||||
{ "_" : " " }
|
||||
]
|
||||
},{
|
||||
"ext": { "mp4": true, "mkv": true },
|
||||
"rules": [
|
||||
{ "^(.+)%..+$": "%1" },
|
||||
{ "%s*[%[%(].-[%]%)]%s*": "" },
|
||||
{ "(%w)%.(%w)": "%1 %2" }
|
||||
]
|
||||
},{
|
||||
"protocol": { "http": true, "https": true },
|
||||
"rules": [
|
||||
{ "^%a+://w*%.?": "" }
|
||||
]
|
||||
}
|
||||
]
|
||||
]],
|
||||
--END OF SAMPLE REPLACE ]=====]
|
||||
|
||||
--json array of filetypes to search from directory
|
||||
loadfiles_filetypes = [[
|
||||
[
|
||||
"jpg", "jpeg", "png", "tif", "tiff", "gif", "webp", "svg", "bmp",
|
||||
"mp3", "wav", "ogm", "flac", "m4a", "wma", "ogg", "opus",
|
||||
"mkv", "avi", "mp4", "ogv", "webm", "rmvb", "flv", "wmv", "mpeg", "mpg", "m4v", "3gp"
|
||||
]
|
||||
]],
|
||||
|
||||
--loadfiles at startup if there is 0 or 1 items in playlist, if 0 uses worḱing dir for files
|
||||
loadfiles_on_start = false,
|
||||
|
||||
--sort playlist on mpv start
|
||||
sortplaylist_on_start = false,
|
||||
|
||||
--sort playlist when files are added to playlist
|
||||
sortplaylist_on_file_add = false,
|
||||
|
||||
--use alphanumerical sort
|
||||
alphanumsort = true,
|
||||
|
||||
--"linux | windows | auto"
|
||||
system = "auto",
|
||||
|
||||
--Use ~ for home directory. Leave as empty to use mpv/playlists
|
||||
playlist_savepath = "",
|
||||
|
||||
|
||||
--show playlist or filename every time a new file is loaded
|
||||
--2 shows playlist, 1 shows current file(filename strip applied) as osd text, 0 shows nothing
|
||||
--instead of using this you can also call script-message playlistmanager show playlist/filename
|
||||
--ex. KEY playlist-next ; script-message playlistmanager show playlist
|
||||
show_playlist_on_fileload = 0,
|
||||
|
||||
--sync cursor when file is loaded from outside reasons(file-ending, playlist-next shortcut etc.)
|
||||
--has the sideeffect of moving cursor if file happens to change when navigating
|
||||
--good side is cursor always following current file when going back and forth files with playlist-next/prev
|
||||
sync_cursor_on_load = true,
|
||||
|
||||
--playlist open key will toggle visibility instead of refresh, best used with long timeout
|
||||
open_toggles = true,
|
||||
|
||||
--allow the playlist cursor to loop from end to start and vice versa
|
||||
loop_cursor = true,
|
||||
|
||||
|
||||
--#### VISUAL SETTINGS
|
||||
|
||||
--prefer to display titles for following files: "all", "url", "none". Sorting still uses filename.
|
||||
prefer_titles = "url",
|
||||
|
||||
--call youtube-dl to resolve the titles of urls in the playlist
|
||||
resolve_titles = false,
|
||||
|
||||
--osd timeout on inactivity, with high value on this open_toggles is good to be true
|
||||
playlist_display_timeout = 5,
|
||||
|
||||
--amount of entries to show before slicing. Optimal value depends on font/video size etc.
|
||||
showamount = 16,
|
||||
|
||||
--font size scales by window, if false requires larger font and padding sizes
|
||||
scale_playlist_by_window=true,
|
||||
--playlist ass style overrides inside curly brackets, \keyvalue is one field, extra \ for escape in lua
|
||||
--example {\\fnUbuntu\\fs10\\b0\\bord1} equals: font=Ubuntu, size=10, bold=no, border=1
|
||||
--read http://docs.aegisub.org/3.2/ASS_Tags/ for reference of tags
|
||||
--undeclared tags will use default osd settings
|
||||
--these styles will be used for the whole playlist
|
||||
style_ass_tags = "{}",
|
||||
--paddings from top left corner
|
||||
text_padding_x = 10,
|
||||
text_padding_y = 30,
|
||||
|
||||
--set title of window with stripped name
|
||||
set_title_stripped = false,
|
||||
title_prefix = "",
|
||||
title_suffix = " - mpv",
|
||||
|
||||
--slice long filenames, and how many chars to show
|
||||
slice_longfilenames = false,
|
||||
slice_longfilenames_amount = 70,
|
||||
|
||||
--Playlist header template
|
||||
--%mediatitle or %filename = title or name of playing file
|
||||
--%pos = position of playing file
|
||||
--%cursor = position of navigation
|
||||
--%plen = playlist length
|
||||
--%N = newline
|
||||
playlist_header = "[%cursor/%plen]",
|
||||
|
||||
--Playlist file templates
|
||||
--%pos = position of file with leading zeros
|
||||
--%name = title or name of file
|
||||
--%N = newline
|
||||
--you can also use the ass tags mentioned above. For example:
|
||||
-- selected_file="{\\c&HFF00FF&}➔ %name" | to add a color for selected file. However, if you
|
||||
-- use ass tags you need to reset them for every line (see https://github.com/jonniek/mpv-playlistmanager/issues/20)
|
||||
normal_file = "○ %name",
|
||||
hovered_file = "● %name",
|
||||
selected_file = "➔ %name",
|
||||
playing_file = "▷ %name",
|
||||
playing_hovered_file = "▶ %name",
|
||||
playing_selected_file = "➤ %name",
|
||||
|
||||
|
||||
-- what to show when playlist is truncated
|
||||
playlist_sliced_prefix = "...",
|
||||
playlist_sliced_suffix = "..."
|
||||
|
||||
}
|
||||
local opts = require("mp.options")
|
||||
opts.read_options(settings, "playlistmanager", function(list) update_opts(list) end)
|
||||
|
||||
local utils = require("mp.utils")
|
||||
local msg = require("mp.msg")
|
||||
local assdraw = require("mp.assdraw")
|
||||
|
||||
|
||||
--check os
|
||||
if settings.system=="auto" then
|
||||
local o = {}
|
||||
if mp.get_property_native('options/vo-mmcss-profile', o) ~= o then
|
||||
settings.system = "windows"
|
||||
else
|
||||
settings.system = "linux"
|
||||
end
|
||||
end
|
||||
|
||||
--global variables
|
||||
local playlist_visible = false
|
||||
local strippedname = nil
|
||||
local path = nil
|
||||
local directory = nil
|
||||
local filename = nil
|
||||
local pos = 0
|
||||
local plen = 0
|
||||
local cursor = 0
|
||||
--table for saved media titles for later if we prefer them
|
||||
local url_table = {}
|
||||
-- table for urls that we have request to be resolved to titles
|
||||
local requested_urls = {}
|
||||
--state for if we sort on playlist size change
|
||||
local sort_watching = false
|
||||
|
||||
local filetype_lookup = {}
|
||||
|
||||
function update_opts(changelog)
|
||||
msg.verbose('updating options')
|
||||
|
||||
--parse filename json
|
||||
if changelog.filename_replace then
|
||||
if(settings.filename_replace~="") then
|
||||
settings.filename_replace = utils.parse_json(settings.filename_replace)
|
||||
else
|
||||
settings.filename_replace = false
|
||||
end
|
||||
end
|
||||
|
||||
--parse loadfiles json
|
||||
if changelog.loadfiles_filetypes then
|
||||
settings.loadfiles_filetypes = utils.parse_json(settings.loadfiles_filetypes)
|
||||
|
||||
filetype_lookup = {}
|
||||
--create loadfiles set
|
||||
for _, ext in ipairs(settings.loadfiles_filetypes) do
|
||||
filetype_lookup[ext] = true
|
||||
end
|
||||
end
|
||||
|
||||
if changelog.resolve_titles then
|
||||
resolve_titles()
|
||||
end
|
||||
|
||||
if changelog.playlist_display_timeout then
|
||||
keybindstimer = mp.add_periodic_timer(settings.playlist_display_timeout, remove_keybinds)
|
||||
keybindstimer:kill()
|
||||
end
|
||||
|
||||
if playlist_visible then showplaylist() end
|
||||
end
|
||||
|
||||
update_opts({filename_replace = true, loadfiles_filetypes = true})
|
||||
|
||||
function on_loaded()
|
||||
filename = mp.get_property("filename")
|
||||
path = mp.get_property('path')
|
||||
--if not a url then join path with working directory
|
||||
if not path:match("^%a%a+:%/%/") then
|
||||
path = utils.join_path(mp.get_property('working-directory'), path)
|
||||
directory = utils.split_path(path)
|
||||
else
|
||||
directory = nil
|
||||
end
|
||||
|
||||
refresh_globals()
|
||||
if settings.sync_cursor_on_load then
|
||||
cursor=pos
|
||||
--refresh playlist if cursor moved
|
||||
if playlist_visible then draw_playlist() end
|
||||
end
|
||||
|
||||
local media_title = mp.get_property("media-title")
|
||||
if path:match('^https?://') and not url_table[path] and path ~= media_title then
|
||||
url_table[path] = media_title
|
||||
end
|
||||
|
||||
strippedname = stripfilename(mp.get_property('media-title'))
|
||||
if settings.show_playlist_on_fileload == 2 then
|
||||
showplaylist()
|
||||
elseif settings.show_playlist_on_fileload == 1 then
|
||||
mp.commandv('show-text', strippedname)
|
||||
end
|
||||
if settings.set_title_stripped then
|
||||
mp.set_property("title", settings.title_prefix..strippedname..settings.title_suffix)
|
||||
end
|
||||
|
||||
local didload = false
|
||||
if settings.loadfiles_on_start and plen == 1 then
|
||||
didload = true --save reference for sorting
|
||||
msg.info("Loading files from playing files directory")
|
||||
playlist()
|
||||
end
|
||||
|
||||
--if we promised to sort files on launch do it
|
||||
if promised_sort then
|
||||
promised_sort = false
|
||||
msg.info("Your playlist is sorted before starting playback")
|
||||
if didload then sortplaylist() else sortplaylist(true) end
|
||||
end
|
||||
|
||||
--if we promised to listen and sort on playlist size increase do it
|
||||
if promised_sort_watch then
|
||||
promised_sort_watch = false
|
||||
sort_watching = true
|
||||
msg.info("Added files will be automatically sorted")
|
||||
mp.observe_property('playlist-count', "number", autosort)
|
||||
end
|
||||
end
|
||||
|
||||
function on_closed()
|
||||
strippedname = nil
|
||||
path = nil
|
||||
directory = nil
|
||||
filename = nil
|
||||
if playlist_visible then showplaylist() end
|
||||
end
|
||||
|
||||
function refresh_globals()
|
||||
pos = mp.get_property_number('playlist-pos', 0)
|
||||
plen = mp.get_property_number('playlist-count', 0)
|
||||
end
|
||||
|
||||
function escapepath(dir, escapechar)
|
||||
return string.gsub(dir, escapechar, '\\'..escapechar)
|
||||
end
|
||||
|
||||
--strip a filename based on its extension or protocol according to rules in settings
|
||||
function stripfilename(pathfile, media_title)
|
||||
if pathfile == nil then return '' end
|
||||
local ext = pathfile:match("^.+%.(.+)$")
|
||||
local protocol = pathfile:match("^(%a%a+)://")
|
||||
if not ext then ext = "" end
|
||||
local tmp = pathfile
|
||||
if settings.filename_replace and not media_title then
|
||||
for k,v in ipairs(settings.filename_replace) do
|
||||
if ( v['ext'] and (v['ext'][ext] or (ext and not protocol and v['ext']['all'])) )
|
||||
or ( v['protocol'] and (v['protocol'][protocol] or (protocol and not ext and v['protocol']['all'])) ) then
|
||||
for ruleindex, indexrules in ipairs(v['rules']) do
|
||||
for rule, override in pairs(indexrules) do
|
||||
tmp = tmp:gsub(rule, override)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if settings.slice_longfilenames and tmp:len()>settings.slice_longfilenames_amount+5 then
|
||||
tmp = tmp:sub(1, settings.slice_longfilenames_amount).." ..."
|
||||
end
|
||||
return tmp
|
||||
end
|
||||
|
||||
--gets a nicename of playlist entry at 0-based position i
|
||||
function get_name_from_index(i, notitle)
|
||||
refresh_globals()
|
||||
if plen <= i then msg.error("no index in playlist", i, "length", plen); return nil end
|
||||
local _, name = nil
|
||||
local title = mp.get_property('playlist/'..i..'/title')
|
||||
local name = mp.get_property('playlist/'..i..'/filename')
|
||||
|
||||
local should_use_title = settings.prefer_titles == 'all' or name:match('^https?://') and settings.prefer_titles == 'url'
|
||||
--check if file has a media title stored or as property
|
||||
if not title and should_use_title then
|
||||
local mtitle = mp.get_property('media-title')
|
||||
if i == pos and mp.get_property('filename') ~= mtitle then
|
||||
if not url_table[name] then
|
||||
url_table[name] = mtitle
|
||||
end
|
||||
title = mtitle
|
||||
elseif url_table[name] then
|
||||
title = url_table[name]
|
||||
end
|
||||
end
|
||||
|
||||
--if we have media title use a more conservative strip
|
||||
if title and not notitle and should_use_title then return stripfilename(title, true) end
|
||||
|
||||
--remove paths if they exist, keeping protocols for stripping
|
||||
if string.sub(name, 1, 1) == '/' or name:match("^%a:[/\\]") then
|
||||
_, name = utils.split_path(name)
|
||||
end
|
||||
return stripfilename(name)
|
||||
end
|
||||
|
||||
function parse_header(string)
|
||||
local esc_title = stripfilename(mp.get_property("media-title"), true):gsub("%%", "%%%%")
|
||||
local esc_file = stripfilename(mp.get_property("filename")):gsub("%%", "%%%%")
|
||||
return string:gsub("%%N", "\\N")
|
||||
:gsub("%%pos", mp.get_property_number("playlist-pos",0)+1)
|
||||
:gsub("%%plen", mp.get_property("playlist-count"))
|
||||
:gsub("%%cursor", cursor+1)
|
||||
:gsub("%%mediatitle", esc_title)
|
||||
:gsub("%%filename", esc_file)
|
||||
-- undo name escape
|
||||
:gsub("%%%%", "%%")
|
||||
end
|
||||
|
||||
function parse_filename(string, name, index)
|
||||
local base = tostring(plen):len()
|
||||
local esc_name = stripfilename(name):gsub("%%", "%%%%")
|
||||
return string:gsub("%%N", "\\N")
|
||||
:gsub("%%pos", string.format("%0"..base.."d", index+1))
|
||||
:gsub("%%name", esc_name)
|
||||
-- undo name escape
|
||||
:gsub("%%%%", "%%")
|
||||
end
|
||||
|
||||
function parse_filename_by_index(index)
|
||||
local template = settings.normal_file
|
||||
|
||||
local is_idle = mp.get_property_native('idle-active')
|
||||
local position = is_idle and -1 or pos
|
||||
|
||||
if index == position then
|
||||
if index == cursor then
|
||||
if selection then
|
||||
template = settings.playing_selected_file
|
||||
else
|
||||
template = settings.playing_hovered_file
|
||||
end
|
||||
else
|
||||
template = settings.playing_file
|
||||
end
|
||||
elseif index == cursor then
|
||||
if selection then
|
||||
template = settings.selected_file
|
||||
else
|
||||
template = settings.hovered_file
|
||||
end
|
||||
end
|
||||
|
||||
return parse_filename(template, get_name_from_index(index), index)
|
||||
end
|
||||
|
||||
|
||||
function draw_playlist()
|
||||
refresh_globals()
|
||||
local ass = assdraw.ass_new()
|
||||
ass:new_event()
|
||||
ass:pos(settings.text_padding_x, settings.text_padding_y)
|
||||
ass:append(settings.style_ass_tags)
|
||||
|
||||
if settings.playlist_header ~= "" then
|
||||
ass:append(parse_header(settings.playlist_header).."\\N")
|
||||
end
|
||||
local start = cursor - math.floor(settings.showamount/2)
|
||||
local showall = false
|
||||
local showrest = false
|
||||
if start<0 then start=0 end
|
||||
if plen <= settings.showamount then
|
||||
start=0
|
||||
showall=true
|
||||
end
|
||||
if start > math.max(plen-settings.showamount-1, 0) then
|
||||
start=plen-settings.showamount
|
||||
showrest=true
|
||||
end
|
||||
if start > 0 and not showall then ass:append(settings.playlist_sliced_prefix.."\\N") end
|
||||
for index=start,start+settings.showamount-1,1 do
|
||||
if index == plen then break end
|
||||
|
||||
ass:append(parse_filename_by_index(index).."\\N")
|
||||
if index == start+settings.showamount-1 and not showall and not showrest then
|
||||
ass:append(settings.playlist_sliced_suffix)
|
||||
end
|
||||
end
|
||||
local w, h = mp.get_osd_size()
|
||||
if settings.scale_playlist_by_window then w,h = 0, 0 end
|
||||
mp.set_osd_ass(w, h, ass.text)
|
||||
end
|
||||
|
||||
function toggle_playlist()
|
||||
if settings.open_toggles then
|
||||
if playlist_visible then
|
||||
remove_keybinds()
|
||||
return
|
||||
end
|
||||
end
|
||||
showplaylist()
|
||||
end
|
||||
|
||||
function showplaylist(duration)
|
||||
refresh_globals()
|
||||
if plen == 0 then return end
|
||||
playlist_visible = true
|
||||
add_keybinds()
|
||||
|
||||
draw_playlist()
|
||||
keybindstimer:kill()
|
||||
if duration then
|
||||
keybindstimer = mp.add_periodic_timer(duration, remove_keybinds)
|
||||
else
|
||||
keybindstimer:resume()
|
||||
end
|
||||
end
|
||||
|
||||
selection=nil
|
||||
function selectfile()
|
||||
refresh_globals()
|
||||
if plen == 0 then return end
|
||||
if not selection then
|
||||
selection=cursor
|
||||
else
|
||||
selection=nil
|
||||
end
|
||||
showplaylist()
|
||||
end
|
||||
|
||||
function unselectfile()
|
||||
selection=nil
|
||||
showplaylist()
|
||||
end
|
||||
|
||||
function removefile()
|
||||
refresh_globals()
|
||||
if plen == 0 then return end
|
||||
selection = nil
|
||||
if cursor==pos then mp.command("script-message unseenplaylist mark true \"playlistmanager avoid conflict when removing file\"") end
|
||||
mp.commandv("playlist-remove", cursor)
|
||||
if cursor==plen-1 then cursor = cursor - 1 end
|
||||
showplaylist()
|
||||
end
|
||||
|
||||
function moveup()
|
||||
refresh_globals()
|
||||
if plen == 0 then return end
|
||||
if cursor~=0 then
|
||||
if selection then mp.commandv("playlist-move", cursor,cursor-1) end
|
||||
cursor = cursor-1
|
||||
elseif settings.loop_cursor then
|
||||
if selection then mp.commandv("playlist-move", cursor,plen) end
|
||||
cursor = plen-1
|
||||
end
|
||||
showplaylist()
|
||||
end
|
||||
|
||||
function movedown()
|
||||
refresh_globals()
|
||||
if plen == 0 then return end
|
||||
if cursor ~= plen-1 then
|
||||
if selection then mp.commandv("playlist-move", cursor,cursor+2) end
|
||||
cursor = cursor + 1
|
||||
elseif settings.loop_cursor then
|
||||
if selection then mp.commandv("playlist-move", cursor,0) end
|
||||
cursor = 0
|
||||
end
|
||||
showplaylist()
|
||||
end
|
||||
|
||||
function write_watch_later(force_write)
|
||||
if mp.get_property_bool("save-position-on-quit") or force_write then
|
||||
mp.command("write-watch-later-config")
|
||||
end
|
||||
end
|
||||
|
||||
function playlist_next(force_write)
|
||||
write_watch_later(force_write)
|
||||
mp.commandv("playlist-next", "weak")
|
||||
end
|
||||
|
||||
function playlist_prev(force_write)
|
||||
write_watch_later(force_write)
|
||||
mp.commandv("playlist-prev", "weak")
|
||||
end
|
||||
|
||||
function playfile()
|
||||
refresh_globals()
|
||||
if plen == 0 then return end
|
||||
selection = nil
|
||||
local is_idle = mp.get_property_native('idle-active')
|
||||
if cursor ~= pos or is_idle then
|
||||
write_watch_later()
|
||||
mp.set_property("playlist-pos", cursor)
|
||||
else
|
||||
if cursor~=plen-1 then
|
||||
cursor = cursor + 1
|
||||
end
|
||||
write_watch_later()
|
||||
mp.commandv("playlist-next", "weak")
|
||||
end
|
||||
if settings.show_playlist_on_fileload ~= 2 then
|
||||
remove_keybinds()
|
||||
end
|
||||
end
|
||||
|
||||
function get_files_windows(dir)
|
||||
local args = {
|
||||
'powershell', '-NoProfile', '-Command', [[& {
|
||||
Trap {
|
||||
Write-Error -ErrorRecord $_
|
||||
Exit 1
|
||||
}
|
||||
$path = "]]..dir..[["
|
||||
$escapedPath = [WildcardPattern]::Escape($path)
|
||||
cd $escapedPath
|
||||
|
||||
$list = (Get-ChildItem -File | Sort-Object { [regex]::Replace($_.Name, '\d+', { $args[0].Value.PadLeft(20) }) }).Name
|
||||
$string = ($list -join "/")
|
||||
$u8list = [System.Text.Encoding]::UTF8.GetBytes($string)
|
||||
[Console]::OpenStandardOutput().Write($u8list, 0, $u8list.Length)
|
||||
}]]
|
||||
}
|
||||
local process = utils.subprocess({ args = args, cancellable = false })
|
||||
return parse_files(process, '%/')
|
||||
end
|
||||
|
||||
function get_files_linux(dir)
|
||||
local args = { 'ls', '-1pv', dir }
|
||||
local process = utils.subprocess({ args = args, cancellable = false })
|
||||
return parse_files(process, '\n')
|
||||
end
|
||||
|
||||
function parse_files(res, delimiter)
|
||||
if not res.error and res.status == 0 then
|
||||
local valid_files = {}
|
||||
for line in res.stdout:gmatch("[^"..delimiter.."]+") do
|
||||
local ext = line:match("^.+%.(.+)$")
|
||||
if ext and filetype_lookup[ext:lower()] then
|
||||
table.insert(valid_files, line)
|
||||
end
|
||||
end
|
||||
return valid_files, nil
|
||||
else
|
||||
return nil, res.error
|
||||
end
|
||||
end
|
||||
|
||||
--Creates a playlist of all files in directory, will keep the order and position
|
||||
--For exaple, Folder has 12 files, you open the 5th file and run this, the remaining 7 are added behind the 5th file and prior 4 files before it
|
||||
function playlist(force_dir)
|
||||
refresh_globals()
|
||||
if not directory and plen > 0 then return end
|
||||
local hasfile = true
|
||||
if plen == 0 then
|
||||
hasfile = false
|
||||
dir = mp.get_property('working-directory')
|
||||
else
|
||||
dir = directory
|
||||
end
|
||||
if force_dir then dir = force_dir end
|
||||
|
||||
local files, error
|
||||
if settings.system == "linux" then
|
||||
files, error = get_files_linux(dir)
|
||||
else
|
||||
files, error = get_files_windows(dir)
|
||||
end
|
||||
|
||||
local c, c2 = 0,0
|
||||
if files then
|
||||
local cur = false
|
||||
local filename = mp.get_property("filename")
|
||||
for _, file in ipairs(files) do
|
||||
local appendstr = "append"
|
||||
if not hasfile then
|
||||
cur = true
|
||||
appendstr = "append-play"
|
||||
hasfile = true
|
||||
end
|
||||
if cur == true then
|
||||
mp.commandv("loadfile", utils.join_path(dir, file), appendstr)
|
||||
msg.info("Appended to playlist: " .. file)
|
||||
c2 = c2 + 1
|
||||
elseif file ~= filename then
|
||||
mp.commandv("loadfile", utils.join_path(dir, file), appendstr)
|
||||
msg.info("Prepended to playlist: " .. file)
|
||||
mp.commandv("playlist-move", mp.get_property_number("playlist-count", 1)-1, c)
|
||||
c = c + 1
|
||||
else
|
||||
cur = true
|
||||
end
|
||||
end
|
||||
if c2 > 0 or c>0 then
|
||||
mp.osd_message("Added "..c + c2.." files to playlist")
|
||||
else
|
||||
mp.osd_message("No additional files found")
|
||||
end
|
||||
cursor = mp.get_property_number('playlist-pos', 1)
|
||||
else
|
||||
msg.error("Could not scan for files: "..(error or ""))
|
||||
end
|
||||
if sort_watching then
|
||||
msg.info("Ignoring directory structure and using playlist sort")
|
||||
sortplaylist()
|
||||
end
|
||||
refresh_globals()
|
||||
if playlist_visible then showplaylist() end
|
||||
return c + c2
|
||||
end
|
||||
|
||||
function parse_home(path)
|
||||
if not path:find("^~") then
|
||||
return path
|
||||
end
|
||||
local home_dir = os.getenv("HOME") or os.getenv("USERPROFILE")
|
||||
if not home_dir then
|
||||
local drive = os.getenv("HOMEDRIVE")
|
||||
local path = os.getenv("HOMEPATH")
|
||||
if drive and path then
|
||||
home_dir = utils.join_path(drive, path)
|
||||
else
|
||||
msg.error("Couldn't find home dir.")
|
||||
return nil
|
||||
end
|
||||
end
|
||||
local result = path:gsub("^~", home_dir)
|
||||
return result
|
||||
end
|
||||
|
||||
--saves the current playlist into a m3u file
|
||||
function save_playlist()
|
||||
local length = mp.get_property_number('playlist-count', 0)
|
||||
if length == 0 then return end
|
||||
|
||||
--get playlist save path
|
||||
local savepath
|
||||
if settings.playlist_savepath == nil or settings.playlist_savepath == "" then
|
||||
savepath = mp.command_native({"expand-path", "~~home/"}).."/playlists"
|
||||
else
|
||||
savepath = parse_home(settings.playlist_savepath)
|
||||
if savepath == nil then return end
|
||||
end
|
||||
|
||||
--create savepath if it doesn't exist
|
||||
if utils.readdir(savepath) == nil then
|
||||
local windows_args = {'powershell', '-NoProfile', '-Command', 'mkdir', savepath}
|
||||
local unix_args = { 'mkdir', savepath }
|
||||
local args = settings.system == 'windows' and windows_args or unix_args
|
||||
local res = utils.subprocess({ args = args, cancellable = false })
|
||||
if res.status ~= 0 then
|
||||
msg.error("Failed to create playlist save directory "..savepath..". Error: "..(res.error or "unknown"))
|
||||
return
|
||||
end
|
||||
end
|
||||
|
||||
local date = os.date("*t")
|
||||
local datestring = ("%02d-%02d-%02d_%02d-%02d-%02d"):format(date.year, date.month, date.day, date.hour, date.min, date.sec)
|
||||
|
||||
local savepath = utils.join_path(savepath, datestring.."_playlist-size_"..length..".m3u")
|
||||
local file, err = io.open(savepath, "w")
|
||||
if not file then
|
||||
msg.error("Error in creating playlist file, check permissions. Error: "..(err or "unknown"))
|
||||
else
|
||||
local i=0
|
||||
while i < length do
|
||||
local pwd = mp.get_property("working-directory")
|
||||
local filename = mp.get_property('playlist/'..i..'/filename')
|
||||
local fullpath = filename
|
||||
if not filename:match("^%a%a+:%/%/") then
|
||||
fullpath = utils.join_path(pwd, filename)
|
||||
end
|
||||
local title = mp.get_property('playlist/'..i..'/title')
|
||||
if title then file:write("#EXTINF:,"..title.."\n") end
|
||||
file:write(fullpath, "\n")
|
||||
i=i+1
|
||||
end
|
||||
msg.info("Playlist written to: "..savepath)
|
||||
file:close()
|
||||
end
|
||||
end
|
||||
|
||||
function alphanumsort(a, b)
|
||||
local function padnum(d)
|
||||
local dec, n = string.match(d, "(%.?)0*(.+)")
|
||||
return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n)
|
||||
end
|
||||
return tostring(a):lower():gsub("%.?%d+",padnum)..("%3d"):format(#b)
|
||||
< tostring(b):lower():gsub("%.?%d+",padnum)..("%3d"):format(#a)
|
||||
end
|
||||
|
||||
function dosort(a,b)
|
||||
if settings.alphanumsort then
|
||||
return alphanumsort(a,b)
|
||||
else
|
||||
return a < b
|
||||
end
|
||||
end
|
||||
|
||||
function sortplaylist(startover)
|
||||
local length = mp.get_property_number('playlist-count', 0)
|
||||
if length < 2 then return end
|
||||
--use insertion sort on playlist to make it easy to order files with playlist-move
|
||||
for outer=1, length-1, 1 do
|
||||
local outerfile = get_name_from_index(outer, true)
|
||||
local inner = outer - 1
|
||||
while inner >= 0 and dosort(outerfile, get_name_from_index(inner, true)) do
|
||||
inner = inner - 1
|
||||
end
|
||||
inner = inner + 1
|
||||
if outer ~= inner then
|
||||
mp.commandv('playlist-move', outer, inner)
|
||||
end
|
||||
end
|
||||
cursor = mp.get_property_number('playlist-pos', 0)
|
||||
if startover then
|
||||
mp.set_property('playlist-pos', 0)
|
||||
end
|
||||
if playlist_visible then showplaylist() end
|
||||
end
|
||||
|
||||
function autosort(name, param)
|
||||
if param == 0 then return end
|
||||
if plen < param then
|
||||
msg.info("Playlistmanager autosorting playlist")
|
||||
refresh_globals()
|
||||
sortplaylist()
|
||||
end
|
||||
end
|
||||
|
||||
function reverseplaylist()
|
||||
local length = mp.get_property_number('playlist-count', 0)
|
||||
if length < 2 then return end
|
||||
for outer=1, length-1, 1 do
|
||||
mp.commandv('playlist-move', outer, 0)
|
||||
end
|
||||
if playlist_visible then showplaylist() end
|
||||
end
|
||||
|
||||
function shuffleplaylist()
|
||||
refresh_globals()
|
||||
if plen < 2 then return end
|
||||
mp.command("playlist-shuffle")
|
||||
math.randomseed(os.time())
|
||||
mp.commandv("playlist-move", pos, math.random(0, plen-1))
|
||||
mp.set_property('playlist-pos', 0)
|
||||
refresh_globals()
|
||||
if playlist_visible then showplaylist() end
|
||||
end
|
||||
|
||||
function bind_keys(keys, name, func, opts)
|
||||
if not keys then
|
||||
mp.add_forced_key_binding(keys, name, func, opts)
|
||||
return
|
||||
end
|
||||
local i = 1
|
||||
for key in keys:gmatch("[^%s]+") do
|
||||
local prefix = i == 1 and '' or i
|
||||
mp.add_forced_key_binding(key, name..prefix, func, opts)
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
|
||||
function unbind_keys(keys, name)
|
||||
if not keys then
|
||||
mp.remove_key_binding(name)
|
||||
return
|
||||
end
|
||||
local i = 1
|
||||
for key in keys:gmatch("[^%s]+") do
|
||||
local prefix = i == 1 and '' or i
|
||||
mp.remove_key_binding(name..prefix)
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
|
||||
function add_keybinds()
|
||||
bind_keys(settings.key_moveup, 'moveup', moveup, "repeatable")
|
||||
bind_keys(settings.key_movedown, 'movedown', movedown, "repeatable")
|
||||
bind_keys(settings.key_selectfile, 'selectfile', selectfile)
|
||||
bind_keys(settings.key_unselectfile, 'unselectfile', unselectfile)
|
||||
bind_keys(settings.key_playfile, 'playfile', playfile)
|
||||
bind_keys(settings.key_removefile, 'removefile', removefile, "repeatable")
|
||||
bind_keys(settings.key_closeplaylist, 'closeplaylist', remove_keybinds)
|
||||
end
|
||||
|
||||
function remove_keybinds()
|
||||
keybindstimer:kill()
|
||||
keybindstimer = mp.add_periodic_timer(settings.playlist_display_timeout, remove_keybinds)
|
||||
keybindstimer:kill()
|
||||
mp.set_osd_ass(0, 0, "")
|
||||
playlist_visible = false
|
||||
if settings.dynamic_binds then
|
||||
unbind_keys(settings.key_moveup, 'moveup')
|
||||
unbind_keys(settings.key_movedown, 'movedown')
|
||||
unbind_keys(settings.key_selectfile, 'selectfile')
|
||||
unbind_keys(settings.key_unselectfile, 'unselectfile')
|
||||
unbind_keys(settings.key_playfile, 'playfile')
|
||||
unbind_keys(settings.key_removefile, 'removefile')
|
||||
unbind_keys(settings.key_closeplaylist, 'closeplaylist')
|
||||
end
|
||||
end
|
||||
|
||||
keybindstimer = mp.add_periodic_timer(settings.playlist_display_timeout, remove_keybinds)
|
||||
keybindstimer:kill()
|
||||
|
||||
if not settings.dynamic_binds then
|
||||
add_keybinds()
|
||||
end
|
||||
|
||||
if settings.loadfiles_on_start and mp.get_property_number('playlist-count', 0) == 0 then
|
||||
playlist()
|
||||
end
|
||||
|
||||
promised_sort_watch = false
|
||||
if settings.sortplaylist_on_file_add then
|
||||
promised_sort_watch = true
|
||||
end
|
||||
|
||||
promised_sort = false
|
||||
if settings.sortplaylist_on_start then
|
||||
promised_sort = true
|
||||
end
|
||||
|
||||
mp.observe_property('playlist-count', "number", function()
|
||||
if playlist_visible then showplaylist() end
|
||||
if settings.prefer_titles == 'none' then return end
|
||||
-- resolve titles
|
||||
resolve_titles()
|
||||
end)
|
||||
|
||||
--resolves url titles by calling youtube-dl
|
||||
function resolve_titles()
|
||||
if not settings.resolve_titles then return end
|
||||
local length = mp.get_property_number('playlist-count', 0)
|
||||
if length < 2 then return end
|
||||
local i=0
|
||||
-- loop all items in playlist because we can't predict how it has changed
|
||||
while i < length do
|
||||
local filename = mp.get_property('playlist/'..i..'/filename')
|
||||
local title = mp.get_property('playlist/'..i..'/title')
|
||||
if i ~= pos
|
||||
and filename
|
||||
and filename:match('^https?://')
|
||||
and not title
|
||||
and not url_table[filename]
|
||||
and not requested_urls[filename]
|
||||
then
|
||||
requested_urls[filename] = true
|
||||
|
||||
local args = { 'youtube-dl', '--no-playlist', '--flat-playlist', '-sJ', filename }
|
||||
local req = mp.command_native_async(
|
||||
{
|
||||
name = "subprocess",
|
||||
args = args,
|
||||
playback_only = false,
|
||||
capture_stdout = true
|
||||
}, function (success, res)
|
||||
if res.killed_by_us then
|
||||
msg.verbose('Request to resolve url title ' .. filename .. ' timed out')
|
||||
return
|
||||
end
|
||||
if res.status == 0 then
|
||||
local json, err = utils.parse_json(res.stdout)
|
||||
if not err then
|
||||
local is_playlist = json['_type'] and json['_type'] == 'playlist'
|
||||
local title = (is_playlist and '[playlist]: ' or '') .. json['title']
|
||||
msg.verbose(filename .. " resolved to '" .. title .. "'")
|
||||
url_table[filename] = title
|
||||
refresh_globals()
|
||||
if playlist_visible then showplaylist() end
|
||||
return
|
||||
else
|
||||
msg.error("Failed parsing json, reason: "..(err or "unknown"))
|
||||
end
|
||||
else
|
||||
msg.error("Failed to resolve url title "..filename.." Error: "..(res.error or "unknown"))
|
||||
end
|
||||
end)
|
||||
|
||||
mp.add_timeout(5, function()
|
||||
mp.abort_async_command(req)
|
||||
end)
|
||||
|
||||
end
|
||||
i=i+1
|
||||
end
|
||||
end
|
||||
|
||||
--script message handler
|
||||
function handlemessage(msg, value, value2)
|
||||
if msg == "show" and value == "playlist" then
|
||||
if value2 ~= "toggle" then
|
||||
showplaylist(value2)
|
||||
return
|
||||
else
|
||||
toggle_playlist()
|
||||
return
|
||||
end
|
||||
end
|
||||
if msg == "show" and value == "filename" and strippedname and value2 then
|
||||
mp.commandv('show-text', strippedname, tonumber(value2)*1000 ) ; return
|
||||
end
|
||||
if msg == "show" and value == "filename" and strippedname then
|
||||
mp.commandv('show-text', strippedname ) ; return
|
||||
end
|
||||
if msg == "sort" then sortplaylist(value) ; return end
|
||||
if msg == "shuffle" then shuffleplaylist() ; return end
|
||||
if msg == "reverse" then reverseplaylist() ; return end
|
||||
if msg == "loadfiles" then playlist(value) ; return end
|
||||
if msg == "save" then save_playlist() ; return end
|
||||
if msg == "playlist-next" then playlist_next(true) ; return end
|
||||
if msg == "playlist-prev" then playlist_prev(true) ; return end
|
||||
end
|
||||
|
||||
mp.register_script_message("playlistmanager", handlemessage)
|
||||
|
||||
mp.add_key_binding("CTRL+p", "sortplaylist", sortplaylist)
|
||||
mp.add_key_binding("CTRL+P", "shuffleplaylist", shuffleplaylist)
|
||||
mp.add_key_binding("CTRL+R", "reverseplaylist", reverseplaylist)
|
||||
mp.add_key_binding("P", "loadfiles", playlist)
|
||||
mp.add_key_binding("p", "saveplaylist", save_playlist)
|
||||
mp.add_key_binding("SHIFT+ENTER", "showplaylist", toggle_playlist)
|
||||
|
||||
mp.register_event("file-loaded", on_loaded)
|
||||
mp.register_event("end-file", on_closed)
|
||||
@@ -0,0 +1,157 @@
|
||||
local assdraw = require 'mp.assdraw'
|
||||
local active = false
|
||||
local cursor_position = 1
|
||||
local time_scale = {60*60*10, 60*60, 60*10, 60, 10, 1, 0.1, 0.01, 0.001}
|
||||
|
||||
local ass_begin = mp.get_property("osd-ass-cc/0")
|
||||
local ass_end = mp.get_property("osd-ass-cc/1")
|
||||
|
||||
local history = { {} }
|
||||
for i = 1, 9 do
|
||||
history[1][i] = 0
|
||||
end
|
||||
local history_position = 1
|
||||
|
||||
-- timer to redraw periodically the message
|
||||
-- to avoid leaving bindings when the seeker disappears for whatever reason
|
||||
-- pretty hacky tbh
|
||||
local timer = nil
|
||||
local timer_duration = 3
|
||||
|
||||
function show_seeker()
|
||||
local prepend_char = {'','',':','',':','','.','',''}
|
||||
local str = ''
|
||||
for i = 1, 9 do
|
||||
str = str .. prepend_char[i]
|
||||
if i == cursor_position then
|
||||
str = str .. '{\\b1}' .. history[history_position][i] .. '{\\r}'
|
||||
else
|
||||
str = str .. history[history_position][i]
|
||||
end
|
||||
end
|
||||
mp.osd_message("Seek to: " .. ass_begin .. str .. ass_end, timer_duration)
|
||||
end
|
||||
|
||||
function copy_history_to_last()
|
||||
if history_position ~= #history then
|
||||
for i = 1, 9 do
|
||||
history[#history][i] = history[history_position][i]
|
||||
end
|
||||
history_position = #history
|
||||
end
|
||||
end
|
||||
|
||||
function change_number(i)
|
||||
-- can't set above 60 minutes or seconds
|
||||
if (cursor_position == 3 or cursor_position == 5) and i >= 6 then
|
||||
return
|
||||
end
|
||||
if history[history_position][cursor_position] ~= i then
|
||||
copy_history_to_last()
|
||||
history[#history][cursor_position] = i
|
||||
end
|
||||
shift_cursor(false)
|
||||
end
|
||||
|
||||
function shift_cursor(left)
|
||||
if left then
|
||||
cursor_position = math.max(1, cursor_position - 1)
|
||||
else
|
||||
cursor_position = math.min(cursor_position + 1, 9)
|
||||
end
|
||||
end
|
||||
|
||||
function current_time_as_sec(time)
|
||||
local sec = 0
|
||||
for i = 1, 9 do
|
||||
sec = sec + time_scale[i] * time[i]
|
||||
end
|
||||
return sec
|
||||
end
|
||||
|
||||
function time_equal(lhs, rhs)
|
||||
for i = 1, 9 do
|
||||
if lhs[i] ~= rhs[i] then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
function seek_to()
|
||||
copy_history_to_last()
|
||||
mp.commandv("osd-bar", "seek", current_time_as_sec(history[history_position]), "absolute")
|
||||
--deduplicate consecutive timestamps
|
||||
if #history == 1 or not time_equal(history[history_position], history[#history - 1]) then
|
||||
history[#history + 1] = {}
|
||||
history_position = #history
|
||||
end
|
||||
for i = 1, 9 do
|
||||
history[#history][i] = 0
|
||||
end
|
||||
end
|
||||
|
||||
function backspace()
|
||||
if cursor_position ~= 9 or current_time[9] == 0 then
|
||||
shift_cursor(true)
|
||||
end
|
||||
if history[history_position][cursor_position] ~= 0 then
|
||||
copy_history_to_last()
|
||||
history[#history][cursor_position] = 0
|
||||
end
|
||||
end
|
||||
|
||||
function history_move(up)
|
||||
if up then
|
||||
history_position = math.max(1, history_position - 1)
|
||||
else
|
||||
history_position = math.min(history_position + 1, #history)
|
||||
end
|
||||
end
|
||||
|
||||
local key_mappings = {
|
||||
LEFT = function() shift_cursor(true) show_seeker() end,
|
||||
RIGHT = function() shift_cursor(false) show_seeker() end,
|
||||
UP = function() history_move(true) show_seeker() end,
|
||||
DOWN = function() history_move(false) show_seeker() end,
|
||||
BS = function() backspace() show_seeker() end,
|
||||
ESC = function() set_inactive() end,
|
||||
ENTER = function() seek_to() set_inactive() end
|
||||
}
|
||||
for i = 0, 9 do
|
||||
local func = function() change_number(i) show_seeker() end
|
||||
key_mappings[string.format("KP%d", i)] = func
|
||||
key_mappings[string.format("%d", i)] = func
|
||||
end
|
||||
|
||||
function set_active()
|
||||
if not mp.get_property("seekable") then return end
|
||||
-- find duration of the video and set cursor position accordingly
|
||||
local duration = mp.get_property_number("duration")
|
||||
if duration ~= nil then
|
||||
for i = 1, 9 do
|
||||
if duration > time_scale[i] then
|
||||
cursor_position = i
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
for key, func in pairs(key_mappings) do
|
||||
mp.add_forced_key_binding(key, "seek-to-"..key, func)
|
||||
end
|
||||
show_seeker()
|
||||
timer = mp.add_periodic_timer(timer_duration, show_seeker)
|
||||
active = true
|
||||
end
|
||||
|
||||
function set_inactive()
|
||||
mp.osd_message("")
|
||||
for key, _ in pairs(key_mappings) do
|
||||
mp.remove_key_binding("seek-to-"..key)
|
||||
end
|
||||
timer:kill()
|
||||
active = false
|
||||
end
|
||||
|
||||
mp.add_key_binding(nil, "toggle-seeker", function() if active then set_inactive() else set_active() end end)
|
||||
|
||||
@@ -0,0 +1,738 @@
|
||||
-- youtube-download.lua
|
||||
--
|
||||
-- Download video/audio from youtube via youtube-dl and ffmpeg/avconv
|
||||
-- This is forked/based on https://github.com/jgreco/mpv-youtube-quality
|
||||
--
|
||||
-- Video download bound to ctrl-d by default.
|
||||
-- Audio download bound to ctrl-a by default.
|
||||
|
||||
-- Requires youtube-dl in PATH for video download
|
||||
-- Requires ffmpeg or avconv in PATH for audio download
|
||||
|
||||
local mp = require 'mp'
|
||||
local utils = require 'mp.utils'
|
||||
local msg = require 'mp.msg'
|
||||
|
||||
local opts = {
|
||||
-- Key bindings
|
||||
-- Set to empty string "" to disable
|
||||
download_video_binding = "ctrl+d",
|
||||
download_audio_binding = "ctrl+a",
|
||||
download_subtitle_binding = "ctrl+s",
|
||||
download_video_embed_subtitle_binding = "ctrl+i",
|
||||
select_range_binding = "ctrl+r",
|
||||
|
||||
-- Specify audio format: "best", "aac","flac", "mp3", "m4a", "opus", "vorbis", or "wav"
|
||||
audio_format = "mp3",
|
||||
|
||||
-- Specify ffmpeg/avconv audio quality
|
||||
-- insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K
|
||||
audio_quality = "0",
|
||||
|
||||
-- Same as youtube-dl --format FORMAT
|
||||
-- see https://github.com/ytdl-org/youtube-dl/blob/master/README.md#format-selection
|
||||
video_format = "",
|
||||
|
||||
-- Encode the video to another format if necessary: "mp4", "flv", "ogg", "webm", "mkv", "avi"
|
||||
recode_video = "",
|
||||
|
||||
-- Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames
|
||||
restrict_filenames = true,
|
||||
|
||||
-- Download the whole playlist (false) or only one video (true)
|
||||
-- Same as youtube-dl --no-playlist
|
||||
no_playlist = true,
|
||||
|
||||
-- Use an archive file, see youtube-dl --download-archive
|
||||
-- You have these options:
|
||||
-- * Set to empty string "" to not use an archive file
|
||||
-- * Set an absolute path to use one archive for all downloads e.g. download_archive="/home/user/archive.txt"
|
||||
-- * Set a relative path/only a filename to use one archive per directory e.g. download_archive="archive.txt"
|
||||
-- * Use $PLAYLIST to create one archive per playlist e.g. download_archive="/home/user/archives/$PLAYLIST.txt"
|
||||
download_archive = "",
|
||||
|
||||
-- Use a cookies file for youtube-dl
|
||||
-- Same as youtube-dl --cookies
|
||||
-- On Windows you need to use a double blackslash or a single fordwardslash
|
||||
-- For example "C:\\Users\\Username\\cookies.txt"
|
||||
-- Or "C:/Users/Username/cookies.txt"
|
||||
cookies = "",
|
||||
|
||||
-- Filename or full path
|
||||
-- Same as youtube-dl -o FILETEMPLATE
|
||||
-- see https://github.com/ytdl-org/youtube-dl/blob/master/README.md#output-template
|
||||
-- A relative path or a file name is relative to the path mpv was launched from
|
||||
-- On Windows you need to use a double blackslash or a single fordwardslash
|
||||
-- For example "C:\\Users\\Username\\Downloads\\%(title)s.%(ext)s"
|
||||
-- Or "C:/Users/Username/Downloads/%(title)s.%(ext)s"
|
||||
filename = "%(title)s.%(ext)s",
|
||||
|
||||
-- Subtitle language
|
||||
-- Same as youtube-dl --sub-lang en
|
||||
sub_lang = "en",
|
||||
|
||||
-- Subtitle format
|
||||
-- Same as youtube-dl --sub-format best
|
||||
sub_format = "best",
|
||||
|
||||
-- Log file for download errors
|
||||
log_file = "",
|
||||
|
||||
}
|
||||
|
||||
--Read configuration file
|
||||
(require 'mp.options').read_options(opts, "youtube-download")
|
||||
|
||||
--Read command line arguments
|
||||
local ytdl_raw_options = mp.get_property("ytdl-raw-options")
|
||||
if ytdl_raw_options ~= nil and ytdl_raw_options:find("cookies=") ~= nil then
|
||||
local cookie_file = ytdl_raw_options:match("cookies=([^,]+)")
|
||||
if cookie_file ~= nil then
|
||||
opts.cookies = cookie_file
|
||||
end
|
||||
end
|
||||
|
||||
local function exec(args, capture_stdout, capture_stderr)
|
||||
local ret = mp.command_native({
|
||||
name = "subprocess",
|
||||
playback_only = false,
|
||||
capture_stdout = capture_stdout,
|
||||
capture_stderr = capture_stderr,
|
||||
args = args,
|
||||
})
|
||||
return ret.status, ret.stdout, ret.stderr, ret
|
||||
end
|
||||
|
||||
local function trim(str)
|
||||
return str:gsub("^%s+", ""):gsub("%s+$", "")
|
||||
end
|
||||
|
||||
local function not_empty(str)
|
||||
if str == nil or str == "" then
|
||||
return false
|
||||
end
|
||||
return trim(str) ~= ""
|
||||
end
|
||||
|
||||
local function path_separator()
|
||||
return package.config:sub(1,1)
|
||||
end
|
||||
|
||||
local function path_join(...)
|
||||
return table.concat({...}, path_separator())
|
||||
end
|
||||
|
||||
local DOWNLOAD = {
|
||||
VIDEO=1,
|
||||
AUDIO=2,
|
||||
SUBTITLE=3,
|
||||
VIDEO_EMBED_SUBTITLE=4
|
||||
}
|
||||
local select_range_mode = 0
|
||||
local start_time_seconds = nil
|
||||
local start_time_formated = nil
|
||||
local end_time_seconds = nil
|
||||
local end_time_formated = nil
|
||||
|
||||
local is_downloading = false
|
||||
|
||||
local function disable_select_range()
|
||||
-- Disable range mode
|
||||
select_range_mode = 0
|
||||
-- Remove the arrow key key bindings
|
||||
mp.remove_key_binding("select-range-set-up")
|
||||
mp.remove_key_binding("select-range-set-down")
|
||||
mp.remove_key_binding("select-range-set-left")
|
||||
mp.remove_key_binding("select-range-set-right")
|
||||
end
|
||||
|
||||
|
||||
local function download(download_type)
|
||||
local start_time = os.date("%c")
|
||||
msg.verbose("download()")
|
||||
if is_downloading then
|
||||
return
|
||||
end
|
||||
is_downloading = true
|
||||
msg.verbose("download() aquired")
|
||||
|
||||
local ass0 = mp.get_property("osd-ass-cc/0")
|
||||
local ass1 = mp.get_property("osd-ass-cc/1")
|
||||
local url = mp.get_property("path")
|
||||
|
||||
url = string.gsub(url, "ytdl://", "") -- Strip possible ytdl:// prefix.
|
||||
|
||||
if string.find(url, "//youtu.be/") == nil
|
||||
and string.find(url, "//ww.youtu.be/") == nil
|
||||
and string.find(url, "//youtube.com/") == nil
|
||||
and string.find(url, "//www.youtube.com/") == nil
|
||||
then
|
||||
mp.osd_message("Not a youtube URL: " .. tostring(url), 10)
|
||||
is_downloading = false
|
||||
return
|
||||
end
|
||||
|
||||
local list_match = url:match("list=(%w+)")
|
||||
local download_archive = opts.download_archive
|
||||
if list_match ~= nil and opts.download_archive ~= nil and opts.download_archive:find("$PLAYLIST", 1, true) then
|
||||
download_archive = opts.download_archive:gsub("$PLAYLIST", list_match)
|
||||
end
|
||||
|
||||
if download_type == DOWNLOAD.AUDIO then
|
||||
mp.osd_message("Audio download started", 2)
|
||||
elseif download_type == DOWNLOAD.SUBTITLE then
|
||||
mp.osd_message("Subtitle download started", 2)
|
||||
elseif download_type == DOWNLOAD.VIDEO_EMBED_SUBTITLE then
|
||||
mp.osd_message("Video w/ subtitle download started", 2)
|
||||
else
|
||||
mp.osd_message("Video download started", 2)
|
||||
end
|
||||
|
||||
-- Compose command line arguments
|
||||
local command = {}
|
||||
|
||||
local range_mode_file_name = nil
|
||||
local range_mode_subtitle_file_name = nil
|
||||
local start_time_offset = 0
|
||||
|
||||
if select_range_mode == 0 or (select_range_mode > 0 and (download_type == DOWNLOAD.AUDIO or download_type == DOWNLOAD.SUBTITLE)) then
|
||||
table.insert(command, "youtube-dl")
|
||||
table.insert(command, "--no-overwrites")
|
||||
if opts.restrict_filenames then
|
||||
table.insert(command, "--restrict-filenames")
|
||||
end
|
||||
if not_empty(opts.filename) then
|
||||
table.insert(command, "-o")
|
||||
table.insert(command, opts.filename)
|
||||
end
|
||||
if opts.no_playlist then
|
||||
table.insert(command, "--no-playlist")
|
||||
end
|
||||
if not_empty(download_archive) then
|
||||
table.insert(command, "--download-archive")
|
||||
table.insert(command, download_archive)
|
||||
end
|
||||
|
||||
if download_type == DOWNLOAD.SUBTITLE then
|
||||
table.insert(command, "--sub-lang")
|
||||
table.insert(command, opts.sub_lang)
|
||||
table.insert(command, "--write-sub")
|
||||
table.insert(command, "--skip-download")
|
||||
if not_empty(opts.sub_format) then
|
||||
table.insert(command, "--sub-format")
|
||||
table.insert(command, opts.sub_format)
|
||||
end
|
||||
if select_range_mode > 0 then
|
||||
mp.osd_message("Range mode is not available for subtitle-only download", 10)
|
||||
is_downloading = false
|
||||
return
|
||||
end
|
||||
elseif download_type == DOWNLOAD.AUDIO then
|
||||
table.insert(command, "--extract-audio")
|
||||
if not_empty(opts.audio_format) then
|
||||
table.insert(command, "--audio-format")
|
||||
table.insert(command, opts.audio_format)
|
||||
end
|
||||
if not_empty(opts.audio_quality) then
|
||||
table.insert(command, "--audio-quality")
|
||||
table.insert(command, opts.audio_quality)
|
||||
end
|
||||
if select_range_mode > 0 then
|
||||
local start_time_str = tostring(start_time_seconds)
|
||||
local end_time_str = tostring(end_time_seconds)
|
||||
table.insert(command, "--external-downloader")
|
||||
table.insert(command, "ffmpeg")
|
||||
table.insert(command, "--external-downloader-args")
|
||||
table.insert(command, "-loglevel warning -nostats -hide_banner -ss ".. start_time_str .. " -to " .. end_time_str .. " -avoid_negative_ts make_zero")
|
||||
end
|
||||
else --DOWNLOAD.VIDEO or DOWNLOAD.VIDEO_EMBED_SUBTITLE
|
||||
if download_type == DOWNLOAD.VIDEO_EMBED_SUBTITLE then
|
||||
table.insert(command, "--all-subs")
|
||||
table.insert(command, "--write-sub")
|
||||
table.insert(command, "--embed-subs")
|
||||
if not_empty(opts.sub_format) then
|
||||
table.insert(command, "--sub-format")
|
||||
table.insert(command, opts.sub_format)
|
||||
end
|
||||
end
|
||||
if not_empty(opts.video_format) then
|
||||
table.insert(command, "--format")
|
||||
table.insert(command, opts.video_format)
|
||||
end
|
||||
if not_empty(opts.recode_video) then
|
||||
table.insert(command, "--recode-video")
|
||||
table.insert(command, opts.recode_video)
|
||||
end
|
||||
end
|
||||
if not_empty(opts.cookies) then
|
||||
table.insert(command, "--cookies")
|
||||
table.insert(command, opts.cookies)
|
||||
end
|
||||
table.insert(command, url)
|
||||
|
||||
elseif select_range_mode > 0 and
|
||||
(download_type == DOWNLOAD.VIDEO or download_type == DOWNLOAD.VIDEO_EMBED_SUBTITLE) then
|
||||
|
||||
-- Show download indicator
|
||||
mp.set_osd_ass(0, 0, "{\\an9}{\\fs12}⌛🔗")
|
||||
|
||||
start_time_seconds = math.floor(start_time_seconds)
|
||||
end_time_seconds = math.ceil(end_time_seconds)
|
||||
|
||||
local start_time_str = tostring(start_time_seconds)
|
||||
local end_time_str = tostring(end_time_seconds)
|
||||
|
||||
-- Add time to the file name of the video
|
||||
local filename_format
|
||||
-- Insert start time/end time
|
||||
if not_empty(opts.filename) then
|
||||
if opts.filename:find("%%%(start_time%)") ~= nil then
|
||||
-- Found "start_time" -> replace it
|
||||
filename_format = tostring(opts.filename:
|
||||
gsub("%%%(start_time%)[^diouxXeEfFgGcrs]*[diouxXeEfFgGcrs]", start_time_str):
|
||||
gsub("%%%(end_time%)[^diouxXeEfFgGcrs]*[diouxXeEfFgGcrs]", end_time_str))
|
||||
else
|
||||
local ext_pattern = "%(ext)s"
|
||||
if opts.filename:sub(-#ext_pattern) == ext_pattern then
|
||||
-- Insert before ext
|
||||
filename_format = opts.filename:sub(1, #(opts.filename) - #ext_pattern) ..
|
||||
start_time_str .. "-" ..
|
||||
end_time_str .. ".%(ext)s"
|
||||
else
|
||||
-- append at end
|
||||
filename_format = opts.filename .. start_time_str .. "-" .. end_time_str
|
||||
end
|
||||
end
|
||||
else
|
||||
-- default youtube-dl filename pattern
|
||||
filename_format = "%(title)s-%(id)s." .. start_time_str .. "-" .. end_time_str .. ".%(ext)s"
|
||||
end
|
||||
|
||||
-- Find a suitable format
|
||||
local format = "bestvideo[ext*=mp4]+bestaudio/best[ext*=mp4]/best"
|
||||
if opts.video_format == nil or opts.video_format == "" then
|
||||
format = format
|
||||
elseif opts.video_format == "best" then
|
||||
-- "best" works, because its a single file stream
|
||||
format = "best"
|
||||
elseif opts.video_format:find("mp4") ~= nil then
|
||||
-- probably a mp4 format, so use it
|
||||
format = opts.video_format
|
||||
else
|
||||
-- custom format, no "mp4" found -> use default
|
||||
msg.warn("Select range mode requires a .mp4 format or \"best\", found " ..
|
||||
opts.video_format ..
|
||||
"\nUsing default format instead: " .. format)
|
||||
end
|
||||
|
||||
-- Get the download url of the video file
|
||||
-- e.g.: youtube-dl -g -f bestvideo[ext*=mp4]+bestaudio/best[ext*=mp4]/best -s --get-filename https://www.youtube.com/watch?v=abcdefg
|
||||
command = {"youtube-dl"}
|
||||
if opts.restrict_filenames then
|
||||
table.insert(command, "--restrict-filenames")
|
||||
end
|
||||
if not_empty(opts.cookies) then
|
||||
table.insert(command, "--cookies")
|
||||
table.insert(command, opts.cookies)
|
||||
end
|
||||
table.insert(command, "-g")
|
||||
table.insert(command, "--no-playlist")
|
||||
table.insert(command, "-f")
|
||||
table.insert(command, format)
|
||||
table.insert(command, "-o")
|
||||
table.insert(command, filename_format)
|
||||
table.insert(command, "-s")
|
||||
table.insert(command, "--get-filename")
|
||||
table.insert(command, url)
|
||||
|
||||
msg.debug("info exec: " .. table.concat(command, " "))
|
||||
local info_status, info_stdout, info_stderr = exec(command, true, true)
|
||||
if info_status ~= 0 then
|
||||
mp.set_osd_ass(0, 0, "")
|
||||
mp.osd_message("Could not retieve download stream url: status=" .. tostring(info_status) .. "\n" ..
|
||||
ass0 .. "{\\fs8} " .. info_stdout:gsub("\r", "") .."\n" .. info_stderr:gsub("\r", "") .. ass1, 20)
|
||||
msg.debug("info_stdout:\n" .. info_stdout)
|
||||
msg.debug("info_stderr:\n" .. info_stderr)
|
||||
mp.set_osd_ass(0, 0, "")
|
||||
is_downloading = false
|
||||
return
|
||||
end
|
||||
|
||||
-- Split result into lines
|
||||
local info_lines = {}
|
||||
local last_index = 0
|
||||
local info_lines_N = 0
|
||||
while true do
|
||||
local start_i, end_i = info_stdout:find("\n", last_index, true)
|
||||
if start_i then
|
||||
local line = tostring(trim(info_stdout:sub(last_index, start_i)))
|
||||
if line ~= "" then
|
||||
table.insert(info_lines, line)
|
||||
info_lines_N = info_lines_N + 1
|
||||
end
|
||||
else
|
||||
break
|
||||
end
|
||||
last_index = end_i + 1
|
||||
end
|
||||
|
||||
if info_lines_N < 2 then
|
||||
mp.set_osd_ass(0, 0, "")
|
||||
mp.osd_message("Could not extract download stream urls and filename from output\n" ..
|
||||
ass0 .. "{\\fs8} " .. info_stdout:gsub("\r", "") .."\n" .. info_stderr:gsub("\r", "") .. ass1, 20)
|
||||
msg.debug("info_stdout:\n" .. info_stdout)
|
||||
msg.debug("info_stderr:\n" .. info_stderr)
|
||||
mp.set_osd_ass(0, 0, "")
|
||||
is_downloading = false
|
||||
return
|
||||
end
|
||||
range_mode_file_name = info_lines[info_lines_N]
|
||||
table.remove(info_lines)
|
||||
|
||||
if download_type == DOWNLOAD.VIDEO_EMBED_SUBTITLE then
|
||||
-- youtube-dl --write-sub --skip-download https://www.youtube.com/watch?v=abcdefg -o "temp.%(ext)s"
|
||||
command = {"youtube-dl", "--write-sub", "--skip-download", "--sub-lang", opts.sub_lang}
|
||||
if not_empty(opts.sub_format) then
|
||||
table.insert(command, "--sub-format")
|
||||
table.insert(command, opts.sub_format)
|
||||
end
|
||||
local randomName = "tmp_" .. tostring(math.random())
|
||||
table.insert(command, "-o")
|
||||
table.insert(command, randomName .. ".%(ext)s")
|
||||
table.insert(command, url)
|
||||
|
||||
-- Start subtitle download
|
||||
msg.debug("exec: " .. table.concat(command, " "))
|
||||
local subtitle_status, subtitle_stdout, subtitle_stderr = exec(command, true, true)
|
||||
if subtitle_status == 0 and subtitle_stdout:find(randomName) then
|
||||
local i, j = subtitle_stdout:find(randomName .. "[^\n]+")
|
||||
range_mode_subtitle_file_name = trim(subtitle_stdout:sub(i, j))
|
||||
if range_mode_subtitle_file_name ~= "" then
|
||||
if range_mode_file_name:sub(-4) ~= ".mkv" then
|
||||
-- Only mkv supports all kinds of subtitle formats
|
||||
range_mode_file_name = range_mode_file_name:sub(1,-4) .. "mkv"
|
||||
end
|
||||
end
|
||||
else
|
||||
mp.osd_message("Could not find a suitable subtitle")
|
||||
msg.debug("subtitle_stdout:\n" .. subtitle_stdout)
|
||||
msg.debug("subtitle_stderr:\n" .. subtitle_stderr)
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
-- Download earlier (cut off afterwards)
|
||||
start_time_offset = math.min(15, start_time_seconds)
|
||||
start_time_seconds = start_time_seconds - start_time_offset
|
||||
|
||||
start_time_str = tostring(start_time_seconds)
|
||||
end_time_str = tostring(end_time_seconds)
|
||||
|
||||
command = {"ffmpeg", "-loglevel", "warning", "-nostats", "-hide_banner", "-y"}
|
||||
for _, value in ipairs(info_lines) do
|
||||
table.insert(command, "-ss")
|
||||
table.insert(command, start_time_str)
|
||||
table.insert(command, "-to")
|
||||
table.insert(command, end_time_str)
|
||||
table.insert(command, "-i")
|
||||
table.insert(command, value)
|
||||
end
|
||||
if not_empty(range_mode_subtitle_file_name) then
|
||||
table.insert(command, "-ss")
|
||||
table.insert(command, start_time_str)
|
||||
table.insert(command, "-i")
|
||||
table.insert(command, range_mode_subtitle_file_name)
|
||||
table.insert(command, "-to") -- To must be after input for subtitle
|
||||
table.insert(command, end_time_str)
|
||||
end
|
||||
table.insert(command, "-c")
|
||||
table.insert(command, "copy")
|
||||
table.insert(command, range_mode_file_name)
|
||||
|
||||
disable_select_range()
|
||||
end
|
||||
|
||||
-- Show download indicator
|
||||
mp.set_osd_ass(0, 0, "{\\an9}{\\fs12}⌛💾")
|
||||
|
||||
-- Start download
|
||||
msg.debug("exec: " .. table.concat(command, " "))
|
||||
local status, stdout, stderr = exec(command, true, true)
|
||||
|
||||
if status == 0 and range_mode_file_name ~= nil then
|
||||
mp.set_osd_ass(0, 0, "{\\an9}{\\fs12}⌛🔨")
|
||||
|
||||
-- Cut first few seconds to fix errors
|
||||
local start_time_offset_str = tostring(start_time_offset)
|
||||
if #start_time_offset_str == 1 then
|
||||
start_time_offset_str = "0" .. start_time_offset_str
|
||||
end
|
||||
local max_length = end_time_seconds - start_time_seconds + start_time_offset + 12
|
||||
local tmp_file_name = range_mode_file_name .. ".tmp." .. range_mode_file_name:sub(-3)
|
||||
command = {"ffmpeg", "-loglevel", "warning", "-nostats", "-hide_banner", "-y",
|
||||
"-i", range_mode_file_name, "-ss", "00:00:" .. start_time_offset_str,
|
||||
"-c", "copy", "-avoid_negative_ts", "make_zero", "-t", tostring(max_length), tmp_file_name}
|
||||
msg.debug("mux exec: " .. table.concat(command, " "))
|
||||
local muxstatus, muxstdout, muxstderr = exec(command, true, true)
|
||||
if muxstatus ~= 0 and not_empty(muxstderr) then
|
||||
msg.warn("Remux log:" .. tostring(muxstdout))
|
||||
msg.warn("Remux errorlog:" .. tostring(muxstderr))
|
||||
end
|
||||
if muxstatus == 0 then
|
||||
os.remove(range_mode_file_name)
|
||||
os.rename(tmp_file_name, range_mode_file_name)
|
||||
if not_empty(range_mode_subtitle_file_name) then
|
||||
os.remove(range_mode_subtitle_file_name)
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
|
||||
is_downloading = false
|
||||
|
||||
-- Hide download indicator
|
||||
mp.set_osd_ass(0, 0, "")
|
||||
|
||||
local wrote_error_log = false
|
||||
if stderr ~= nil and not_empty(opts.log_file) and not_empty(stderr) then
|
||||
-- Write stderr to log file
|
||||
local title = mp.get_property("media-title")
|
||||
local file = io.open (opts.log_file , "a+")
|
||||
file:write("\n[")
|
||||
file:write(start_time)
|
||||
file:write("] ")
|
||||
file:write(url)
|
||||
file:write("\n[\"")
|
||||
file:write(title)
|
||||
file:write("\"]\n")
|
||||
file:write(stderr)
|
||||
file:close()
|
||||
wrote_error_log = true
|
||||
end
|
||||
|
||||
if (status ~= 0) then
|
||||
mp.osd_message("download failed:\n" .. tostring(stderr), 10)
|
||||
msg.error("URL: " .. tostring(url))
|
||||
msg.error("Return status code: " .. tostring(status))
|
||||
msg.verbose(tostring(stderr))
|
||||
msg.verbose(tostring(stdout))
|
||||
return
|
||||
end
|
||||
|
||||
if string.find(stdout, "has already been recorded in archive") ~=nil then
|
||||
mp.osd_message("Has already been recorded in archive", 5)
|
||||
return
|
||||
end
|
||||
|
||||
-- Retrieve the file name
|
||||
local filename = nil
|
||||
if range_mode_file_name == nil and stdout then
|
||||
local i, j, last_i, start_index = 0
|
||||
while i ~= nil do
|
||||
last_i, start_index = i, j
|
||||
i, j = stdout:find ("Destination: ",j, true)
|
||||
end
|
||||
|
||||
if last_i ~= nil then
|
||||
local end_index = stdout:find ("\n", start_index, true)
|
||||
if end_index ~= nil and start_index ~= nil then
|
||||
filename = trim(stdout:sub(start_index, end_index))
|
||||
end
|
||||
end
|
||||
elseif not_empty(range_mode_file_name) then
|
||||
filename = range_mode_file_name
|
||||
end
|
||||
|
||||
local osd_text = "Download succeeded\n"
|
||||
local osd_time = 5
|
||||
-- Find filename or directory
|
||||
if filename then
|
||||
local filepath
|
||||
local basepath
|
||||
if filename:find("/") == nil and filename:find("\\") == nil then
|
||||
basepath = utils.getcwd()
|
||||
filepath = path_join(utils.getcwd(), filename)
|
||||
else
|
||||
basepath = ""
|
||||
filepath = filename
|
||||
end
|
||||
|
||||
if filepath:len() < 100 then
|
||||
osd_text = osd_text .. ass0 .. "{\\fs12} " .. filepath .. " {\\fs20}" .. ass1
|
||||
elseif basepath == "" then
|
||||
osd_text = osd_text .. ass0 .. "{\\fs8} " .. filepath .. " {\\fs20}" .. ass1
|
||||
else
|
||||
osd_text = osd_text .. ass0 .. "{\\fs11} " .. basepath .. "\n" .. filename .. " {\\fs20}" .. ass1
|
||||
end
|
||||
if wrote_error_log then
|
||||
-- Write filename and end time to log file
|
||||
local file = io.open (opts.log_file , "a+")
|
||||
file:write("[" .. filepath .. "]\n")
|
||||
file:write(os.date("[end %c]\n"))
|
||||
file:close()
|
||||
end
|
||||
else
|
||||
if wrote_error_log then
|
||||
-- Write directory and end time to log file
|
||||
local file = io.open (opts.log_file , "a+")
|
||||
file:write("[" .. utils.getcwd() .. "]\n")
|
||||
file:write(os.date("[end %c]\n"))
|
||||
file:close()
|
||||
end
|
||||
osd_text = osd_text .. utils.getcwd()
|
||||
end
|
||||
|
||||
-- Show warnings
|
||||
if not_empty(stderr) then
|
||||
msg.warn("Errorlog:" .. tostring(stderr))
|
||||
if stderr:find("incompatible for merge") == nil then
|
||||
local i = stderr:find("Input #")
|
||||
if i ~= nil then
|
||||
stderr = stderr:sub(i)
|
||||
end
|
||||
osd_text = osd_text .. "\n" .. ass0 .. "{\\fs8} " .. stderr:gsub("\r", "") .. ass1
|
||||
osd_time = osd_time + 5
|
||||
end
|
||||
end
|
||||
|
||||
mp.osd_message(osd_text, osd_time)
|
||||
end
|
||||
|
||||
local function select_range_show()
|
||||
local status
|
||||
if select_range_mode > 0 then
|
||||
if select_range_mode == 2 then
|
||||
status = "Download range: Fine tune\n← → start time\n↓ ↑ end time\n" ..
|
||||
tostring(opts.select_range_binding) .. " next mode"
|
||||
elseif select_range_mode == 1 then
|
||||
status = "Download range: Select interval\n← start here\n→ end here\n↓from beginning\n↑til end\n" ..
|
||||
tostring(opts.select_range_binding) .. " next mode"
|
||||
end
|
||||
mp.osd_message("Start: " .. start_time_formated .. "\nEnd: " .. end_time_formated .. "\n" .. status, 30)
|
||||
else
|
||||
status = "Download range: Disabled (download full length)"
|
||||
mp.osd_message(status, 3)
|
||||
end
|
||||
end
|
||||
|
||||
local function select_range_set_left()
|
||||
if select_range_mode == 2 then
|
||||
start_time_seconds = math.max(0, start_time_seconds - 1)
|
||||
if start_time_seconds < 86400 then
|
||||
start_time_formated = os.date("!%H:%M:%S", start_time_seconds)
|
||||
else
|
||||
start_time_formated = tostring(start_time_seconds) .. "s"
|
||||
end
|
||||
elseif select_range_mode == 1 then
|
||||
start_time_seconds = mp.get_property_number("time-pos")
|
||||
start_time_formated = mp.command_native({"expand-text","${time-pos}"})
|
||||
end
|
||||
select_range_show()
|
||||
end
|
||||
|
||||
local function select_range_set_start()
|
||||
if select_range_mode == 2 then
|
||||
end_time_seconds = math.max(1, end_time_seconds - 1)
|
||||
if end_time_seconds < 86400 then
|
||||
end_time_formated = os.date("!%H:%M:%S", end_time_seconds)
|
||||
else
|
||||
end_time_formated = tostring(end_time_seconds) .. "s"
|
||||
end
|
||||
elseif select_range_mode == 1 then
|
||||
start_time_seconds = 0
|
||||
start_time_formated = "00:00:00"
|
||||
end
|
||||
select_range_show()
|
||||
end
|
||||
|
||||
local function select_range_set_end()
|
||||
if select_range_mode == 2 then
|
||||
end_time_seconds = math.min(mp.get_property_number("duration"), end_time_seconds + 1)
|
||||
if end_time_seconds < 86400 then
|
||||
end_time_formated = os.date("!%H:%M:%S", end_time_seconds)
|
||||
else
|
||||
end_time_formated = tostring(end_time_seconds) .. "s"
|
||||
end
|
||||
elseif select_range_mode == 1 then
|
||||
end_time_seconds = mp.get_property_number("duration")
|
||||
end_time_formated = mp.command_native({"expand-text","${duration}"})
|
||||
end
|
||||
select_range_show()
|
||||
end
|
||||
|
||||
local function select_range_set_right()
|
||||
if select_range_mode == 2 then
|
||||
start_time_seconds = math.min(mp.get_property_number("duration") - 1, start_time_seconds + 1)
|
||||
if start_time_seconds < 86400 then
|
||||
start_time_formated = os.date("!%H:%M:%S", start_time_seconds)
|
||||
else
|
||||
start_time_formated = tostring(start_time_seconds) .. "s"
|
||||
end
|
||||
elseif select_range_mode == 1 then
|
||||
end_time_seconds = mp.get_property_number("time-pos")
|
||||
end_time_formated = mp.command_native({"expand-text","${time-pos}"})
|
||||
end
|
||||
select_range_show()
|
||||
end
|
||||
|
||||
|
||||
local function select_range()
|
||||
-- Cycle through modes
|
||||
if select_range_mode == 2 then
|
||||
-- Disable range mode
|
||||
disable_select_range()
|
||||
elseif select_range_mode == 1 then
|
||||
-- Switch to "fine tune" mode
|
||||
select_range_mode = 2
|
||||
else
|
||||
select_range_mode = 1
|
||||
-- Add keybinds for arrow keys
|
||||
mp.add_key_binding("up", "select-range-set-up", select_range_set_end)
|
||||
mp.add_key_binding("down", "select-range-set-down", select_range_set_start)
|
||||
mp.add_key_binding("left", "select-range-set-left", select_range_set_left)
|
||||
mp.add_key_binding("right", "select-range-set-right", select_range_set_right)
|
||||
|
||||
-- Defaults
|
||||
if start_time_seconds == nil then
|
||||
start_time_seconds = mp.get_property_number("time-pos")
|
||||
start_time_formated = mp.command_native({"expand-text","${time-pos}"})
|
||||
end_time_seconds = mp.get_property_number("duration")
|
||||
end_time_formated = mp.command_native({"expand-text","${duration}"})
|
||||
end
|
||||
end
|
||||
select_range_show()
|
||||
end
|
||||
|
||||
local function download_video()
|
||||
return download(DOWNLOAD.VIDEO)
|
||||
end
|
||||
|
||||
local function download_audio()
|
||||
return download(DOWNLOAD.AUDIO)
|
||||
end
|
||||
|
||||
local function download_subtitle()
|
||||
return download(DOWNLOAD.SUBTITLE)
|
||||
end
|
||||
|
||||
local function download_embed_subtitle()
|
||||
return download(DOWNLOAD.VIDEO_EMBED_SUBTITLE)
|
||||
end
|
||||
|
||||
-- keybind
|
||||
if not_empty(opts.download_video_binding) then
|
||||
mp.add_key_binding(opts.download_video_binding, "download-video", download_video)
|
||||
end
|
||||
if not_empty(opts.download_audio_binding) then
|
||||
mp.add_key_binding(opts.download_audio_binding, "download-audio", download_audio)
|
||||
end
|
||||
if not_empty(opts.download_subtitle_binding) then
|
||||
mp.add_key_binding(opts.download_subtitle_binding, "download-subtitle", download_subtitle)
|
||||
end
|
||||
if not_empty(opts.download_video_embed_subtitle_binding) then
|
||||
mp.add_key_binding(opts.download_video_embed_subtitle_binding, "download-embed-subtitle", download_embed_subtitle)
|
||||
end
|
||||
if not_empty(opts.select_range_binding) then
|
||||
mp.add_key_binding(opts.select_range_binding, "select-range-start", select_range)
|
||||
end
|
||||
@@ -0,0 +1,275 @@
|
||||
-- youtube-quality.lua
|
||||
--
|
||||
-- Change youtube video quality on the fly.
|
||||
--
|
||||
-- Diplays a menu that lets you switch to different ytdl-format settings while
|
||||
-- you're in the middle of a video (just like you were using the web player).
|
||||
--
|
||||
-- Bound to ctrl-f by default.
|
||||
|
||||
local mp = require 'mp'
|
||||
local utils = require 'mp.utils'
|
||||
local msg = require 'mp.msg'
|
||||
local assdraw = require 'mp.assdraw'
|
||||
|
||||
local opts = {
|
||||
--key bindings
|
||||
toggle_menu_binding = "ctrl+f",
|
||||
up_binding = "UP",
|
||||
down_binding = "DOWN",
|
||||
select_binding = "ENTER",
|
||||
|
||||
--formatting / cursors
|
||||
selected_and_active = "▶ - ",
|
||||
selected_and_inactive = "● - ",
|
||||
unselected_and_active = "▷ - ",
|
||||
unselected_and_inactive = "○ - ",
|
||||
|
||||
--font size scales by window, if false requires larger font and padding sizes
|
||||
scale_playlist_by_window=false,
|
||||
|
||||
--playlist ass style overrides inside curly brackets, \keyvalue is one field, extra \ for escape in lua
|
||||
--example {\\fnUbuntu\\fs10\\b0\\bord1} equals: font=Ubuntu, size=10, bold=no, border=1
|
||||
--read http://docs.aegisub.org/3.2/ASS_Tags/ for reference of tags
|
||||
--undeclared tags will use default osd settings
|
||||
--these styles will be used for the whole playlist. More specific styling will need to be hacked in
|
||||
--
|
||||
--(a monospaced font is recommended but not required)
|
||||
style_ass_tags = "{\\fnFuraCode Nerd Font}",
|
||||
|
||||
--paddings for top left corner
|
||||
text_padding_x = 5,
|
||||
text_padding_y = 5,
|
||||
|
||||
--other
|
||||
menu_timeout = 10,
|
||||
|
||||
--use youtube-dl to fetch a list of available formats (overrides quality_strings)
|
||||
fetch_formats = true,
|
||||
|
||||
--default menu entries
|
||||
quality_strings=[[
|
||||
[
|
||||
{"4320p" : "bestvideo[height<=?4320p]+bestaudio/best"},
|
||||
{"2160p" : "bestvideo[height<=?2160]+bestaudio/best"},
|
||||
{"1440p" : "bestvideo[height<=?1440]+bestaudio/best"},
|
||||
{"1080p" : "bestvideo[height<=?1080]+bestaudio/best"},
|
||||
{"720p" : "bestvideo[height<=?720]+bestaudio/best"},
|
||||
{"480p" : "bestvideo[height<=?480]+bestaudio/best"},
|
||||
{"360p" : "bestvideo[height<=?360]+bestaudio/best"},
|
||||
{"240p" : "bestvideo[height<=?240]+bestaudio/best"},
|
||||
{"144p" : "bestvideo[height<=?144]+bestaudio/best"}
|
||||
]
|
||||
]],
|
||||
}
|
||||
(require 'mp.options').read_options(opts, "youtube-quality")
|
||||
opts.quality_strings = utils.parse_json(opts.quality_strings)
|
||||
|
||||
local destroyer = nil
|
||||
|
||||
|
||||
function show_menu()
|
||||
local selected = 1
|
||||
local active = 0
|
||||
local current_ytdl_format = mp.get_property("ytdl-format")
|
||||
msg.verbose("current ytdl-format: "..current_ytdl_format)
|
||||
local num_options = 0
|
||||
local options = {}
|
||||
|
||||
|
||||
if opts.fetch_formats then
|
||||
options, num_options = download_formats()
|
||||
end
|
||||
|
||||
if next(options) == nil then
|
||||
for i,v in ipairs(opts.quality_strings) do
|
||||
num_options = num_options + 1
|
||||
for k,v2 in pairs(v) do
|
||||
options[i] = {label = k, format=v2}
|
||||
if v2 == current_ytdl_format then
|
||||
active = i
|
||||
selected = active
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--set the cursor to the currently format
|
||||
for i,v in ipairs(options) do
|
||||
if v.format == current_ytdl_format then
|
||||
active = i
|
||||
selected = active
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
function selected_move(amt)
|
||||
selected = selected + amt
|
||||
if selected < 1 then selected = num_options
|
||||
elseif selected > num_options then selected = 1 end
|
||||
timeout:kill()
|
||||
timeout:resume()
|
||||
draw_menu()
|
||||
end
|
||||
function choose_prefix(i)
|
||||
if i == selected and i == active then return opts.selected_and_active
|
||||
elseif i == selected then return opts.selected_and_inactive end
|
||||
|
||||
if i ~= selected and i == active then return opts.unselected_and_active
|
||||
elseif i ~= selected then return opts.unselected_and_inactive end
|
||||
return "> " --shouldn't get here.
|
||||
end
|
||||
|
||||
function draw_menu()
|
||||
local ass = assdraw.ass_new()
|
||||
|
||||
ass:pos(opts.text_padding_x, opts.text_padding_y)
|
||||
ass:append(opts.style_ass_tags)
|
||||
|
||||
for i,v in ipairs(options) do
|
||||
ass:append(choose_prefix(i)..v.label.."\\N")
|
||||
end
|
||||
|
||||
local w, h = mp.get_osd_size()
|
||||
if opts.scale_playlist_by_window then w,h = 0, 0 end
|
||||
mp.set_osd_ass(w, h, ass.text)
|
||||
end
|
||||
|
||||
function destroy()
|
||||
timeout:kill()
|
||||
mp.set_osd_ass(0,0,"")
|
||||
mp.remove_key_binding("move_up")
|
||||
mp.remove_key_binding("move_down")
|
||||
mp.remove_key_binding("select")
|
||||
mp.remove_key_binding("escape")
|
||||
destroyer = nil
|
||||
end
|
||||
timeout = mp.add_periodic_timer(opts.menu_timeout, destroy)
|
||||
destroyer = destroy
|
||||
|
||||
mp.add_forced_key_binding(opts.up_binding, "move_up", function() selected_move(-1) end, {repeatable=true})
|
||||
mp.add_forced_key_binding(opts.down_binding, "move_down", function() selected_move(1) end, {repeatable=true})
|
||||
mp.add_forced_key_binding(opts.select_binding, "select", function()
|
||||
destroy()
|
||||
mp.set_property("ytdl-format", options[selected].format)
|
||||
reload_resume()
|
||||
end)
|
||||
mp.add_forced_key_binding(opts.toggle_menu_binding, "escape", destroy)
|
||||
|
||||
draw_menu()
|
||||
return
|
||||
end
|
||||
|
||||
local ytdl = {
|
||||
path = "youtube-dl",
|
||||
searched = false,
|
||||
blacklisted = {}
|
||||
}
|
||||
|
||||
format_cache={}
|
||||
function download_formats()
|
||||
local function exec(args)
|
||||
local ret = utils.subprocess({args = args})
|
||||
return ret.status, ret.stdout, ret
|
||||
end
|
||||
|
||||
local function table_size(t)
|
||||
s = 0
|
||||
for i,v in ipairs(t) do
|
||||
s = s+1
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
local url = mp.get_property("path")
|
||||
|
||||
url = string.gsub(url, "ytdl://", "") -- Strip possible ytdl:// prefix.
|
||||
|
||||
-- don't fetch the format list if we already have it
|
||||
if format_cache[url] ~= nil then
|
||||
local res = format_cache[url]
|
||||
return res, table_size(res)
|
||||
end
|
||||
mp.osd_message("fetching available formats with youtube-dl...", 60)
|
||||
|
||||
if not (ytdl.searched) then
|
||||
local ytdl_mcd = mp.find_config_file("youtube-dl")
|
||||
if not (ytdl_mcd == nil) then
|
||||
msg.verbose("found youtube-dl at: " .. ytdl_mcd)
|
||||
ytdl.path = ytdl_mcd
|
||||
end
|
||||
ytdl.searched = true
|
||||
end
|
||||
|
||||
local command = {ytdl.path, "--no-warnings", "--no-playlist", "-J"}
|
||||
table.insert(command, url)
|
||||
local es, json, result = exec(command)
|
||||
|
||||
if (es < 0) or (json == nil) or (json == "") then
|
||||
mp.osd_message("fetching formats failed...", 1)
|
||||
msg.error("failed to get format list: " .. err)
|
||||
return {}, 0
|
||||
end
|
||||
|
||||
local json, err = utils.parse_json(json)
|
||||
|
||||
if (json == nil) then
|
||||
mp.osd_message("fetching formats failed...", 1)
|
||||
msg.error("failed to parse JSON data: " .. err)
|
||||
return {}, 0
|
||||
end
|
||||
|
||||
res = {}
|
||||
msg.verbose("youtube-dl succeeded!")
|
||||
for i,v in ipairs(json.formats) do
|
||||
if v.vcodec ~= "none" then
|
||||
local fps = v.fps and v.fps.."fps" or ""
|
||||
local resolution = string.format("%sx%s", v.width, v.height)
|
||||
local l = string.format("%-9s %-5s (%-4s / %s)", resolution, fps, v.ext, v.vcodec)
|
||||
local f = string.format("%s+bestaudio/best", v.format_id)
|
||||
table.insert(res, {label=l, format=f, width=v.width })
|
||||
end
|
||||
end
|
||||
|
||||
table.sort(res, function(a, b) return a.width > b.width end)
|
||||
|
||||
mp.osd_message("", 0)
|
||||
format_cache[url] = res
|
||||
return res, table_size(res)
|
||||
end
|
||||
|
||||
|
||||
-- register script message to show menu
|
||||
mp.register_script_message("toggle-quality-menu",
|
||||
function()
|
||||
if destroyer ~= nil then
|
||||
destroyer()
|
||||
else
|
||||
show_menu()
|
||||
end
|
||||
end)
|
||||
|
||||
-- keybind to launch menu
|
||||
mp.add_key_binding(opts.toggle_menu_binding, "quality-menu", show_menu)
|
||||
|
||||
-- special thanks to reload.lua (https://github.com/4e6/mpv-reload/)
|
||||
function reload_resume()
|
||||
local playlist_pos = mp.get_property_number("playlist-pos")
|
||||
local reload_duration = mp.get_property_native("duration")
|
||||
local time_pos = mp.get_property("time-pos")
|
||||
|
||||
mp.set_property_number("playlist-pos", playlist_pos)
|
||||
|
||||
-- Tries to determine live stream vs. pre-recordered VOD. VOD has non-zero
|
||||
-- duration property. When reloading VOD, to keep the current time position
|
||||
-- we should provide offset from the start. Stream doesn't have fixed start.
|
||||
-- Decent choice would be to reload stream from it's current 'live' positon.
|
||||
-- That's the reason we don't pass the offset when reloading streams.
|
||||
if reload_duration and reload_duration > 0 then
|
||||
local function seeker()
|
||||
mp.commandv("seek", time_pos, "absolute")
|
||||
mp.unregister_event(seeker)
|
||||
end
|
||||
mp.register_event("file-loaded", seeker)
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user