-- Instant Replay VLC -- Save -> optional copy -> one-entry VLC playlist; session-only replay history. -- Existing settings and five hotkey IDs are deliberately preserved. local obs = obslua local VERSION = "1.5.0-dev6" local cfg = {source = "", folder = "", copied = true, timeout = 10} local history, selected = {}, 0 local job, timer_running, loaded = nil, false, false local status = "Ready. Select a dedicated VLC source and check setup." local sequence = 0 local awaiting_completion = false local tick, on_event local hotkeys = {} local CHUNK, TICK_MS = 256 * 1024, 20 -- Temporary layout guide only. All ordinary replay controls remain unchanged. local guide = nil -- OBS Sources-panel eye toggle is the Apply control for the guide. -- Process it on the next timer tick, outside OBS's visibility signal callback. local finish_replay_area local guide_apply_tick, guide_apply_timer_running = nil, false local guide_visibility_changed local pending_areas = {} local area_tick, area_timer_running = nil, false -- The auto-setup timer is deliberately separate from deferred VLC transforms. -- Completed/canceled guide setups are remembered per scene + VLC source. local auto_tick, auto_timer_running = nil, false local configured_areas, configured_signatures, attempted_areas = {}, {}, {} local AUTO_POLL_MS = 1250 local function report(message, level) status = message obs.script_log(level or obs.LOG_INFO, "[Instant Replay VLC] " .. message) end local function now() return tonumber(obs.os_gettime_ns()) / 1000000000 end local function basename(path) return path:match("([^\\/]+)$") or path end local function join(folder, name) return folder .. (folder:match("[\\/]$") and "" or package.config:sub(1, 1)) .. name end local function source_for(name) if name == "" then return nil, "Select a VLC source in Tools > Scripts." end local s = obs.obs_get_source_by_name(name) if not s then return nil, "VLC source not found: " .. name end if obs.obs_source_get_id(s) ~= "vlc_source" then obs.obs_source_release(s) return nil, "Selected source is not a VLC Video Source: " .. name end return s end local function readable(path) local f, err = io.open(path, "rb") if not f then return false, err end local size, size_err = f:seek("end") f:close() return size ~= nil and size > 0, size_err or "File is empty or unavailable." end local function set_playlist(name, path) local s, err = source_for(name) if not s then return false, err end local settings, array = obs.obs_data_create(), obs.obs_data_array_create() if path then local item = obs.obs_data_create() obs.obs_data_set_string(item, "value", path) obs.obs_data_array_push_back(array, item) obs.obs_data_release(item) end obs.obs_data_set_array(settings, "playlist", array) obs.obs_source_update(s, settings) obs.obs_data_array_release(array) obs.obs_data_release(settings) obs.obs_source_release(s) return true -- Settings submitted; decoding/playback is owned by VLC. end local function stop_timer() if timer_running then obs.timer_remove(tick); timer_running = false end end local function cleanup_copy(j) if j.input then pcall(function() j.input:close() end); j.input = nil end if j.output then pcall(function() j.output:close() end); j.output = nil end if j.temp then if obs.os_unlink(j.temp) ~= 0 then report("Could not remove partial copy: " .. j.temp, obs.LOG_WARNING) end j.temp = nil end if j.lock then if obs.os_rmdir(j.lock) ~= 0 then report("Temporary directory remains: " .. j.lock, obs.LOG_WARNING) end j.lock = nil end end local function cancel(message) stop_timer() if job then cleanup_copy(job); job = nil end if message then report(message, obs.LOG_WARNING) end end local function select_entry(index) local entry = history[index] if not entry then return false end local ok = readable(entry.path) if not ok then return false end local updated, err = set_playlist(cfg.source, entry.path) if not updated then report(err, obs.LOG_WARNING); return false, "source" end selected = index report(string.format("Selected %d/%d: %s", selected, #history, basename(entry.path))) return true end local function finish(path, warning) local j = job if not j then return end cleanup_copy(j) stop_timer() job = nil local ok, err = readable(path) if not ok then report("Replay unavailable: " .. path .. " (" .. tostring(err) .. ")", obs.LOG_ERROR); return end if #history == 0 or history[#history].path ~= path then history[#history + 1] = {path = path} end local updated, update_err = set_playlist(j.source, path) if updated then selected = #history report(string.format("%sSelected %d/%d: %s", warning and (warning .. " ") or "", selected, #history, basename(path)), warning and obs.LOG_WARNING or obs.LOG_INFO) else report("Replay saved in history, but not selected: " .. update_err, obs.LOG_WARNING) end end local function copy_failed(reason) finish(job.path, "Copy failed; using original. " .. tostring(reason)) end -- Reserve a name using an exclusive directory. Other instances of this script -- respect the same reservation. Never use this folder with external writers -- that deliberately replace these names; Lua has no portable no-replace rename. local function reserve_copy(j) local filename = basename(j.path) local base, ext = filename:match("^(.*)(%.[^%.]+)$") base, ext = base or filename, ext or "" local stem = base .. "_" .. os.date("%Y%m%d_%H%M%S") for n = 1, 1000 do local destination = join(j.folder, stem .. (n == 1 and "" or ("_" .. n)) .. ext) if not obs.os_file_exists(destination) then local lock = destination .. ".irvlc-lock" local result = obs.os_mkdir(lock) if result == 0 then if obs.os_file_exists(destination) then obs.os_rmdir(lock) else j.destination, j.lock = destination, lock return true end elseif result == -1 then return false, "Copy folder is unavailable or not writable." end end end return false, "Could not reserve a unique copy filename." end local function start_copy(j) if not obs.os_mkdir or not obs.os_rmdir or not obs.os_unlink or not obs.os_file_exists then copy_failed("Required filesystem bindings unavailable in this OBS build."); return end local ok, err = reserve_copy(j) if not ok then copy_failed(err); return end j.input, err = io.open(j.path, "rb") if not j.input then copy_failed(err); return end j.size, err = j.input:seek("end") if not j.size or j.size <= 0 then copy_failed(err or "Empty replay."); return end if not j.input:seek("set", 0) then copy_failed("Cannot seek original."); return end local temp = join(j.lock, "replay.part") j.output, err = io.open(temp, "wb") if not j.output then copy_failed(err); return end j.temp, j.bytes, j.state = temp, 0, "copying" j.deadline = now() + 300 report("Copying replay: " .. basename(j.path)) end local function get_last_path() local output = obs.obs_frontend_get_replay_buffer_output() if not output then return nil end local cd = obs.calldata_create() local ok = obs.proc_handler_call(obs.obs_output_get_proc_handler(output), "get_last_replay", cd) local path = ok and obs.calldata_string(cd, "path") or nil obs.calldata_destroy(cd) obs.obs_output_release(output) return path end local function process_tick() local j = job if not j then stop_timer(); return end if now() >= j.deadline then if j.state == "copying" then copy_failed("Copy exceeded five minutes.") else cancel("Timed out waiting for OBS. The recording may still finish; no old replay was selected.") end return end if j.state ~= "copying" then return end -- At most 1 MiB per tick; yield sooner if the 4 ms work budget is consumed. local started = now() for _ = 1, 4 do local chunk, err = j.input:read(CHUNK) if not chunk then if err or j.bytes ~= j.size then copy_failed(err or "Source size changed or read was incomplete."); return end local closed, close_err = j.output:close(); j.output = nil if not closed then copy_failed(close_err or "Could not finalize copy."); return end j.input:close(); j.input = nil local check = io.open(j.temp, "rb") local actual = check and check:seek("end") if check then check:close() end if actual ~= j.size then copy_failed("Copied size does not match original."); return end if obs.os_file_exists(j.destination) then copy_failed("Destination appeared during copying; not overwritten."); return end local renamed, rename_err = os.rename(j.temp, j.destination) if not renamed then copy_failed(rename_err or "Cannot publish copy."); return end j.temp = nil finish(j.copied and j.destination or j.path) return end local written, write_err = j.output:write(chunk) if not written then copy_failed(write_err or "Write failed."); return end j.bytes = j.bytes + #chunk if j.bytes > j.size then copy_failed("Original replay changed during copying."); return end if now() - started >= 0.004 then return end end end tick = function() local ok, err = pcall(process_tick) if not ok then cancel("Processing stopped safely: " .. tostring(err)) end end function instant_replay(pressed) if not pressed then return end if job then report("Replay processing is already in progress; additional save ignored.", obs.LOG_WARNING); return end if awaiting_completion then report("Waiting for the canceled/timed-out OBS save to finish. If it is stuck, stop and restart Replay Buffer.", obs.LOG_WARNING); return end if not loaded then report("Script is not ready.", obs.LOG_WARNING); return end if not obs.obs_frontend_replay_buffer_active() then report("Start Replay Buffer in OBS before saving a replay.", obs.LOG_WARNING); return end sequence = sequence + 1 job = {id = sequence, state = "saving", source = cfg.source, folder = cfg.folder, copied = cfg.copied, deadline = now() + cfg.timeout} awaiting_completion = true obs.timer_add(tick, TICK_MS); timer_running = true report("Save requested; waiting for OBS.") obs.obs_frontend_replay_buffer_save() end -- Replay area setup. The Color Source has real dimensions even before VLC -- decodes a video. The user positions this temporary source using OBS itself. local GUIDE_PREFIX = "[Instant Replay VLC] Temporary Area " local GUIDE_WIDTH, GUIDE_HEIGHT = 640, 360 local AREA_POLL_MS = 250 local function area_key(scene_name, source_name, collection_name) -- Length prefixes avoid collisions in names, across scene collections. local collection = collection_name if collection == nil then collection = (obs.obs_frontend_get_current_scene_collection and obs.obs_frontend_get_current_scene_collection()) or "" end return tostring(#collection) .. ":" .. collection .. tostring(#scene_name) .. ":" .. scene_name .. source_name end -- A source name is not an identity: OBS can reuse the same name after deletion. -- Include the source UUID AND the scene-item ID because removing/re-adding an -- existing source also creates a new item with a different transform. local function scene_item_signature(item) if not item then return nil end local src = obs.obs_sceneitem_get_source(item) if not src then return nil end local uuid = obs.obs_source_get_uuid and obs.obs_source_get_uuid(src) or nil local id = obs.obs_sceneitem_get_id and obs.obs_sceneitem_get_id(item) or nil -- Not every C API symbol is exposed in every obslua build. Either -- identifier distinguishes a replacement; together they are strongest. if uuid and uuid ~= "" and id ~= nil then return "source:" .. uuid .. "#item:" .. tostring(id) end if uuid and uuid ~= "" then return "source:" .. uuid end if id ~= nil then return "item:" .. tostring(id) end return nil end local function pending_for(scene_name, source_name) for _, area in ipairs(pending_areas) do if area.scene == scene_name and area.source == source_name then return true end end return false end local function discard_old_area(scene_name, source_name) local key = area_key(scene_name, source_name) configured_areas[key], configured_signatures[key], attempted_areas[key] = nil, nil, nil for i = #pending_areas, 1, -1 do if pending_areas[i].scene == scene_name and pending_areas[i].source == source_name then table.remove(pending_areas, i) end end if #pending_areas == 0 then -- The timer will stop at its next tick. Avoid calling the timer stop -- helper here, since that helper is declared later in the file. end end local function output_active() return (obs.obs_frontend_streaming_active and obs.obs_frontend_streaming_active()) or (obs.obs_frontend_recording_active and obs.obs_frontend_recording_active()) or (obs.obs_frontend_virtualcam_active and obs.obs_frontend_virtualcam_active()) or (obs.obs_frontend_replay_buffer_active and obs.obs_frontend_replay_buffer_active()) end -- VLC Video Source files, folders and URLs are all playlist entries. -- Do not overwrite or display guides for sources with existing content. local function vlc_playlist_empty(vlc) local settings = obs.obs_source_get_settings(vlc) if not settings then return false end local playlist = obs.obs_data_get_array(settings, "playlist") local empty = not playlist or obs.obs_data_array_count(playlist) == 0 if playlist then obs.obs_data_array_release(playlist) end obs.obs_data_release(settings) return empty end local function current_scene_context() local scene_source = obs.obs_frontend_get_current_scene() if not scene_source then return nil, nil, "No active OBS scene." end local scene = obs.obs_scene_from_source(scene_source) if not scene then obs.obs_source_release(scene_source) return nil, nil, "The current source is not an OBS scene." end return scene_source, scene end local function remove_guide() if not guide then return end local old = guide guide = nil if guide_apply_timer_running then obs.timer_remove(guide_apply_tick) guide_apply_timer_running = false end -- Do not let our own source removal re-enter the visibility handler. if old.signal_connected then local scene_source = obs.obs_get_source_by_name(old.scene) if scene_source then obs.signal_handler_disconnect(obs.obs_source_get_signal_handler(scene_source), "item_visible", guide_visibility_changed) obs.obs_source_release(scene_source) end end -- We retain our own reference to the source, so this is safe even if the -- user deleted its scene item while adjusting the guide. if old.source then obs.obs_source_remove(old.source) obs.obs_source_release(old.source) end end -- Register visibility events on the scene's signal handler. The signal is -- emitted when a user clicks the eye beside a scene item in OBS Sources. -- We only act if that exact temporary guide is hidden. local function watch_guide_visibility() if not guide or guide.signal_connected then return end if not obs.signal_handler_connect or not obs.obs_source_get_signal_handler then report("This OBS build cannot watch guide visibility. Use Apply Replay Area in Tools > Scripts.", obs.LOG_WARNING) return end local scene_source = obs.obs_get_source_by_name(guide.scene) if not scene_source then return end obs.signal_handler_connect(obs.obs_source_get_signal_handler(scene_source), "item_visible", guide_visibility_changed) obs.obs_source_release(scene_source) guide.signal_connected = true end guide_apply_tick = function() obs.timer_remove(guide_apply_tick) guide_apply_timer_running = false if not guide then return end local ok, err = pcall(finish_replay_area) if not ok then report("Cannot apply hidden replay guide: " .. tostring(err), obs.LOG_ERROR) end end guide_visibility_changed = function(cd) if not guide or obs.calldata_bool(cd, "visible") then return end local item = obs.calldata_sceneitem(cd, "item") if not item then return end local src = obs.obs_sceneitem_get_source(item) if not src or obs.obs_source_get_name(src) ~= obs.obs_source_get_name(guide.source) then return end if not guide_apply_timer_running then guide_apply_timer_running = true obs.timer_add(guide_apply_tick, 100) end end local function stop_area_timer() if area_timer_running then obs.timer_remove(area_tick); area_timer_running = false end end local function start_area_timer() if not area_timer_running and #pending_areas > 0 then obs.timer_add(area_tick, AREA_POLL_MS) area_timer_running = true end end local function queue_area(area) for i = #pending_areas, 1, -1 do if pending_areas[i].scene == area.scene and pending_areas[i].source == area.source then table.remove(pending_areas, i) end end pending_areas[#pending_areas + 1] = area end local function apply_area(area) local scene_source = obs.obs_get_source_by_name(area.scene) if not scene_source then return false end local scene = obs.obs_scene_from_source(scene_source) local item = scene and obs.obs_scene_find_source(scene, area.source) or nil if not item then obs.obs_source_release(scene_source); return false end local vlc = obs.obs_sceneitem_get_source(item) -- Never transfer a stale queued layout to a replacement source/item. if area.identity and area.identity ~= "" then local current = scene_item_signature(item) if current and current ~= area.identity then obs.obs_source_release(scene_source) return "stale" end end if obs.obs_source_get_id(vlc) ~= "vlc_source" or obs.obs_source_get_width(vlc) <= 0 or obs.obs_source_get_height(vlc) <= 0 then obs.obs_source_release(scene_source) return false end -- Use the scene-item accessors exposed by OBS's Lua bindings. Older -- get_info() / obs_transform_info() assumptions are not portable here. -- This operation runs only after VLC reports non-zero video dimensions. local pos, scale, bounds = obs.vec2(), obs.vec2(), obs.vec2() pos.x, pos.y = area.x, area.y scale.x, scale.y = 1, 1 bounds.x, bounds.y = area.width, area.height obs.obs_sceneitem_set_scale(item, scale) obs.obs_sceneitem_set_alignment(item, area.alignment) obs.obs_sceneitem_set_rot(item, area.rot) -- OBS enumerates SCALE_INNER as 2; some Lua builds omit the symbol. obs.obs_sceneitem_set_bounds_type(item, obs.OBS_BOUNDS_SCALE_INNER or 2) -- OBS_ALIGN_CENTER is zero. The symbolic alignment constants are not -- guaranteed to be available in obslua, so avoid referencing them. obs.obs_sceneitem_set_bounds_alignment(item, 0) obs.obs_sceneitem_set_bounds(item, bounds) obs.obs_sceneitem_set_pos(item, pos) obs.obs_source_release(scene_source) return true end area_tick = function() for i = #pending_areas, 1, -1 do local area = pending_areas[i] local ok, applied = pcall(apply_area, area) if ok and applied == "stale" then table.remove(pending_areas, i) report("Skipped old replay dimensions because the VLC scene item was replaced.", obs.LOG_WARNING) elseif ok and applied then table.remove(pending_areas, i) report(string.format("Replay area applied to '%s': %.0f x %.0f. ", area.scene, area.width, area.height) .. "The VLC source uses OBS's fit-within-bounds transform.") elseif not ok then -- Leave area queued for a future retry, and avoid flooding the log. stop_area_timer() report("Cannot apply replay area: " .. tostring(applied), obs.LOG_ERROR) return end end if #pending_areas == 0 then stop_area_timer() end end -- OBS can retain a temporary Color Source after a script reload or another -- loss of Lua-only state. Recover a guide from the active scene rather than -- making users start over. If several exist, only trust the selected one. local function recover_replay_area_guide() local scene_source, scene, err = current_scene_context() if not scene_source then return false, err, false end local items = obs.obs_scene_enum_items(scene) local matches = {} if items then for _, item in ipairs(items) do local s = obs.obs_sceneitem_get_source(item) if s then local name = obs.obs_source_get_name(s) local kind = (obs.obs_source_get_unversioned_id and obs.obs_source_get_unversioned_id(s)) or obs.obs_source_get_id(s) if name and name:sub(1, #GUIDE_PREFIX) == GUIDE_PREFIX and type(kind) == "string" and kind:match("^color_source") then matches[#matches + 1] = {name = name, selected = obs.obs_sceneitem_selected and obs.obs_sceneitem_selected(item) or false} end end end obs.sceneitem_list_release(items) end if #matches == 0 then obs.obs_source_release(scene_source) return false, "Click Set Replay Area first. No temporary guide exists in this scene.", false end local candidate = nil if #matches == 1 then candidate = matches[1] else local count = 0 for _, m in ipairs(matches) do if m.selected then candidate = m; count = count + 1 end end if count ~= 1 then obs.obs_source_release(scene_source) return false, "Multiple replay-area guides found. Select exactly one in OBS Sources and retry, or delete the extras.", true end end -- Refuse to transfer a rectangle to a missing/different target source. local target = obs.obs_scene_find_source(scene, cfg.source) local vlc = target and obs.obs_sceneitem_get_source(target) or nil if not vlc or obs.obs_source_get_id(vlc) ~= "vlc_source" then obs.obs_source_release(scene_source) return false, "The selected VLC Video Source is not in this scene. Add it and retry.", true end local recovered = obs.obs_get_source_by_name(candidate.name) if not recovered then obs.obs_source_release(scene_source) return false, "The temporary guide is no longer available. Click Set Replay Area again.", false end guide = {source = recovered, scene = obs.obs_source_get_name(scene_source), target = cfg.source, identity = scene_item_signature(target)} obs.obs_source_release(scene_source) watch_guide_visibility() return true, "Recovered existing replay-area guide: " .. candidate.name, true end local function begin_replay_area() -- A normal Color Source is part of the program scene, not just an editor -- overlay. Never allow accidental guide visibility in a live output. if output_active() then report("Stop streaming, recording, virtual camera and Replay Buffer before setting a replay area; the guide is a real scene source.", obs.LOG_WARNING) return end if guide then report("A replay-area guide is already active. Resize it or click Cancel.", obs.LOG_WARNING) return end local recovered, recovery_message, has_guide = recover_replay_area_guide() if recovered then report(recovery_message .. ". Resize it, then click its eye icon to apply."); return end if has_guide then report(recovery_message, obs.LOG_WARNING); return end local vlc, err = source_for(cfg.source) if not vlc then report(err, obs.LOG_WARNING); return end obs.obs_source_release(vlc) local scene_source, scene, scene_err = current_scene_context() if not scene_source then report(scene_err, obs.LOG_WARNING); return end -- Limit this workflow to a direct scene item. Group coordinates are local -- to the group and cannot safely be copied as scene coordinates. if not obs.obs_scene_find_source(scene, cfg.source) then obs.obs_source_release(scene_source) report("Add the dedicated VLC source directly to the current scene first (not inside a group).", obs.LOG_WARNING) return end local name for n = 1, 1000 do local candidate = GUIDE_PREFIX .. tostring(n) local existing = obs.obs_get_source_by_name(candidate) if existing then obs.obs_source_release(existing) else name = candidate; break end end if not name then obs.obs_source_release(scene_source) report("Cannot create a unique replay area guide.", obs.LOG_WARNING) return end local settings = obs.obs_data_create() -- RGBA, encoded as OBS color (AABBGGRR): translucent blue (~35% opacity). obs.obs_data_set_int(settings, "color", 0x59F0A050) obs.obs_data_set_int(settings, "width", GUIDE_WIDTH) obs.obs_data_set_int(settings, "height", GUIDE_HEIGHT) local source = obs.obs_source_create("color_source", name, settings, nil) obs.obs_data_release(settings) if not source then obs.obs_source_release(scene_source) report("OBS could not create the temporary Color Source.", obs.LOG_ERROR) return end local item = obs.obs_scene_add(scene, source) if not item then obs.obs_source_remove(source) obs.obs_source_release(source) obs.obs_source_release(scene_source) report("Could not add the guide to this OBS scene.", obs.LOG_ERROR) return end local pos = obs.vec2() pos.x, pos.y = 80, 80 -- Keep the Color Source's default alignment. It has real dimensions, -- and its numeric alignment will be transferred to the VLC scene item. obs.obs_sceneitem_set_pos(item, pos) -- New scene items are inserted at the top by OBS. No order enum needed. obs.obs_sceneitem_select(item, true) guide = {source = source, scene = obs.obs_source_get_name(scene_source), target = cfg.source, identity = scene_item_signature(obs.obs_scene_find_source(scene, cfg.source))} watch_guide_visibility() attempted_areas[area_key(guide.scene, guide.target)] = true obs.obs_source_release(scene_source) report("Drag/resize the translucent guide, then click its eye icon in OBS Sources to Apply. " .. "The guide is visible in the scene, so set up off-air.") end finish_replay_area = function() if not guide then local recovered, why = recover_replay_area_guide() if not recovered then report(why, obs.LOG_WARNING); return end report("Temporary guide recovered; applying its current dimensions.") end local scene_source = obs.obs_get_source_by_name(guide.scene) local scene = scene_source and obs.obs_scene_from_source(scene_source) or nil local item = scene and obs.obs_scene_find_source(scene, obs.obs_source_get_name(guide.source)) or nil local target = scene and obs.obs_scene_find_source(scene, guide.target) or nil if not item or not target or obs.obs_source_get_name(obs.obs_sceneitem_get_source(item)) ~= obs.obs_source_get_name(guide.source) then if scene_source then obs.obs_source_release(scene_source) end remove_guide() report("Guide or VLC scene item was removed. No replay layout was changed.", obs.LOG_WARNING) return end if guide.identity and scene_item_signature(target) ~= guide.identity then obs.obs_source_release(scene_source) local scene_name, source_name = guide.scene, guide.target remove_guide() discard_old_area(scene_name, source_name) report("The VLC source was replaced during setup. The old guide was discarded.", obs.LOG_WARNING) return end if obs.obs_sceneitem_locked(item) then obs.obs_source_release(scene_source) report("Unlock the temporary guide before applying its layout.", obs.LOG_WARNING) return end -- Read the same item geometry OBS's preview uses, without relying on -- obs_sceneitem_get_info(), which is nil in the reported Lua environment. local pos, scale, bounds = obs.vec2(), obs.vec2(), obs.vec2() obs.obs_sceneitem_get_pos(item, pos) obs.obs_sceneitem_get_scale(item, scale) local alignment = obs.obs_sceneitem_get_alignment(item) local rotation = obs.obs_sceneitem_get_rot(item) local w, h if obs.obs_sceneitem_get_bounds_type(item) ~= (obs.OBS_BOUNDS_NONE or 0) then obs.obs_sceneitem_get_bounds(item, bounds) w, h = bounds.x, bounds.y else -- Unlike an empty VLC source, the temporary Color Source has dimensions. w = obs.obs_source_get_width(guide.source) * scale.x h = obs.obs_source_get_height(guide.source) * scale.y end local crop = obs.obs_sceneitem_crop() obs.obs_sceneitem_get_crop(item, crop) if crop.left ~= 0 or crop.right ~= 0 or crop.top ~= 0 or crop.bottom ~= 0 or w <= 0 or h <= 0 or w ~= w or h ~= h or w > 16384 or h > 16384 or rotation ~= 0 or scale.x <= 0 or scale.y <= 0 then obs.obs_source_release(scene_source) report("Guide must be an unrotated, uncropped rectangle with positive dimensions. " .. "Drag its edges to resize, then try Apply again.", obs.LOG_WARNING) return end local area = {scene = guide.scene, source = guide.target, x = pos.x, y = pos.y, width = w, height = h, rot = 0, alignment = alignment, identity = scene_item_signature(target)} obs.obs_source_release(scene_source) queue_area(area) local key = area_key(area.scene, area.source) configured_areas[key], configured_signatures[key] = true, area.identity remove_guide() area_tick() -- Applies immediately if VLC dimensions are already known. if #pending_areas > 0 then start_area_timer() report(string.format("Replay area saved: %.0f x %.0f. It will activate when the first replay loads.", w, h)) end end local function cancel_replay_area() if not guide then local recovered, why, has_guide = recover_replay_area_guide() if not recovered then report(has_guide and why or "No replay-area setup is active.", has_guide and obs.LOG_WARNING or obs.LOG_INFO) return end end local key = area_key(guide.scene, guide.target) configured_areas[key], configured_signatures[key] = true, guide.identity remove_guide() report("Replay-area setup canceled. Existing layout unchanged. Use Set Replay Area in Tools > Scripts to restart setup.") end -- If the user did not select a VLC source in the script properties, the only -- direct VLC item in this scene is an unambiguous candidate. Never guess when -- multiple VLC items are present. Existing settings remain authoritative. local function auto_resolve_source(scene) if cfg.source ~= "" then local existing = obs.obs_get_source_by_name(cfg.source) if existing then local valid = obs.obs_source_get_id(existing) == "vlc_source" obs.obs_source_release(existing) if valid then return cfg.source end end end -- The original named source no longer exists. Rebind only when there is -- exactly ONE direct VLC source in this scene; never guess among several. local items = obs.obs_scene_enum_items(scene) if not items then return nil end local found, count = nil, 0 for _, item in ipairs(items) do local src = obs.obs_sceneitem_get_source(item) if src and obs.obs_source_get_id(src) == "vlc_source" then count, found = count + 1, obs.obs_source_get_name(src) end end obs.sceneitem_list_release(items) if count ~= 1 then return nil end local previous = cfg.source cfg.source = found if previous == "" then report("Selected the only VLC Video Source in this scene: " .. found .. ".") else -- Clear any replay file-selection state from the missing source. selected = 0 report("Previous VLC source was removed. Automatically linked replacement: " .. found .. ".") end return found end local function maybe_auto_replay_area() if not loaded or output_active() then -- A guide is a visible source and must not survive transition to output. if guide and output_active() then remove_guide() end return end local scene_source, scene = current_scene_context() if not scene_source then return end local scene_name = obs.obs_source_get_name(scene_source) if guide then -- A guide can outlive its VLC target, particularly when a source is -- deleted during setup. Remove it, then allow the new target to qualify. local item = scene_name == guide.scene and obs.obs_scene_find_source(scene, guide.target) or nil local still_valid = item and obs.obs_source_get_id(obs.obs_sceneitem_get_source(item)) == "vlc_source" if still_valid and guide.identity then still_valid = scene_item_signature(item) == guide.identity end if still_valid then obs.obs_source_release(scene_source); return end local old_scene, old_source = guide.scene, guide.target remove_guide() discard_old_area(old_scene, old_source) report("The VLC target changed. Discarded its obsolete temporary replay guide.", obs.LOG_WARNING) end local source_name = auto_resolve_source(scene) if not source_name then obs.obs_source_release(scene_source); return end local key = area_key(scene_name, source_name) local target_item = obs.obs_scene_find_source(scene, source_name) local target = target_item and obs.obs_sceneitem_get_source(target_item) or nil if not target or obs.obs_source_get_id(target) ~= "vlc_source" then obs.obs_source_release(scene_source); return end local identity = scene_item_signature(target_item) if configured_areas[key] then local saved_id = configured_signatures[key] if saved_id and identity and saved_id ~= identity then -- A new OBS source or new scene item with the same name. discard_old_area(scene_name, source_name) report("Replacement VLC scene item detected; replay area needs setup again.") elseif not saved_id then -- dev5 stored only names. Preserve previously applied dimensions, -- but treat a default-sized, newly created item as unconfigured. local has_bounds = obs.obs_sceneitem_get_bounds_type(target_item) ~= (obs.OBS_BOUNDS_NONE or 0) if not has_bounds and not pending_for(scene_name, source_name) then discard_old_area(scene_name, source_name) report("Unconfigured VLC scene item detected; opening replay area guide.") else configured_signatures[key] = identity end end end if configured_areas[key] or attempted_areas[key] then obs.obs_source_release(scene_source); return end if not vlc_playlist_empty(target) then obs.obs_source_release(scene_source); return end obs.obs_source_release(scene_source) -- A prior version/reload might have left the guide in this scene. local recovered, why, has_guide = recover_replay_area_guide() if recovered then attempted_areas[key] = true report("Existing replay-area guide recovered. Resize it, then click its eye icon in Sources.") return end if has_guide then attempted_areas[key] = true report(why, obs.LOG_WARNING) return end if not output_active() then begin_replay_area() end end auto_tick = function() local ok, err = pcall(maybe_auto_replay_area) if not ok then if auto_timer_running then obs.timer_remove(auto_tick); auto_timer_running = false end report("Automatic replay-area setup disabled after error: " .. tostring(err), obs.LOG_ERROR) end end local function load_configured_areas(settings) local array = obs.obs_data_get_array(settings, "completed_replay_areas") if not array then return end for i = 0, obs.obs_data_array_count(array) - 1 do local item = obs.obs_data_array_item(array, i) local scene, source = obs.obs_data_get_string(item, "scene"), obs.obs_data_get_string(item, "source") local collection = obs.obs_data_get_string(item, "collection") if scene ~= "" and source ~= "" then local key = area_key(scene, source, collection) configured_areas[key] = true local identity = obs.obs_data_get_string(item, "identity") if identity ~= "" then configured_signatures[key] = identity end end obs.obs_data_release(item) end obs.obs_data_array_release(array) end local function save_configured_areas(settings) local array = obs.obs_data_array_create() -- Keys are packed in a length-prefixed format. Parse without relying on a -- separator that might appear in a user-selected scene/source name. for key in pairs(configured_areas) do local clen, body = key:match("^(%d+):(.*)$") local c = tonumber(clen) if c and #body >= c then local collection = body:sub(1, c) local rest = body:sub(c + 1) local slen, remainder = rest:match("^(%d+):(.*)$") local n = tonumber(slen) if n and n > 0 and #remainder > n then local item = obs.obs_data_create() obs.obs_data_set_string(item, "collection", collection) obs.obs_data_set_string(item, "scene", remainder:sub(1, n)) obs.obs_data_set_string(item, "source", remainder:sub(n + 1)) obs.obs_data_set_string(item, "identity", configured_signatures[key] or "") obs.obs_data_array_push_back(array, item) obs.obs_data_release(item) end end end obs.obs_data_set_array(settings, "completed_replay_areas", array) obs.obs_data_array_release(array) end local function read_pending_areas(settings) local array = obs.obs_data_get_array(settings, "pending_replay_areas") if not array then return end for i = 0, obs.obs_data_array_count(array) - 1 do local item = obs.obs_data_array_item(array, i) local area = { scene = obs.obs_data_get_string(item, "scene"), source = obs.obs_data_get_string(item, "source"), x = obs.obs_data_get_double(item, "x"), y = obs.obs_data_get_double(item, "y"), width = obs.obs_data_get_double(item, "width"), height = obs.obs_data_get_double(item, "height"), rot = 0, alignment = obs.obs_data_get_int(item, "alignment"), identity = obs.obs_data_get_string(item, "identity") } if area.scene ~= "" and area.source ~= "" and area.width > 0 and area.height > 0 then queue_area(area) end obs.obs_data_release(item) end obs.obs_data_array_release(array) end local function save_pending_areas(settings) local array = obs.obs_data_array_create() for _, area in ipairs(pending_areas) do local item = obs.obs_data_create() obs.obs_data_set_string(item, "scene", area.scene) obs.obs_data_set_string(item, "source", area.source) obs.obs_data_set_double(item, "x", area.x) obs.obs_data_set_double(item, "y", area.y) obs.obs_data_set_double(item, "width", area.width) obs.obs_data_set_double(item, "height", area.height) obs.obs_data_set_int(item, "alignment", area.alignment) obs.obs_data_set_string(item, "identity", area.identity or "") obs.obs_data_array_push_back(array, item) obs.obs_data_release(item) end obs.obs_data_set_array(settings, "pending_replay_areas", array) obs.obs_data_array_release(array) end on_event = function(event) if event == obs.OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED then awaiting_completion = false -- Only process a pending script request. Native saves otherwise retain -- their original OBS-only behavior. OBS events do not contain request IDs. if not job or job.state ~= "saving" then return end local path = get_last_path() if not path or path == "" then cancel("OBS reported a save, but returned no replay path."); return end job.path = path if job.folder ~= "" then local ok, err = pcall(start_copy, job) if not ok then cancel("Cannot prepare copy: " .. tostring(err)) end else finish(path) end elseif event == obs.OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED then awaiting_completion = false if job and job.state == "saving" then cancel("Replay buffer stopped before completion was received.") end elseif event == obs.OBS_FRONTEND_EVENT_STREAMING_STARTING or event == obs.OBS_FRONTEND_EVENT_RECORDING_STARTING or (obs.OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING and event == obs.OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING) or (obs.OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED and event == obs.OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED) then if guide then remove_guide() report("OBS output starting: temporary replay-area guide removed for safety.", obs.LOG_WARNING) end elseif event == obs.OBS_FRONTEND_EVENT_SCENE_CHANGED then if guide then local current = obs.obs_frontend_get_current_scene() local name = current and obs.obs_source_get_name(current) or "" if current then obs.obs_source_release(current) end if name ~= guide.scene then remove_guide() report("Scene changed; temporary replay-area guide removed.", obs.LOG_WARNING) end end elseif event == obs.OBS_FRONTEND_EVENT_SCENE_COLLECTION_CHANGING or event == obs.OBS_FRONTEND_EVENT_PROFILE_CHANGING then remove_guide() pending_areas = {} stop_area_timer() cancel("OBS context changed; pending replay processing canceled.") history, selected = {}, 0 end end local function navigate(direction) if #history == 0 then report("No replays in this session.", obs.LOG_WARNING); return end local index = selected == 0 and (direction == 1 and 1 or #history) or selected + direction while index >= 1 and index <= #history do local ok, reason = select_entry(index) if ok or reason == "source" then return end index = index + direction end report("No further available replay in that direction. Current selection unchanged.") end function replay_prev(pressed) if pressed then navigate(-1) end end function replay_next(pressed) if pressed then navigate(1) end end function replay_latest(pressed) if not pressed then return end for index = #history, 1, -1 do if index == selected and readable(history[index].path) then report("Latest available replay is already selected."); return end local ok, reason = select_entry(index) if ok or reason == "source" then return end end report("No available replay in this session.", obs.LOG_WARNING) end function clear_vlc_playlist(pressed) if not pressed then return end cancel() history, selected = {}, 0 local ok, err = set_playlist(cfg.source, nil) report(ok and "Playlist and history cleared. Recordings were not deleted." or ("History cleared; playlist unchanged: " .. err), ok and obs.LOG_INFO or obs.LOG_WARNING) end local function check_setup() local s, err = source_for(cfg.source) if not s then report(err, obs.LOG_WARNING); return end obs.obs_source_release(s) if cfg.folder ~= "" then if not obs.os_opendir or not obs.os_mkdir or not obs.os_rmdir or not obs.os_unlink or not obs.os_file_exists then report("Cannot validate folder with this OBS build.", obs.LOG_WARNING); return end local dir = obs.os_opendir(cfg.folder) if not dir then report("Copy folder is not an accessible directory.", obs.LOG_WARNING); return end obs.os_closedir(dir) -- A write probe is deliberately performed only when the user clicks Check. local probe = {path = "setup-check.tmp", folder = cfg.folder} local ok, why = reserve_copy(probe) if not ok then report(why, obs.LOG_WARNING); return end local temp = join(probe.lock, "probe.tmp") probe.output, why = io.open(temp, "wb") if probe.output then probe.temp = temp ok, why = probe.output:write("Instant Replay VLC setup check") local closed, close_err = probe.output:close(); probe.output = nil if not closed then ok, why = false, close_err end else ok = false end cleanup_copy(probe) if not ok then report("Copy folder write check failed: " .. tostring(why), obs.LOG_WARNING); return end end report(obs.obs_frontend_replay_buffer_active() and "Setup check passed. Use a dedicated VLC source; scene switching remains manual." or "Source/folder checks passed. Start Replay Buffer before saving.") end function script_description() return "Instant Replay VLC " .. VERSION .. [[ Save OBS Replay Buffer clips to a dedicated VLC source. Optional file copies and replay navigation. Setup: Select a VLC source and assign Save / Previous / Next / Latest / Clear in Settings > Hotkeys. Replay area: While off-air, resize the blue guide and click its eye icon in Sources to apply. Use Set Replay Area to redo. Clear does not delete recordings. Replay history resets when OBS closes. ]] end local function options_changed(props, _, settings) obs.obs_property_set_enabled(obs.obs_properties_get(props, "use_copied_file"), obs.obs_data_get_string(settings, "copy_folder") ~= "") return true end local function safe_area_callback(callback) local ok, err = pcall(callback) if not ok then report("Replay area action failed: " .. tostring(err), obs.LOG_ERROR) end return true end function script_properties() local props = obs.obs_properties_create() local list = obs.obs_properties_add_list(props, "source", "Dedicated VLC Video Source", obs.OBS_COMBO_TYPE_LIST, obs.OBS_COMBO_FORMAT_STRING) obs.obs_property_list_add_string(list, "Select a VLC source", "") local sources, found = obs.obs_enum_sources(), false if sources then for _, s in ipairs(sources) do if obs.obs_source_get_id(s) == "vlc_source" then local name = obs.obs_source_get_name(s) obs.obs_property_list_add_string(list, name, name) if name == cfg.source then found = true end end end obs.source_list_release(sources) end if cfg.source ~= "" and not found then obs.obs_property_list_add_string(list, "Missing: " .. cfg.source, cfg.source) end local folder = obs.obs_properties_add_path(props, "copy_folder", "Copy replays to folder (optional)", obs.OBS_PATH_DIRECTORY, "", "") obs.obs_property_set_modified_callback(folder, options_changed) local copied = obs.obs_properties_add_bool(props, "use_copied_file", "Play copied replay") obs.obs_property_set_enabled(copied, cfg.folder ~= "") obs.obs_properties_add_int(props, "timeout_seconds", "Save timeout (seconds)", 2, 120, 1) obs.obs_properties_add_button(props, "begin_area", "Set Replay Area (off-air)", function() return safe_area_callback(begin_replay_area) end) obs.obs_properties_add_button(props, "finish_area", "Apply Replay Area", function() return safe_area_callback(finish_replay_area) end) obs.obs_properties_add_button(props, "cancel_area", "Cancel Replay Area", function() return safe_area_callback(cancel_replay_area) end) obs.obs_properties_add_button(props, "check", "Check setup", function() check_setup(); return true end) obs.obs_properties_add_button(props, "refresh", "Refresh sources / status", function() return true end) obs.obs_properties_add_text(props, "status", "Status: " .. status, obs.OBS_TEXT_INFO) return props end function script_defaults(settings) obs.obs_data_set_default_bool(settings, "use_copied_file", true) obs.obs_data_set_default_int(settings, "interval", 500) obs.obs_data_set_default_int(settings, "max_attempts", 20) end function script_update(settings) local source = obs.obs_data_get_string(settings, "source") if source ~= cfg.source then cancel() remove_guide() -- A deferred transform must never modify a source the user has -- deliberately deselected in script settings. for i = #pending_areas, 1, -1 do if pending_areas[i].source == cfg.source then table.remove(pending_areas, i) end end if #pending_areas == 0 then stop_area_timer() end selected = 0 end cfg.source = source cfg.folder = obs.obs_data_get_string(settings, "copy_folder") cfg.copied = obs.obs_data_get_bool(settings, "use_copied_file") local timeout = obs.obs_data_get_int(settings, "timeout_seconds") if timeout <= 0 then timeout = obs.obs_data_get_int(settings, "interval") * obs.obs_data_get_int(settings, "max_attempts") / 1000 if timeout <= 0 then timeout = 10 end end cfg.timeout = math.max(2, math.min(120, math.ceil(timeout))) obs.obs_data_set_int(settings, "timeout_seconds", cfg.timeout) end function script_load(settings) script_update(settings) read_pending_areas(settings) load_configured_areas(settings) if not obs.OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED or not obs.os_gettime_ns then report("Unsupported OBS build: replay saved events and monotonic timer are required.", obs.LOG_ERROR); return end local definitions = { {"trigger", "Save Replay", instant_replay}, {"prev", "Previous Replay", replay_prev}, {"next", "Next Replay", replay_next}, {"latest", "Latest Replay", replay_latest}, {"clear_playlist", "Clear playlist + history", clear_vlc_playlist} } for _, definition in ipairs(definitions) do local key = "instant_replay_vlc." .. definition[1] local id = obs.obs_hotkey_register_frontend(key, "Instant Replay VLC: " .. definition[2], definition[3]) hotkeys[key] = id local data = obs.obs_data_get_array(settings, key) obs.obs_hotkey_load(id, data) obs.obs_data_array_release(data) end obs.obs_frontend_add_event_callback(on_event) loaded = true start_area_timer() if not auto_timer_running then obs.timer_add(auto_tick, AUTO_POLL_MS) auto_timer_running = true end report("Loaded " .. VERSION .. ". Existing hotkeys retained; check setup before going live.") end function script_save(settings) if cfg.source ~= "" then obs.obs_data_set_string(settings, "source", cfg.source) end save_pending_areas(settings) save_configured_areas(settings) for key, id in pairs(hotkeys) do local data = obs.obs_hotkey_save(id) obs.obs_data_set_array(settings, key, data) obs.obs_data_array_release(data) end end function script_unload() remove_guide() stop_area_timer() if auto_timer_running then obs.timer_remove(auto_tick); auto_timer_running = false end cancel() if loaded then obs.obs_frontend_remove_event_callback(on_event) end loaded = false history, selected = {}, 0 -- OBS owns and unregisters script hotkeys on unload. end