Skip to content

Instantly share code, notes, and snippets.

@myjian
Created September 30, 2018 07:21
Show Gist options
  • Save myjian/43564ea77eb612c386a6c4e8ce883ebc to your computer and use it in GitHub Desktop.
Save myjian/43564ea77eb612c386a6c4e8ce883ebc to your computer and use it in GitHub Desktop.
mpv user script to navigate to previous/next file
/**
* mpv user script to navigate to previous/next file
* Usage: Add the following lines to input.conf
*
* MBTN_BACK script-message navigate prev
* MBTN_FORWARD script-message navigate next
* Shift+LEFT script-message navigate prev
* Shift+RIGHT script-message navigate next
* WHEEL_LEFT script-message navigate prev
* WHEEL_RIGHT script-message navigate next
*/
var Settings = {
/** Types we consider to load. */
FILE_TYPES: [
"webm", "mkv", "mp4", "mov", "mpg",
"mpeg", "m4v", "wmv", "avi", "ogv",
"rmvb", "flv", "3gp", "mp3", "wav",
"flac", "ogv", "m4a", "wma", "ts"
]
};
var cacheSiblings = null;
var cacheDir = null;
function getExtension(path) {
var dotIndex = path.lastIndexOf(".");
if (dotIndex >= 0) {
return path.substring(dotIndex + 1).toLowerCase();
}
return "";
}
function isSupportedFileType(path) {
var ext = getExtension(path);
return Settings.FILE_TYPES.indexOf(ext) >= 0;
}
function playLoadedFile() {
mp.unregister_event(playLoadedFile);
if (mp.get_property_bool("pause")) {
mp.set_property_bool("pause", false);
}
}
/**
* Script message handler.
* direction: "prev" or "next"
*/
function handleNavigate(direction) {
var startTime = Date.now();
// Get path of the current file
var path = mp.get_property("path");
var pathParts = mp.utils.split_path(path);
var dir = pathParts[0];
var currentFilename = pathParts[1];
var pl_count = mp.get_property_number("playlist-count", 1);
if (pl_count > 1 || (pl_count == 1 && !isSupportedFileType(currentFilename))) {
return;
}
var siblings = cacheSiblings;
if (cacheDir != dir) {
siblings = mp.utils.readdir(dir, "all");
mp.msg.info("Reading current dir took " + (Date.now() - startTime) + "ms.");
// Filter unsupported extensions
siblings = siblings.filter(isSupportedFileType);
siblings.sort();
cacheSiblings = siblings;
cacheDir = dir;
}
// Find the index of current file
var currentPos = siblings.indexOf(currentFilename);
if (currentPos < 0) {
return;
}
// Prepare the path for previous/next file
var nextFile = (direction == "prev") ? siblings[currentPos-1] : siblings[currentPos+1];
if (!nextFile) {
mp.osd_message("This is the first/last file in the folder.");
return;
}
nextFile = mp.utils.join_path(dir, nextFile);
mp.register_event("file-loaded", playLoadedFile);
mp.msg.info("handleNavigate " + direction + " took " + (Date.now() - startTime) + "ms.");
mp.commandv("loadfile", nextFile, "replace");
}
mp.register_script_message("navigate", handleNavigate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment