1 --[==========================================================================[
2 rc.lua: remote control module for VLC
3 --[==========================================================================[
4 Copyright (C) 2007-2009 the VideoLAN team
7 Authors: Antoine Cellerier <dionoea at videolan dot org>
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 --]==========================================================================]
25 [============================================================================[
26 Remote control interface for VLC
28 This is a modules/control/rc.c look alike (with a bunch of new features)
32 Use on tcp connection:
33 vlc -I luarc --lua-config "rc={host='localhost:4212'}"
34 Use on multiple hosts (term + 2 tcp ports):
35 vlc -I luarc --lua-config "rc={hosts={'*console','localhost:4212','localhost:5678'}}"
38 -I luarc is an alias for -I lua --lua-intf rc
40 Configuration options setable throught the --lua-config option are:
41 * hosts: A list of hosts to listen on.
42 * host: A host to listen on. (won't be used if `hosts' is set)
43 The following can be set using the --lua-config option or in the interface
44 itself using the `set' command:
46 * welcome: The welcome message.
47 * width: The default terminal width (used to format text).
48 * autocompletion: When issuing an unknown command, print a list of
49 possible commands to autocomplete with. (0 to disable,
51 * autoalias: If autocompletion returns only one possibility, use it
52 (0 to disable, 1 to enable).
53 * flatplaylist: 0 to disable, 1 to enable.
54 ]============================================================================]
58 skip2 = function(foo) return skip(skip(foo)) end
59 setarg = common.setarg
62 --[[ Setup default environement ]]
63 env = { prompt = "> ";
67 welcome = "Remote control interface initialized. Type `help' for help.";
71 --[[ Import custom environement variables from the command line config (if possible) ]]
72 for k,v in pairs(env) do
74 if type(env[k]) == type(config[k]) then
76 vlc.msg.dbg("set environement variable `"..k.."' to "..tostring(env[k]))
78 vlc.msg.err("environement variable `"..k.."' should be of type "..type(env[k])..". config value will be discarded.")
83 --[[ Command functions ]]
84 function set_env(name,client,value)
86 local var,val = split_input(value)
88 s = string.gsub(val,"\"(.*)\"","%1")
89 if type(client.env[var])==type(1) then
90 client.env[var] = tonumber(s)
95 client:append( tostring(client.env[var]) )
98 for e,v in common.pairs_sorted(client.env) do
99 client:append(e.."="..v)
104 function save_env(name,client,value)
105 env = common.table_copy(client.env)
108 function alias(client,value)
110 local var,val = split_input(value)
111 if commands[var] and type(commands[var]) ~= type("") then
112 client:append("Error: cannot use a primary command as an alias name")
114 if commands[val] then
117 client:append("Error: unknown primary command `"..val.."'.")
121 for c,v in common.pairs_sorted(commands) do
122 if type(v)==type("") then
123 client:append(c.."="..v)
129 function fixme(name,client)
130 client:append( "FIXME: unimplemented command `"..name.."'." )
133 function logout(name,client)
134 if client.type == host.client_type.net then
135 client:send("Bye-bye!")
138 client:append("Error: Can't logout of stdin/stdout. Use quit or shutdown to close VLC.")
142 function shutdown(name,client)
143 client:append("Bye-bye!")
144 h:broadcast("Shutting down.")
145 vlc.msg.info("Requested shutdown.")
149 function quit(name,client)
150 if client.type == host.client_type.net then
153 shutdown(name,client)
157 function add(name,client,arg)
158 -- TODO: par single and double quotes properly
160 if name == "enqueue" then
161 f = vlc.playlist.enqueue
166 for o in string.gmatch(arg," +:([^ ]*)") do
167 table.insert(options,o)
169 arg = string.gsub(arg," +:.*$","")
170 f({{path=arg,options=options}})
173 function playlist_is_tree( client )
174 if client.env.flatplaylist == 0 then
181 function playlist(name,client,arg)
182 function playlist0(item,prefix)
183 local prefix = prefix or ""
184 if not item.flags.disabled then
185 local str = "| "..prefix..tostring(item.id).." - "..item.name
186 if item.duration > 0 then
187 str = str.." ("..common.durationtostring(item.duration)..")"
189 if item.nb_played > 0 then
190 str = str.." [played "..tostring(item.nb_played).." time"
191 if item.nb_played > 1 then
198 if item.children then
199 for _, c in ipairs(item.children) do
200 playlist0(c,prefix.." ")
205 local tree = playlist_is_tree(client)
206 if name == "search" then
207 playlist = vlc.playlist.search(arg or "", tree)
209 if tonumber(arg) then
210 playlist = vlc.playlist.get(tonumber(arg), tree)
212 playlist = vlc.playlist.get(arg, tree)
214 playlist = vlc.playlist.get(nil, tree)
217 if name == "search" then
218 client:append("+----[ Search - "..(arg or "`reset'").." ]")
220 client:append("+----[ Playlist - "..playlist.name.." ]")
222 if playlist.children then
223 for _, item in ipairs(playlist.children) do
229 if name == "search" then
230 client:append("+----[ End of search - Use `search' to reset ]")
232 client:append("+----[ End of playlist ]")
236 function playlist_sort(name,client,arg)
238 client:append("Valid sort keys are: id, title, artist, genre, random, duration, album.")
240 local tree = playlist_is_tree(client)
241 vlc.playlist.sort(arg,false,tree)
245 function services_discovery(name,client,arg)
247 if vlc.sd.is_loaded(arg) then
249 client:append(arg.." disabled.")
252 client:append(arg.." enabled.")
255 local sd = vlc.sd.get_services_names()
256 client:append("+----[ Services discovery ]")
257 for n,ln in pairs(sd) do
259 if vlc.sd.is_loaded(n) then
264 client:append("| "..n..": " .. ln .. " (" .. status .. ")")
266 client:append("+----[ End of services discovery ]")
270 function print_text(label,text)
271 return function(name,client)
272 client:append("+----[ "..label.." ]")
274 for line in string.gmatch(text,".-\r?\n") do
275 client:append("| "..string.gsub(line,"\r?\n",""))
278 client:append("+----[ End of "..string.lower(label).." ]")
282 function help(name,client,arg)
283 local width = client.env.width
284 local long = (name == "longhelp")
286 if arg then extra = "matching `" .. arg .. "' " end
287 client:append("+----[ Remote control commands "..extra.."]")
288 for i, cmd in ipairs(commands_ordered) do
289 if (cmd == "" or not commands[cmd].adv or long)
290 and (not arg or string.match(cmd,arg)) then
291 local str = "| " .. cmd
293 local val = commands[cmd]
295 for _,a in ipairs(val.aliases) do
296 str = str .. ", " .. a
299 if val.args then str = str .. " " .. val.args end
300 if #str%2 == 1 then str = str .. " " end
301 str = str .. string.rep(" .",(width-(#str+#val.help)-1)/2)
302 str = str .. string.rep(" ",width-#str-#val.help) .. val.help
307 client:append("+----[ end of help ]")
310 function input_info(name,client)
311 local categories = vlc.input.info()
312 for cat, infos in pairs(categories) do
313 client:append("+----[ "..cat.." ]")
315 for name, value in pairs(infos) do
316 client:append("| "..name..": "..value)
320 client:append("+----[ end of stream info ]")
323 function stats(name,client)
324 local stats_tab = vlc.input.stats()
326 client:append("+----[ begin of statistical info")
327 client:append("+-[Incoming]")
328 client:append("| input bytes read : "..string.format("%8.0f kB",stats_tab["read_bytes"]/1000))
329 client:append("| input bitrate : "..string.format("%6.0f bB/s",stats_tab["input_bitrate"]*8000))
330 client:append("| demux bytes read : "..string.format("%8.0f kB",stats_tab["demux_read_bytes"]/1000))
331 client:append("| demux bitrate : "..string.format("%6.0f kB/s",stats_tab["demux_bitrate"]*8000))
332 client:append("| demux corrupted : "..string.format("%5i",stats_tab["demux_corrupted"]))
333 client:append("| discontinuities : "..string.format("%5i",stats_tab["demux_discontinuity"]))
335 client:append("+-[Video Decoding]")
336 client:append("| video decoded : "..string.format("%5i",stats_tab["decoded_video"]))
337 client:append("| frames displayed : "..string.format("%5i",stats_tab["displayed_pictures"]))
338 client:append("| frames lost : "..string.format("%5i",stats_tab["lost_pictures"]))
340 client:append("+-[Audio Decoding]")
341 client:append("| audio decoded : "..string.format("%5i",stats_tab["decoded_audio"]))
342 client:append("| buffers played : "..string.format("%5i",stats_tab["played_abuffers"]))
343 client:append("| buffers lost : "..string.format("%5i",stats_tab["lost_abuffers"]))
345 client:append("+-[Streaming]")
346 client:append("| packets sent : "..string.format("%5i",stats_tab["sent_packets"]))
347 client:append("| bytes sent : "..string.format("%8.0f kB",stats_tab["sent_bytes"]/1000))
348 client:append("| sending bitrate : "..string.format("%6.0f kb/s",stats_tab["send_bitrate"]*8000))
349 client:append("+----[ end of statistical info ]")
352 function playlist_status(name,client)
353 local a,b,c = vlc.playlist.status()
354 client:append( "( new input: " .. tostring(a) .. " )" )
355 client:append( "( audio volume: " .. tostring(b) .. " )")
356 client:append( "( state " .. tostring(c) .. " )")
359 function is_playing(name,client)
360 if vlc.input.is_playing() then client:append "1" else client:append "0" end
363 function ret_print(foo,start,stop)
364 local start = start or ""
365 local stop = stop or ""
366 return function(discard,client,...) client:append(start..tostring(foo(...))..stop) end
369 function get_time(var)
370 return function(name,client)
371 local input = vlc.object.input()
372 client:append(math.floor(vlc.var.get( input, var )))
376 function titlechap(name,client,value)
377 local input = vlc.object.input()
378 local var = string.gsub( name, "_.*$", "" )
380 vlc.var.set( input, var, value )
382 local item = vlc.var.get( input, var )
383 -- Todo: add item name conversion
387 function titlechap_offset(client,offset)
388 return function(name,value)
389 local input = vlc.object.input()
390 local var = string.gsub( name, "_.*$", "" )
391 vlc.var.set( input, var, vlc.var.get( input, var )+offset )
395 function seek(name,client,value)
399 function volume(name,client,value)
401 vlc.volume.set(value)
403 client:append(tostring(vlc.volume.get()))
407 function rate(name,client)
408 local input = vlc.object.input()
409 if name == "normal" then
410 vlc.var.set(input,"rate",1)
412 vlc.var.set(input,"rate-"..name,nil)
416 function frame(name,client)
417 vlc.var.trigger_callback(vlc.object.input(),"frame-next");
420 function listvalue(obj,var)
421 return function(client,value)
422 local o = vlc.object.find(nil,obj,"anywhere")
423 if not o then return end
425 vlc.var.set( o, var, value )
427 local c = vlc.var.get( o, var )
428 local v, l = vlc.var.get_list( o, var )
429 client:append("+----[ "..var.." ]")
430 for i,val in ipairs(v) do
431 local mark = (val==c)and " *" or ""
432 client:append("| "..tostring(val).." - "..tostring(l[i])..mark)
434 client:append("+----[ end of "..var.." ]")
439 function eval(client,val)
440 client:append(loadstring("return "..val)())
443 --[[ Declare commands, register their callback functions and provide
446 "<command name>"; { func = <function>; [ args = "<str>"; ] help = "<str>"; [ adv = <bool>; ] [ aliases = { ["<str>";]* }; ] }
449 { "add"; { func = add; args = "XYZ"; help = "add XYZ to playlist" } };
450 { "enqueue"; { func = add; args = "XYZ"; help = "queue XYZ to playlist" } };
451 { "playlist"; { func = playlist; help = "show items currently in playlist" } };
452 { "search"; { func = playlist; args = "[string]"; help = "search for items in playlist (or reset search)" } };
453 { "sort"; { func = playlist_sort; args = "key"; help = "sort the playlist" } };
454 { "sd"; { func = services_discovery; args = "[sd]"; help = "show services discovery or toggle" } };
455 { "play"; { func = skip2(vlc.playlist.play); help = "play stream" } };
456 { "stop"; { func = skip2(vlc.playlist.stop); help = "stop stream" } };
457 { "next"; { func = skip2(vlc.playlist.next); help = "next playlist item" } };
458 { "prev"; { func = skip2(vlc.playlist.prev); help = "previous playlist item" } };
459 { "goto"; { func = skip2(vlc.playlist.goto); help = "goto item at index" } };
460 { "repeat"; { func = skip2(vlc.playlist.repeat_); args = "[on|off]"; help = "toggle playlist repeat" } };
461 { "loop"; { func = skip2(vlc.playlist.loop); args = "[on|off]"; help = "toggle playlist loop" } };
462 { "random"; { func = skip2(vlc.playlist.random); args = "[on|off]"; help = "toggle playlist random" } };
463 { "clear"; { func = skip2(vlc.playlist.clear); help = "clear the playlist" } };
464 { "status"; { func = playlist_status; help = "current playlist status" } };
465 { "title"; { func = titlechap; args = "[X]"; help = "set/get title in current item" } };
466 { "title_n"; { func = titlechap_offset(1); help = "next title in current item" } };
467 { "title_p"; { func = titlechap_offset(-1); help = "previous title in current item" } };
468 { "chapter"; { func = titlechap; args = "[X]"; help = "set/get chapter in current item" } };
469 { "chapter_n"; { func = titlechap_offset(1); help = "next chapter in current item" } };
470 { "chapter_p"; { func = titlechap_offset(-1); help = "previous chapter in current item" } };
472 { "seek"; { func = seek; args = "X"; help = "seek in seconds, for instance `seek 12'" } };
473 { "pause"; { func = setarg(common.hotkey,"key-play-pause"); help = "toggle pause" } };
474 { "fastforward"; { func = setarg(common.hotkey,"key-jump+extrashort"); help = "set to maximum rate" } };
475 { "rewind"; { func = setarg(common.hotkey,"key-jump-extrashort"); help = "set to minimum rate" } };
476 { "faster"; { func = rate; help = "faster playing of stream" } };
477 { "slower"; { func = rate; help = "slower playing of stream" } };
478 { "normal"; { func = rate; help = "normal playing of stream" } };
479 { "frame"; { func = frame; help = "play frame by frame" } };
480 { "fullscreen"; { func = skip2(vlc.video.fullscreen); args = "[on|off]"; help = "toggle fullscreen"; aliases = { "f", "F" } } };
481 { "info"; { func = input_info; help = "information about the current stream" } };
482 { "stats"; { func = stats; help = "show statistical information" } };
483 { "get_time"; { func = get_time("time"); help = "seconds elapsed since stream's beginning" } };
484 { "is_playing"; { func = is_playing; help = "1 if a stream plays, 0 otherwise" } };
485 { "get_title"; { func = ret_print(vlc.input.get_title); help = "the title of the current stream" } };
486 { "get_length"; { func = get_time("length"); help = "the length of the current stream" } };
488 { "volume"; { func = volume; args = "[X]"; help = "set/get audio volume" } };
489 { "volup"; { func = ret_print(vlc.volume.up,"( audio volume: "," )"); args = "[X]"; help = "raise audio volume X steps" } };
490 { "voldown"; { func = ret_print(vlc.volume.down,"( audio volume: "," )"); args = "[X]"; help = "lower audio volume X steps" } };
491 { "adev"; { func = skip(listvalue("aout","audio-device")); args = "[X]"; help = "set/get audio device" } };
492 { "achan"; { func = skip(listvalue("aout","audio-channels")); args = "[X]"; help = "set/get audio channels" } };
493 { "atrack"; { func = skip(listvalue("input","audio-es")); args = "[X]"; help = "set/get audio track" } };
494 { "vtrack"; { func = skip(listvalue("input","video-es")); args = "[X]"; help = "set/get video track" } };
495 { "vratio"; { func = skip(listvalue("vout","aspect-ratio")); args = "[X]"; help = "set/get video aspect ratio" } };
496 { "vcrop"; { func = skip(listvalue("vout","crop")); args = "[X]"; help = "set/get video crop"; aliases = { "crop" } } };
497 { "vzoom"; { func = skip(listvalue("vout","zoom")); args = "[X]"; help = "set/get video zoom"; aliases = { "zoom" } } };
498 { "snapshot"; { func = common.snapshot; help = "take video snapshot" } };
499 { "strack"; { func = skip(listvalue("input","spu-es")); args = "[X]"; help = "set/get subtitles track" } };
500 { "hotkey"; { func = skip(common.hotkey); args = "[hotkey name]"; help = "simulate hotkey press"; adv = true; aliases = { "key" } } };
501 { "menu"; { func = fixme; args = "[on|off|up|down|left|right|select]"; help = "use menu"; adv = true } };
503 { "set"; { func = set_env; args = "[var [value]]"; help = "set/get env var"; adv = true } };
504 { "save_env"; { func = save_env; help = "save env vars (for future clients)"; adv = true } };
505 { "alias"; { func = skip(alias); args = "[cmd]"; help = "set/get command aliases"; adv = true } };
506 { "eval"; { func = skip(eval); help = "eval some lua (*debug*)"; adv =true } }; -- FIXME: comment out if you're not debugging
507 { "description"; { func = print_text("Description",description); help = "describe this module" } };
508 { "license"; { func = print_text("License message",vlc.misc.license()); help = "print VLC's license message"; adv = true } };
509 { "help"; { func = help; args = "[pattern]"; help = "a help message"; aliases = { "?" } } };
510 { "longhelp"; { func = help; args = "[pattern]"; help = "a longer help message" } };
511 { "logout"; { func = logout; help = "exit (if in a socket connection)" } };
512 { "quit"; { func = quit; help = "quit VLC (or logout if in a socket connection)" } };
513 { "shutdown"; { func = shutdown; help = "shutdown VLC" } };
516 for i, cmd in ipairs( commands_ordered ) do
518 commands[cmd[1]]=cmd[2]
519 if cmd[2].aliases then
520 for _,a in ipairs(cmd[2].aliases) do
525 commands_ordered[i]=cmd[1]
527 --[[ From now on commands_ordered is a list of the different command names
528 and commands is a associative array indexed by the command name. ]]
530 -- Compute the column width used when printing a the autocompletion list
532 for c,_ in pairs(commands) do
533 if #c > env.colwidth then env.colwidth = #c end
535 env.coldwidth = env.colwidth + 1
537 -- Count unimplemented functions
541 for c,v in pairs(commands) do
542 if v.func == fixme then
551 if count ~= 0 and env.welcome then
552 env.welcome = env.welcome .. "\r\nWarning: "..count.." functions are still unimplemented "..list.."."
557 function split_input(input)
558 local input = strip(input)
559 local s = string.find(input," ")
561 return string.sub(input,0,s-1), strip(string.sub(input,s))
567 function call_command(cmd,client,arg)
568 if type(commands[cmd]) == type("") then
573 ok, msg = pcall( commands[cmd].func, cmd, client, arg )
575 ok, msg = pcall( commands[cmd].func, cmd, client )
579 if a ~= "" then a = " " .. a end
580 client:append("Error in `"..cmd..a.."' ".. msg)
584 function call_libvlc_command(cmd,client,arg)
585 local ok, vlcerr, vlcmsg = pcall( vlc.var.libvlc_command, cmd, arg )
588 if a ~= "" then a = " " .. a end
589 client:append("Error in `"..cmd..a.."' ".. vlcerr) -- when pcall fails, the 2nd arg is the error message.
594 function call_object_command(cmd,client,arg)
595 local var, val = split_input(arg)
596 local ok, vlcmsg, vlcerr, vlcerrmsg = pcall( vlc.var.command, cmd, var, val )
598 client:append("Error in `"..cmd.." "..var.." "..val.."' ".. vlcmsg) -- when pcall fails the 2nd arg is the error message
601 client:append(vlcmsg)
610 h.status_callbacks[host.status.password] = function(client)
611 client.env = common.table_copy( env )
612 client:send( client.env.welcome .. "\r\n")
613 client:switch_status(host.status.read)
615 -- Print prompt when switching a client's status to `read'
616 h.status_callbacks[host.status.read] = function(client)
617 client:send( client.env.prompt )
620 h:listen( config.hosts or config.host or "*console" )
622 --[[ The main loop ]]
623 while not vlc.misc.should_die() do
625 local write, read = h:select(0.1)
627 for _, client in pairs(write) do
628 local len = client:send()
629 client.buffer = string.sub(client.buffer,len+1)
630 if client.buffer == "" then client:switch_status(host.status.read) end
633 for _, client in pairs(read) do
634 local input = client:recv(1000)
636 if string.match(input,"\n$") then
637 client.buffer = string.gsub(client.buffer..input,"\r?\n$","")
639 elseif client.buffer == ""
640 and ((client.type == host.client_type.stdio and input == "")
641 or (client.type == host.client_type.net and input == "\004")) then
643 client.buffer = "quit"
646 client.buffer = client.buffer .. input
649 local cmd,arg = split_input(client.buffer)
651 client:switch_status(host.status.write)
652 if commands[cmd] then
653 call_command(cmd,client,arg)
654 elseif string.sub(cmd,0,1)=='@'
655 and call_object_command(string.sub(cmd,2,#cmd),client,arg) == 0 then
657 elseif client.type == host.client_type.stdio
658 and call_libvlc_command(cmd,client,arg) == 0 then
662 if client.env.autocompletion ~= 0 then
663 for v,_ in common.pairs_sorted(commands) do
664 if string.sub(v,0,#cmd)==cmd then
665 table.insert(choices, v)
669 if #choices == 1 and client.env.autoalias ~= 0 then
670 -- client:append("Aliasing to \""..choices[1].."\".")
672 call_command(cmd,client,arg)
674 client:append("Unknown command `"..cmd.."'. Type `help' for help.")
675 if #choices ~= 0 then
676 client:append("Possible choices are:")
677 local cols = math.floor(client.env.width/(client.env.colwidth+1))
678 local fmt = "%-"..client.env.colwidth.."s"
679 for i = 1, #choices do
680 choices[i] = string.format(fmt,choices[i])
682 for i = 1, #choices, cols do
683 local j = i + cols - 1
684 if j > #choices then j = #choices end
685 client:append(" "..table.concat(choices," ",i,j))