-- ============================================================================ -- MPV-Trimmer.lua -- Advanced Trim & Cut script for MPV with GPU-acceleration, filesize capping, -- two-click corner crop area selection, audio muting, and real-time progress. -- ============================================================================ local mp = require 'mp' local utils = require 'mp.utils' local msg = require 'mp.msg' -- --- Global State Variables --- local start_time = nil local end_time = nil local cut_counter = 0 local is_muted = false local is_encoding = false local active_async_cmd_id = nil local last_percent = 0 local is_windows = package.config:sub(1,1) == '\\' local home_dir = os.getenv("HOME") or (is_windows and os.getenv("USERPROFILE") or "/home/user") local temp_dir = os.getenv("TEMP") or "/tmp" -- --- USER CONFIGURATION --- -- Hardware Acceleration Settings for GPU Encoders: -- NVIDIA: "h264_nvenc" | AMD: "h264_amf" | Intel: "h264_qsv" local HW_VIDEO_CODEC = "h264_nvenc" -- Output Directory Mode -- "source_dir" = Save in same directory as the source video. -- "default_dir" = Save to Desktop/mpvstreamcut. local current_output_mode = "source_dir" local OUTPUT_DIR_DEFAULT = utils.join_path(home_dir, "Desktop/mpvstreamcut") -- Temp files local TEMP_VIDEO = utils.join_path(temp_dir, "mpv_temp_video.mp4") local TEMP_CLIP_START = utils.join_path(temp_dir, "mpv_temp_clip_start.mp4") local TEMP_CLIP_BULK = utils.join_path(temp_dir, "mpv_temp_clip_bulk.mp4") local TEMP_CONCAT_LIST = utils.join_path(temp_dir, "mpv_temp_concat_list.txt") -- Progress log needs sanitized path for FFmpeg on Windows local FFMPEG_PROGRESS_LOG = utils.join_path(temp_dir, "ffmpeg_progress.log") if is_windows then FFMPEG_PROGRESS_LOG = FFMPEG_PROGRESS_LOG:gsub("\\", "/") end -- Quality Settings & Presets local QUALITY_MODES = { untouched = {name = "Original/Untouched (Fast, Inaccurate Start)", crf = nil}, hybrid_lossless = {name = "Hybrid Lossless (Accurate Start, Fastest)", crf = 18}, high = {name = "High Quality", crf = 18}, medium = {name = "Medium Quality", crf = 23}, low = {name = "Low Quality", crf = 28}, filesize_cap = {name = "File Size Cap: 9.9 MB (GPU Encoded)", crf = nil}, filesize_cap_50 = {name = "File Size Cap: 48.9 MB (GPU Encoded)", crf = nil}, filesize_cap_100 = {name = "File Size Cap: 98.9 MB (GPU Encoded)", crf = nil} } -- Default to 9.9 MB cap mode local current_quality_mode = "filesize_cap" local VIDEO_QUALITY_CRF = QUALITY_MODES[current_quality_mode].crf local filesize_cap_mb = 9.9 local OUTPUT_FORMAT_OPTIONS = { {format = "mp4", video_codec = "libx264", audio_codec = "aac"}, {format = "mkv", video_codec = "libx264", audio_codec = "aac"}, {format = "webm", video_codec = "libvpx-vp9", audio_codec = "libopus"}, {format = "gif", video_codec = "gif", audio_codec = nil} } local current_format_index = 1 local OUTPUT_FORMAT = OUTPUT_FORMAT_OPTIONS[current_format_index].format local VIDEO_CODEC = OUTPUT_FORMAT_OPTIONS[current_format_index].video_codec local AUDIO_CODEC = OUTPUT_FORMAT_OPTIONS[current_format_index].audio_codec -- --- Interactive Crop State & Overlay --- local active_crop = nil -- { x = 0, y = 0, w = 0, h = 0 } local crop_mode_active = false local crop_step = 0 -- 0: waiting for first corner, 1: first corner set & tracking to second corner local crop_p1_x = 0 local crop_p1_y = 0 local crop_curr_x = 0 local crop_curr_y = 0 local crop_overlay = mp.create_osd_overlay("ass-events") local crop_timer = nil local saved_osc_visibility = nil -- --- Helper Functions --- function show_osd_message(message, duration, type) local prefix = " " if type == "error" then prefix = "" elseif type == "success" then prefix = "" elseif type == "info" then prefix = " " end mp.osd_message(prefix .. message, duration or 4) msg.info(message) end function cleanup_temp_files() local files = {TEMP_VIDEO, TEMP_CLIP_START, TEMP_CLIP_BULK, TEMP_CONCAT_LIST, FFMPEG_PROGRESS_LOG} for _, f in ipairs(files) do if utils.file_info(f) then pcall(function() os.remove(f) end) end end end function get_clean_filename(path) if not path then return "output" end local is_stream = path:match("^https?://") ~= nil local _, filename = utils.split_path(path) if is_stream then filename = "stream" else filename = filename:gsub("%.[^.]+$", "") end filename = filename:gsub("[<>:\"/\\|?*]", "_") return filename end function check_ffmpeg_exists() local res = mp.command_native({ name = "subprocess", args = {is_windows and "where" or "which", "ffmpeg"}, capture_stdout = true, capture_stderr = true }) return res and res.status == 0 end function get_active_track_info(track_type) local tracks = mp.get_property_native("track-list") or {} local active_id = mp.get_property((track_type == "sub") and "sid" or "aid") if not active_id or active_id == "no" then return nil, false end for _, t in ipairs(tracks) do if t.type == track_type and tostring(t.id) == active_id then if track_type == "sub" and t.external then return t["external-filename"], true else return tostring(t.id), false end end end return nil, false end -- ============================================================================ -- OSC / BOTTOM TASKBAR SUPPRESSION -- ============================================================================ local function hide_player_ui() saved_osc_visibility = mp.get_property_native("user-data/osc/visibility") -- Hide default mpv OSC (prevents popup, visual block, and mouse event capture) mp.commandv("script-message", "osc-visibility", "never", "no-osd") mp.commandv("script-message", "osc-hide") -- Support for users running uosc pcall(function() mp.commandv("script-message-to", "uosc", "disable-elements", "mpv_trimmer", "timeline,controls,top_bar") end) end local function restore_player_ui() if saved_osc_visibility then mp.commandv("script-message", "osc-visibility", saved_osc_visibility, "no-osd") saved_osc_visibility = nil else mp.commandv("script-message", "osc-visibility", "auto", "no-osd") end pcall(function() mp.commandv("script-message-to", "uosc", "disable-elements", "mpv_trimmer", "") end) end -- ============================================================================ -- CROP SELECTION SYSTEM (Two-Click Corner Mode with Darkened Outer Area) -- ============================================================================ function get_video_render_bounds() local video_w = mp.get_property_native("video-params/w") or mp.get_property_native("dwidth") local video_h = mp.get_property_native("video-params/h") or mp.get_property_native("dheight") if not video_w or not video_h or video_w <= 0 or video_h <= 0 then video_w = 1920 video_h = 1080 end local osd_dims = mp.get_property_native("osd-dimensions") local win_w = (osd_dims and osd_dims.w and osd_dims.w > 0 and osd_dims.w) or mp.get_property_native("osd-width") or 1280 local win_h = (osd_dims and osd_dims.h and osd_dims.h > 0 and osd_dims.h) or mp.get_property_native("osd-height") or 720 local vx0, vy0, vx1, vy1 -- In MPV, osd-dimensions provides ml, mr, mt, mb (margins in OSD pixels) if osd_dims and osd_dims.ml and osd_dims.mr and osd_dims.mt and osd_dims.mb then vx0 = osd_dims.ml vy0 = osd_dims.mt vx1 = win_w - osd_dims.mr vy1 = win_h - osd_dims.mb else local aspect = mp.get_property_native("video-params/aspect") or (video_w / video_h) if not aspect or aspect <= 0 then aspect = video_w / video_h end local win_aspect = win_w / win_h if win_aspect > aspect then local render_w = win_h * aspect vx0 = (win_w - render_w) / 2 vy0 = 0 vx1 = vx0 + render_w vy1 = win_h else local render_h = win_w / aspect vx0 = 0 vy0 = (win_h - render_h) / 2 vx1 = win_w vy1 = vy0 + render_h end end vx0 = math.floor(vx0 or 0) vy0 = math.floor(vy0 or 0) vx1 = math.floor(vx1 or win_w) vy1 = math.floor(vy1 or win_h) if vx1 <= vx0 then vx0 = 0; vx1 = win_w end if vy1 <= vy0 then vy0 = 0; vy1 = win_h end return { win_w = math.floor(win_w), win_h = math.floor(win_h), vx0 = vx0, vy0 = vy0, vx1 = vx1, vy1 = vy1, vw = math.floor(video_w), vh = math.floor(video_h) } end function window_to_video_coords(wx, wy, bounds) if not bounds then bounds = get_video_render_bounds() end if not bounds then return 0, 0 end local rw = bounds.vx1 - bounds.vx0 local rh = bounds.vy1 - bounds.vy0 if rw <= 0 then rw = bounds.win_w end if rh <= 0 then rh = bounds.win_h end local clamped_x = math.max(bounds.vx0, math.min(wx, bounds.vx1)) local clamped_y = math.max(bounds.vy0, math.min(wy, bounds.vy1)) local vx = math.floor(((clamped_x - bounds.vx0) / rw) * bounds.vw) local vy = math.floor(((clamped_y - bounds.vy0) / rh) * bounds.vh) vx = math.max(0, math.min(vx, bounds.vw)) vy = math.max(0, math.min(vy, bounds.vh)) return vx, vy end function video_to_window_coords(vx, vy, bounds) if not bounds then bounds = get_video_render_bounds() end if not bounds then return 0, 0 end local rw = bounds.vx1 - bounds.vx0 local rh = bounds.vy1 - bounds.vy0 if rw <= 0 then rw = bounds.win_w end if rh <= 0 then rh = bounds.win_h end local vw = bounds.vw > 0 and bounds.vw or 1920 local vh = bounds.vh > 0 and bounds.vh or 1080 local wx = bounds.vx0 + (vx / vw) * rw local wy = bounds.vy0 + (vy / vh) * rh return math.floor(wx), math.floor(wy) end function render_crop_overlay() local bounds = get_video_render_bounds() if not bounds then crop_overlay:remove() return end crop_overlay.res_x = bounds.win_w crop_overlay.res_y = bounds.win_h local W = bounds.win_w local H = bounds.win_h -- Case 1: In crop mode, step 0 (Waiting for first corner click) if crop_mode_active and crop_step == 0 then local mx, my = crop_curr_x, crop_curr_y local ass = "" -- Subtle crosshairs at cursor position ass = ass .. string.format("{\\an7}{\\pos(0,0)}{\\bord1}{\\shad0}{\\3c&H00FFFF&}{\\1a&HFF&}{\\p1}m 0 %d l %d %d m %d 0 l %d %d{\\p0}", my, W, my, mx, mx, H) -- Top instructions banner ass = ass .. string.format("{\\an8}{\\pos(%d, 35)}{\\fs22}{\\b1}{\\bord2.5}{\\3c&H000000&}{\\c&H00FFFF&} CROP MODE: CLICK 1ST CORNER\\N{\\fs16}{\\c&HFFFFFF&}Left-click top-left or any corner | Right-click/Esc to cancel", math.floor(W / 2)) crop_overlay.data = ass crop_overlay:update() return end -- Determine window bounding coordinates local bx1, by1, bx2, by2 local label_w, label_h, label_x, label_y if crop_mode_active and crop_step == 1 then bx1 = math.min(crop_p1_x, crop_curr_x) by1 = math.min(crop_p1_y, crop_curr_y) bx2 = math.max(crop_p1_x, crop_curr_x) by2 = math.max(crop_p1_y, crop_curr_y) -- Clamp to window bx1 = math.max(0, math.min(bx1, W)) by1 = math.max(0, math.min(by1, H)) bx2 = math.max(0, math.min(bx2, W)) by2 = math.max(0, math.min(by2, H)) local vx1, vy1 = window_to_video_coords(bx1, by1, bounds) local vx2, vy2 = window_to_video_coords(bx2, by2, bounds) label_w = math.abs(vx2 - vx1) label_h = math.abs(vy2 - vy1) label_x = math.min(vx1, vx2) label_y = math.min(vy1, vy2) elseif active_crop then bx1, by1 = video_to_window_coords(active_crop.x, active_crop.y, bounds) bx2, by2 = video_to_window_coords(active_crop.x + active_crop.w, active_crop.y + active_crop.h, bounds) label_w = active_crop.w label_h = active_crop.h label_x = active_crop.x label_y = active_crop.y else crop_overlay.data = "" crop_overlay:remove() return end -- Render darkened mask outside selected area and crisp crop rectangle local ass = "" -- 1. Darkened outer background mask (75% dark black veil outside the crop box) ass = ass .. "{\\an7}{\\pos(0,0)}{\\bord0}{\\shad0}{\\1c&H000000&}{\\1a&H40&}{\\p1}" -- Top strip (full width above box) if by1 > 0 then ass = ass .. string.format("m 0 0 l %d 0 l %d %d l 0 %d ", W, W, by1, by1) end -- Bottom strip (full width below box) if by2 < H then ass = ass .. string.format("m 0 %d l %d %d l %d %d l 0 %d ", by2, W, by2, W, H, H) end -- Left strip (between by1 and by2, left of bx1) if bx1 > 0 and by2 > by1 then ass = ass .. string.format("m 0 %d l %d %d l %d %d l 0 %d ", by1, bx1, by1, bx1, by2, by2) end -- Right strip (between by1 and by2, right of bx2) if bx2 < W and by2 > by1 then ass = ass .. string.format("m %d %d l %d %d l %d %d l %d %d ", bx2, by1, W, by1, W, by2, bx2, by2) end ass = ass .. "{\\p0}" -- 2. Glowing Crop Box Border (Cyan with black outline) ass = ass .. string.format("{\\an7}{\\pos(0,0)}{\\bord2.5}{\\3c&H000000&}{\\1c&H00FFFF&}{\\1a&HFF&}{\\p1}m %d %d l %d %d l %d %d l %d %d l %d %d{\\p0}", bx1, by1, bx2, by1, bx2, by2, bx1, by2, bx1, by1) -- 3. Corner Handles (Small distinct squares at the 4 corners) local cs = 5 ass = ass .. string.format("{\\an7}{\\pos(0,0)}{\\bord1}{\\3c&H000000&}{\\1c&HFFFFFF&}{\\1a&H00&}{\\p1}" .. "m %d %d l %d %d l %d %d l %d %d " .. "m %d %d l %d %d l %d %d l %d %d " .. "m %d %d l %d %d l %d %d l %d %d " .. "m %d %d l %d %d l %d %d l %d %d {\\p0}", bx1-cs, by1-cs, bx1+cs, by1-cs, bx1+cs, by1+cs, bx1-cs, by1+cs, bx2-cs, by1-cs, bx2+cs, by1-cs, bx2+cs, by1+cs, bx2-cs, by1+cs, bx2-cs, by2-cs, bx2+cs, by2-cs, bx2+cs, by2+cs, bx2-cs, by2+cs, bx1-cs, by2-cs, bx1+cs, by2-cs, bx1+cs, by2+cs, bx1-cs, by2+cs) -- 4. Floating Dimension & Position Badge (Kept safely within visible viewport) local badge_x = math.floor((bx1 + bx2) / 2) local badge_y = math.max(15, by1 - 32) if by1 < 45 then badge_y = by2 + 8 if badge_y > H - 35 then badge_y = math.max(15, math.floor((by1 + by2) / 2) - 10) end end ass = ass .. string.format("{\\an8}{\\pos(%d,%d)}{\\fs18}{\\b1}{\\bord2.5}{\\3c&H000000&}{\\c&H00FFFF&} %dx%d {\\c&HFFFFFF&}[X:%d, Y:%d]", badge_x, badge_y, label_w, label_h, label_x, label_y) if crop_mode_active and crop_step == 1 then ass = ass .. "\\N{\\fs14}{\\c&H00FF00&}Click 2nd corner to finalize | Right-click: Reset 1st corner" end crop_overlay.data = ass crop_overlay:update() end function on_crop_mouse_click() if not crop_mode_active then return end local mx, my = mp.get_mouse_pos() if not mx or not my then return end if crop_step == 0 then -- Step 1: Record first corner crop_p1_x = mx crop_p1_y = my crop_curr_x = mx crop_curr_y = my crop_step = 1 show_osd_message("Corner 1 set. Move mouse and click opposite corner to finish.", 3, "info") render_crop_overlay() elseif crop_step == 1 then -- Step 2: Record second corner & finalize local bounds = get_video_render_bounds() if not bounds then return end local p2_x = mx local p2_y = my local x1 = math.min(crop_p1_x, p2_x) local y1 = math.min(crop_p1_y, p2_y) local x2 = math.max(crop_p1_x, p2_x) local y2 = math.max(crop_p1_y, p2_y) -- Ignore accidental click on the same spot (< 10 px) if (x2 - x1) < 10 or (y2 - y1) < 10 then show_osd_message("Selection too small. Click opposite corner to finish.", 2, "error") return end local vx1, vy1 = window_to_video_coords(x1, y1, bounds) local vx2, vy2 = window_to_video_coords(x2, y2, bounds) local cw = math.abs(vx2 - vx1) local ch = math.abs(vy2 - vy1) local cx = math.min(vx1, vx2) local cy = math.min(vy1, vy2) -- Ensure even dimensions for video codecs (YUV420p requirement) cw = cw - (cw % 2) ch = ch - (ch % 2) cx = cx - (cx % 2) cy = cy - (cy % 2) -- Enforce valid minimum boundaries if cw < 16 then cw = 16 end if ch < 16 then ch = 16 end if cx + cw > bounds.vw then cx = math.max(0, bounds.vw - cw) cx = cx - (cx % 2) if cx + cw > bounds.vw then cw = bounds.vw - cx; cw = cw - (cw % 2) end end if cy + ch > bounds.vh then cy = math.max(0, bounds.vh - ch) cy = cy - (cy % 2) if cy + ch > bounds.vh then ch = bounds.vh - cy; ch = ch - (ch % 2) end end active_crop = { x = cx, y = cy, w = cw, h = ch } show_osd_message(string.format("Crop Set: %dx%d at (%d, %d)", cw, ch, cx, cy), 3, "success") exit_crop_mode(false) end end function on_crop_mouse_right_click() if not crop_mode_active then clear_crop() return end if crop_step == 1 then crop_step = 0 show_osd_message("First corner reset. Click first corner.", 2, "info") render_crop_overlay() else exit_crop_mode(true) show_osd_message("Crop mode cancelled", 2, "info") end end function update_crop_mouse_pos() if not crop_mode_active then return end local mx, my = mp.get_mouse_pos() if mx and my and (mx ~= crop_curr_x or my ~= crop_curr_y) then crop_curr_x = mx crop_curr_y = my render_crop_overlay() end end function enter_crop_mode() -- Hide bottom player taskbar/OSC so it cannot obstruct or consume clicks hide_player_ui() crop_mode_active = true crop_step = 0 local mx, my = mp.get_mouse_pos() crop_curr_x = mx or 0 crop_curr_y = my or 0 mp.add_forced_key_binding("MBTN_LEFT", "crop_m_left", on_crop_mouse_click) mp.add_forced_key_binding("MBTN_LEFT_DBL", "crop_m_dbl", function() end) mp.add_forced_key_binding("MBTN_RIGHT", "crop_m_right", on_crop_mouse_right_click) mp.add_forced_key_binding("ESC", "crop_esc", function() exit_crop_mode(true) end) if crop_timer then crop_timer:kill() end crop_timer = mp.add_periodic_timer(0.025, update_crop_mouse_pos) show_osd_message(" Crop Mode: Click 1st corner of crop area (Right-click: Cancel)", 4, "info") render_crop_overlay() end function exit_crop_mode(cancel_active) crop_mode_active = false crop_step = 0 -- Restore normal bottom bar / OSC functionality restore_player_ui() mp.remove_key_binding("crop_m_left") mp.remove_key_binding("crop_m_dbl") mp.remove_key_binding("crop_m_right") mp.remove_key_binding("crop_esc") if crop_timer then crop_timer:kill() crop_timer = nil end if cancel_active and not active_crop then crop_overlay:remove() else render_crop_overlay() end end function clear_crop() active_crop = nil crop_step = 0 crop_overlay.data = "" crop_overlay:remove() show_osd_message("Crop cleared (Full frame)", 3, "info") if crop_mode_active then exit_crop_mode(false) end end function toggle_crop_mode() if crop_mode_active then exit_crop_mode(true) show_osd_message("Crop mode closed", 2, "info") else enter_crop_mode() end end mp.observe_property("osd-dimensions", "native", function() if crop_mode_active or active_crop then render_crop_overlay() end end) mp.register_event("end-file", function() if crop_mode_active then exit_crop_mode(true) end end) -- ============================================================================ -- PROGRESS TRACKER (Visual Progress Bar & Accurate 100% Detection) -- ============================================================================ local progress_timer = nil function stop_progress_timer() if progress_timer then progress_timer:kill() progress_timer = nil end end function update_progress(total_duration) local f = io.open(FFMPEG_PROGRESS_LOG, "r") if not f then return end local content = f:read("*all") f:close() if not content or content == "" then return end local is_end = content:find("progress=end") ~= nil local last_time_us = nil for match in content:gmatch("out_time_us=(%d+)") do last_time_us = tonumber(match) end local percent = 0 if is_end then percent = 100 elseif last_time_us and total_duration > 0 then percent = math.floor((last_time_us / 1000000 / total_duration) * 100) if percent > 99 then percent = 99 end if percent < 0 then percent = 0 end end last_percent = percent -- Visual block progress bar [] local bar_len = 12 local filled = math.floor((percent / 100) * bar_len) local empty = bar_len - filled local bar_str = string.rep(", filled) .. string.rep(", empty) local cur_sec = (last_time_us and not is_end) and (last_time_us / 1000000) or (is_end and total_duration or 0) if cur_sec > total_duration then cur_sec = total_duration end local time_str = string.format("%02d:%04.1f / %02d:%04.1f", math.floor(cur_sec / 60), cur_sec % 60, math.floor(total_duration / 60), total_duration % 60) if is_end then mp.osd_message(string.format(" Encoding: 100%% [%s]\nFinalizing file container...", bar_str), 2) else mp.osd_message(string.format(" Encoding: %d%% [%s] (%s)", percent, bar_str, time_str), 1.5) end end -- ============================================================================ -- AUDIO MUTING & CANCEL ACTIONS -- ============================================================================ function toggle_mute() is_muted = not is_muted if is_muted then show_osd_message(" Audio: MUTED (Trimmed clip will have no sound)", 3, "info") else show_osd_message(" Audio: UNMUTED", 3, "info") end end function cancel_trimming() -- 1. If currently in crop selection mode, cancel crop mode if crop_mode_active then exit_crop_mode(true) show_osd_message("Crop selection cancelled", 3, "info") return end -- 2. If actively encoding in background, abort the process if is_encoding then if active_async_cmd_id then pcall(function() mp.abort_async_command(active_async_cmd_id) end) active_async_cmd_id = nil end is_encoding = false stop_progress_timer() cleanup_temp_files() start_time = nil end_time = nil show_osd_message("Encoding cancelled!", 4, "info") return end -- 3. If start/end trim points are set, reset them if start_time ~= nil then start_time = nil end_time = nil show_osd_message("Trimming cancelled (Start/End points cleared)", 3, "info") return end -- 4. If crop is active, clear it if active_crop ~= nil then clear_crop() return end show_osd_message("Nothing active to cancel", 2, "info") end -- ============================================================================ -- RENDER & CUT FUNCTIONS -- ============================================================================ -- Used ONLY for standard re-encodes (CRF) or GIFs where MPV filters / subtitles are needed function render_video_with_mpv(output_file) local path = mp.get_property("path") if not path then return nil end local cmd = { "mpv", path, "--start=" .. tostring(start_time), "--end=" .. tostring(end_time), "--vo=lavc", "--o=" .. output_file, "--of=" .. OUTPUT_FORMAT, "--ovc=" .. VIDEO_CODEC, "--ovcopts=crf=18,preset=ultrafast", "--no-ocopy-metadata", "--quiet" } local vf_chain = {} -- Subtitles local sub_info, is_external_sub = get_active_track_info("sub") if sub_info then table.insert(vf_chain, "sub") table.insert(cmd, "--sub-ass=yes") if is_external_sub and not sub_info:match("^edl://") then table.insert(cmd, "--sub-file=" .. sub_info) elseif not is_external_sub then table.insert(cmd, "--sid=" .. sub_info) end else table.insert(cmd, "--no-sub") end -- Audio or Mute if is_muted or not AUDIO_CODEC then table.insert(cmd, "--no-audio") else table.insert(cmd, "--oac=" .. AUDIO_CODEC) local aid = get_active_track_info("audio") if aid then table.insert(cmd, "--aid=" .. aid) end end -- Crop Filter if active_crop then table.insert(vf_chain, string.format("crop=%d:%d:%d:%d", active_crop.w, active_crop.h, active_crop.x, active_crop.y)) end local user_vf = mp.get_property("vf") if user_vf and user_vf ~= "" then table.insert(vf_chain, user_vf) end table.insert(vf_chain, "format=yuv420p") if #vf_chain > 0 then table.insert(cmd, "--vf=" .. table.concat(vf_chain, ",")) end local res = mp.command_native({name = "subprocess", args = cmd, capture_stdout = true, capture_stderr = true}) if res and res.status == 0 and utils.file_info(output_file) then return output_file else return nil end end function cut_video() if not start_time or not end_time then show_osd_message("Set start/end times.", 6, "error") return end if start_time >= end_time then show_osd_message("End time must be greater than start time.", 5, "error") start_time = nil end_time = nil return end if not check_ffmpeg_exists() then show_osd_message("FFmpeg not found in PATH.", 8, "error") return end local path = mp.get_property("path") if not path then show_osd_message("No video currently playing.", 4, "error") return end local clean_name = get_clean_filename(path) -- Determine output directory local output_base_dir if current_output_mode == "source_dir" and not path:match("^https?://") then local dir, _ = utils.split_path(path) output_base_dir = dir else output_base_dir = OUTPUT_DIR_DEFAULT end -- Create directory if missing if not utils.file_info(output_base_dir) then os.execute(is_windows and ('mkdir "' .. output_base_dir .. '"') or ("mkdir -p '" .. output_base_dir .. "'")) end cut_counter = cut_counter + 1 local output_file = utils.join_path(output_base_dir, string.format("%s_%02d_%.2f-%.2f.%s", clean_name, cut_counter, start_time, end_time, OUTPUT_FORMAT)) local duration = end_time - start_time -- Clear progress log local f = io.open(FFMPEG_PROGRESS_LOG, "w") if f then f:close() end is_encoding = true last_percent = 0 -- --- MODE 1: FILE SIZE CAP (GPU Accelerated) --- if filesize_cap_mb and filesize_cap_mb > 0 then if OUTPUT_FORMAT == "gif" then show_osd_message("Size cap not supported for GIF", 5, "error") is_encoding = false return end local target_kb = filesize_cap_mb * 8192 local audio_kbps = is_muted and 0 or 128 local vid_kbps = math.floor((target_kb / duration) - audio_kbps) if vid_kbps < 100 then vid_kbps = 100 end local mute_str = is_muted and " [Muted]" or "" local crop_str = active_crop and string.format(" [Cropped %dx%d]", active_crop.w, active_crop.h) or "" show_osd_message(string.format("Encoding %s @ %dkbps%s%s...", HW_VIDEO_CODEC, vid_kbps, mute_str, crop_str), 999, "info") local ffmpeg_args = { "ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-progress", FFMPEG_PROGRESS_LOG, "-ss", tostring(start_time), "-to", tostring(end_time), "-i", path } if active_crop then table.insert(ffmpeg_args, "-vf") table.insert(ffmpeg_args, string.format("crop=%d:%d:%d:%d", active_crop.w, active_crop.h, active_crop.x, active_crop.y)) end table.insert(ffmpeg_args, "-c:v") table.insert(ffmpeg_args, HW_VIDEO_CODEC) table.insert(ffmpeg_args, "-b:v") table.insert(ffmpeg_args, vid_kbps .. "k") table.insert(ffmpeg_args, "-maxrate") table.insert(ffmpeg_args, vid_kbps .. "k") table.insert(ffmpeg_args, "-bufsize") table.insert(ffmpeg_args, "5M") if is_muted then table.insert(ffmpeg_args, "-an") else table.insert(ffmpeg_args, "-c:a") table.insert(ffmpeg_args, "aac") table.insert(ffmpeg_args, "-b:a") table.insert(ffmpeg_args, "128k") end table.insert(ffmpeg_args, output_file) -- Start Async FFmpeg Process progress_timer = mp.add_periodic_timer(0.4, function() update_progress(duration) end) active_async_cmd_id = mp.command_native_async({ name = "subprocess", args = ffmpeg_args, capture_stdout = true, capture_stderr = true }, function(success, result, error_str) stop_progress_timer() is_encoding = false active_async_cmd_id = nil local info = utils.file_info(output_file) if success and result and result.status == 0 and info and info.size > 0 then local sz_mb = info.size / (1024 * 1024) show_osd_message(string.format("Saved: %s (%.2f MB)", utils.basename(output_file), sz_mb), 6, "success") else local err = (result and result.stderr) or error_str or "Encode failed" local clean_err = err:match("([^\r\n]+)[\r\n]*$") or err if #clean_err > 80 then clean_err = clean_err:sub(1, 80) .. "..." end show_osd_message("Encode failed: " .. clean_err, 8, "error") end cleanup_temp_files() start_time = nil end_time = nil end) return end -- --- MODE 2: HYBRID LOSSLESS (When not cropped) --- if current_quality_mode == "hybrid_lossless" and OUTPUT_FORMAT ~= "gif" and not active_crop then show_osd_message("Processing Hybrid Cut...", 2, "info") local re_encode_end = start_time + math.min(0.5, duration) local audio_args_start = is_muted and {"-an"} or {"-c:a", AUDIO_CODEC or "copy"} local cmd_start = {"ffmpeg", "-y", "-ss", tostring(start_time), "-to", tostring(re_encode_end), "-i", path, "-c:v", VIDEO_CODEC, "-crf", "18"} for _, a in ipairs(audio_args_start) do table.insert(cmd_start, a) end table.insert(cmd_start, TEMP_CLIP_START) mp.command_native({name = "subprocess", args = cmd_start}) local audio_args_bulk = is_muted and {"-an"} or {"-c:a", "copy"} local cmd_bulk = {"ffmpeg", "-y", "-ss", tostring(re_encode_end), "-i", path, "-to", tostring(end_time), "-c:v", "copy"} for _, a in ipairs(audio_args_bulk) do table.insert(cmd_bulk, a) end table.insert(cmd_bulk, TEMP_CLIP_BULK) mp.command_native({name = "subprocess", args = cmd_bulk}) local f_list = io.open(TEMP_CONCAT_LIST, "w") if f_list then f_list:write("file '" .. TEMP_CLIP_START .. "'\nfile '" .. TEMP_CLIP_BULK .. "'\n") f_list:close() end local res = mp.command_native({name = "subprocess", args = {"ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", TEMP_CONCAT_LIST, "-c", "copy", output_file}}) is_encoding = false local info = utils.file_info(output_file) if res and res.status == 0 and info and info.size > 0 then local sz_mb = info.size / (1024 * 1024) show_osd_message(string.format("Saved: %s (%.2f MB)", utils.basename(output_file), sz_mb), 6, "success") else show_osd_message("Hybrid Cut failed.", 6, "error") end cleanup_temp_files() start_time = nil end_time = nil return -- --- MODE 3: UNTOUCHED / STREAM COPY (When not cropped) --- elseif current_quality_mode == "untouched" and OUTPUT_FORMAT ~= "gif" and not active_crop then local cmd = {"ffmpeg", "-y", "-ss", tostring(start_time), "-to", tostring(end_time), "-i", path, "-c:v", "copy"} if is_muted then table.insert(cmd, "-an") else table.insert(cmd, "-c:a") table.insert(cmd, "copy") end table.insert(cmd, output_file) local res = mp.command_native({name = "subprocess", args = cmd}) is_encoding = false local info = utils.file_info(output_file) if res and res.status == 0 and info and info.size > 0 then local sz_mb = info.size / (1024 * 1024) show_osd_message(string.format("Saved: %s (%.2f MB)", utils.basename(output_file), sz_mb), 6, "success") else show_osd_message("Untouched cut failed.", 6, "error") end cleanup_temp_files() start_time = nil end_time = nil return end -- --- MODE 4: STANDARD RE-ENCODE (CRF, GIF, or Cropped Cuts) --- show_osd_message("Step 1/2: Rendering intermediate...", 999, "info") local temp_file = render_video_with_mpv(TEMP_VIDEO) if not temp_file then show_osd_message("Failed to render intermediate video.", 5, "error") is_encoding = false start_time = nil end_time = nil return end local ffmpeg_args = {} if OUTPUT_FORMAT == "gif" then ffmpeg_args = { "ffmpeg", "-y", "-progress", FFMPEG_PROGRESS_LOG, "-i", temp_file, "-vf", "fps=10,scale=480:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse", "-loop", "0", output_file } else ffmpeg_args = { "ffmpeg", "-y", "-progress", FFMPEG_PROGRESS_LOG, "-i", temp_file, "-c:v", "copy" } if is_muted then table.insert(ffmpeg_args, "-an") else table.insert(ffmpeg_args, "-c:a") table.insert(ffmpeg_args, "copy") end table.insert(ffmpeg_args, output_file) end show_osd_message("Step 2/2: Finalizing...", 999, "info") progress_timer = mp.add_periodic_timer(0.4, function() update_progress(duration) end) active_async_cmd_id = mp.command_native_async({ name = "subprocess", args = ffmpeg_args, capture_stdout = true, capture_stderr = true }, function(success, result, error_str) stop_progress_timer() is_encoding = false active_async_cmd_id = nil local info = utils.file_info(output_file) if success and result and result.status == 0 and info and info.size > 0 then local sz_mb = info.size / (1024 * 1024) show_osd_message(string.format("Saved: %s (%.2f MB)", utils.basename(output_file), sz_mb), 6, "success") else local err = (result and result.stderr) or error_str or "Finalize failed" local clean_err = err:match("([^\r\n]+)[\r\n]*$") or err if #clean_err > 80 then clean_err = clean_err:sub(1, 80) .. "..." end show_osd_message("Encode failed: " .. clean_err, 8, "error") end cleanup_temp_files() start_time = nil end_time = nil end) end -- ============================================================================ -- INPUT BINDINGS & CONTROLS -- ============================================================================ function set_start_time() if start_time then set_end_time() else start_time = mp.get_property_number("time-pos") if start_time then show_osd_message(string.format("Start: %.2fs (Press 'c' again for End)", start_time), 3, "info") end end end function set_end_time() end_time = mp.get_property_number("time-pos") if end_time then show_osd_message(string.format("End: %.2fs - Processing Cut...", end_time), 2, "info") cut_video() end end -- Trim Action: 'c' to start, 'c' again to finish & cut mp.add_key_binding("c", "cut_time", set_start_time) -- Cancel Trimming / Abort Encode: Alt+c and Esc mp.add_key_binding("Alt+c", "cancel_trim", cancel_trimming) mp.add_key_binding("Esc", "cancel_trim_esc", function() if crop_mode_active or is_encoding or start_time ~= nil or active_crop ~= nil then cancel_trimming() end end) -- Mute Audio Toggle: Ctrl+m mp.add_key_binding("Ctrl+m", "toggle_mute", toggle_mute) -- Interactive Corner-to-Corner Crop Toggle: Ctrl+x and x mp.add_key_binding("Ctrl+x", "toggle_crop", toggle_crop_mode) mp.add_key_binding("x", "toggle_crop_short", toggle_crop_mode) -- Clear Crop Directly: Ctrl+Shift+X and Alt+x mp.add_key_binding("Ctrl+X", "clear_crop_key", clear_crop) mp.add_key_binding("Alt+x", "clear_crop_alt", clear_crop) -- File Size Cap Presets mp.add_key_binding("Ctrl+5", "set_cap_20", function() filesize_cap_mb = 18.9 current_quality_mode = "filesize_cap" show_osd_message("Mode: 18.9 MB Cap (" .. HW_VIDEO_CODEC .. ")", 3, "info") end) mp.add_key_binding("Ctrl+6", "set_cap_50", function() filesize_cap_mb = 48.9 current_quality_mode = "filesize_cap_50" show_osd_message("Mode: 48.9 MB Cap (" .. HW_VIDEO_CODEC .. ")", 3, "info") end) mp.add_key_binding("Ctrl+7", "set_cap_100", function() filesize_cap_mb = 98.9 current_quality_mode = "filesize_cap_100" show_osd_message("Mode: 98.9 MB Cap (" .. HW_VIDEO_CODEC .. ")", 3, "info") end) -- Output Format Cycle: mp4 -> mkv -> webm -> gif mp.add_key_binding("Ctrl+f", "fmt", function() current_format_index = current_format_index % #OUTPUT_FORMAT_OPTIONS + 1 local o = OUTPUT_FORMAT_OPTIONS[current_format_index] OUTPUT_FORMAT = o.format VIDEO_CODEC = o.video_codec AUDIO_CODEC = o.audio_codec show_osd_message("Format: " .. OUTPUT_FORMAT:upper(), 2, "info") end) -- Output Directory Toggle: Source Dir vs Desktop mp.add_key_binding("Ctrl+d", "toggle_dir", function() if current_output_mode == "source_dir" then current_output_mode = "default_dir" show_osd_message("Output Directory: Desktop/mpvstreamcut", 3, "info") else current_output_mode = "source_dir" show_osd_message("Output Directory: Video Source Folder", 3, "info") end end) -- Quality Presets (Non-Capped) mp.add_key_binding("Ctrl+0", "q0", function() current_quality_mode = "hybrid_lossless" filesize_cap_mb = nil show_osd_message("Mode: Hybrid Lossless", 2, "info") end) mp.add_key_binding("Ctrl+1", "q1", function() current_quality_mode = "untouched" filesize_cap_mb = nil show_osd_message("Mode: Untouched / Stream Copy", 2, "info") end) mp.add_key_binding("Ctrl+2", "q2", function() current_quality_mode = "high" filesize_cap_mb = nil show_osd_message("Mode: High Quality (CRF 18)", 2, "info") end) mp.add_key_binding("Ctrl+3", "q3", function() current_quality_mode = "medium" filesize_cap_mb = nil show_osd_message("Mode: Medium Quality (CRF 23)", 2, "info") end) mp.add_key_binding("Ctrl+4", "q4", function() current_quality_mode = "low" filesize_cap_mb = nil show_osd_message("Mode: Low Quality (CRF 28)", 2, "info") end)