]> git.sesse.net Git - vlc/blob - share/lua/intf/rc.lua
Misc lua interface changes.
[vlc] / share / lua / intf / rc.lua
1 --[==========================================================================[
2  rc.lua: remote control module for VLC
3 --[==========================================================================[
4  Copyright (C) 2007-2009 the VideoLAN team
5  $Id$
6
7  Authors: Antoine Cellerier <dionoea at videolan dot org>
8
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.
13
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.
18
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 --]==========================================================================]
23
24 description=
25 [============================================================================[
26  Remote control interface for VLC
27
28  This is a modules/control/rc.c look alike (with a bunch of new features)
29
30  Use on local term:
31     vlc -I rc
32  Use on tcp connection:
33     vlc -I rc --lua-config "rc={host='localhost:4212'}"
34  Use on multiple hosts (term + 2 tcp ports):
35     vlc -I rc --lua-config "rc={hosts={'*console','localhost:4212','localhost:5678'}}"
36
37  Note:
38     -I rc and -I luarc are aliases for -I lua --lua-intf rc
39
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     * eval: Add eval command to evaluate lua expressions. Set to any value to
44             enable.
45  The following can be set using the --lua-config option or in the interface
46  itself using the `set' command:
47     * prompt: The prompt.
48     * welcome: The welcome message.
49     * width: The default terminal width (used to format text).
50     * autocompletion: When issuing an unknown command, print a list of
51                       possible commands to autocomplete with. (0 to disable,
52                       1 to enable).
53     * autoalias: If autocompletion returns only one possibility, use it
54                  (0 to disable, 1 to enable).
55     * flatplaylist: 0 to disable, 1 to enable.
56 ]============================================================================]
57
58 require("common")
59 skip = common.skip
60 skip2 = function(foo) return skip(skip(foo)) end
61 setarg = common.setarg
62 strip = common.strip
63
64 --[[ Setup default environement ]]
65 env = { prompt = "> ";
66         width = 70;
67         autocompletion = 1;
68         autoalias = 1;
69         welcome = "Remote control interface initialized. Type `help' for help.";
70         flatplaylist = 0;
71       }
72
73 --[[ Import custom environement variables from the command line config (if possible) ]]
74 for k,v in pairs(env) do
75     if config[k] then
76         if type(env[k]) == type(config[k]) then
77             env[k] = config[k]
78             vlc.msg.dbg("set environement variable `"..k.."' to "..tostring(env[k]))
79         else
80             vlc.msg.err("environement variable `"..k.."' should be of type "..type(env[k])..". config value will be discarded.")
81         end
82     end
83 end
84
85 --[[ Command functions ]]
86 function set_env(name,client,value)
87     if value then
88         local var,val = split_input(value)
89         if val then
90             local s = string.gsub(val,"\"(.*)\"","%1")
91             if type(client.env[var])==type(1) then
92                 client.env[var] = tonumber(s)
93             else
94                 client.env[var] = s
95             end
96         else
97             client:append( tostring(client.env[var]) )
98         end
99     else
100         for e,v in common.pairs_sorted(client.env) do
101             client:append(e.."="..v)
102         end
103     end
104 end
105
106 function save_env(name,client,value)
107     env = common.table_copy(client.env)
108 end
109
110 function alias(client,value)
111     if value then
112         local var,val = split_input(value)
113         if commands[var] and type(commands[var]) ~= type("") then
114             client:append("Error: cannot use a primary command as an alias name")
115         else
116             if commands[val] then
117                 commands[var]=val
118             else
119                 client:append("Error: unknown primary command `"..val.."'.")
120             end
121         end
122     else
123         for c,v in common.pairs_sorted(commands) do
124             if type(v)==type("") then
125                 client:append(c.."="..v)
126             end
127         end
128     end
129 end
130
131 function fixme(name,client)
132     client:append( "FIXME: unimplemented command `"..name.."'." )
133 end
134
135 function logout(name,client)
136     if client.type == host.client_type.net then
137         client:send("Bye-bye!")
138         client:del()
139     else
140         client:append("Error: Can't logout of stdin/stdout. Use quit or shutdown to close VLC.")
141     end
142 end
143
144 function shutdown(name,client)
145     client:append("Bye-bye!")
146     h:broadcast("Shutting down.")
147     vlc.msg.info("Requested shutdown.")
148     vlc.misc.quit()
149 end
150
151 function quit(name,client)
152     if client.type == host.client_type.net then
153         logout(name,client)
154     else
155         shutdown(name,client)
156     end
157 end
158
159 function add(name,client,arg)
160     -- TODO: par single and double quotes properly
161     local f
162     if name == "enqueue" then
163         f = vlc.playlist.enqueue
164     else
165         f = vlc.playlist.add
166     end
167     local options = {}
168     for o in string.gmatch(arg," +:([^ ]*)") do
169         table.insert(options,o)
170     end
171     arg = string.gsub(arg," +:.*$","")
172     f({{path=arg,options=options}})
173 end
174
175 function playlist_is_tree( client )
176     if client.env.flatplaylist == 0 then
177         return true
178     else
179         return false
180     end
181 end
182
183 function playlist(name,client,arg)
184     function playlist0(item,prefix)
185         local prefix = prefix or ""
186         if not item.flags.disabled then
187             local str = "| "..prefix..tostring(item.id).." - "..item.name
188             if item.duration > 0 then
189                 str = str.." ("..common.durationtostring(item.duration)..")"
190             end
191             if item.nb_played > 0 then
192                 str = str.." [played "..tostring(item.nb_played).." time"
193                 if item.nb_played > 1 then
194                     str = str .. "s"
195                 end
196                 str = str .. "]"
197             end
198             client:append(str)
199         end
200         if item.children then
201             for _, c in ipairs(item.children) do
202                 playlist0(c,prefix.."  ")
203             end
204         end
205     end
206     local playlist
207     local tree = playlist_is_tree(client)
208     if name == "search" then
209         playlist = vlc.playlist.search(arg or "", tree)
210     else
211         if tonumber(arg) then
212             playlist = vlc.playlist.get(tonumber(arg), tree)
213         elseif arg then
214             playlist = vlc.playlist.get(arg, tree)
215         else
216             playlist = vlc.playlist.get(nil, tree)
217         end
218     end
219     if name == "search" then
220         client:append("+----[ Search - "..(arg or "`reset'").." ]")
221     else
222         client:append("+----[ Playlist - "..playlist.name.." ]")
223     end
224     if playlist.children then
225         for _, item in ipairs(playlist.children) do
226             playlist0(item)
227         end
228     else
229         playlist0(playlist)
230     end
231     if name == "search" then
232         client:append("+----[ End of search - Use `search' to reset ]")
233     else
234         client:append("+----[ End of playlist ]")
235     end
236 end
237
238 function playlist_sort(name,client,arg)
239     if not arg then
240         client:append("Valid sort keys are: id, title, artist, genre, random, duration, album.")
241     else
242         local tree = playlist_is_tree(client)
243         vlc.playlist.sort(arg,false,tree)
244     end
245 end
246
247 function services_discovery(name,client,arg)
248     if arg then
249         if vlc.sd.is_loaded(arg) then
250             vlc.sd.remove(arg)
251             client:append(arg.." disabled.")
252         else
253             vlc.sd.add(arg)
254             client:append(arg.." enabled.")
255         end
256     else
257         local sd = vlc.sd.get_services_names()
258         client:append("+----[ Services discovery ]")
259         for n,ln in pairs(sd) do
260             local status
261             if vlc.sd.is_loaded(n) then
262                 status = "enabled"
263             else
264                 status = "disabled"
265             end
266             client:append("| "..n..": " .. ln .. " (" .. status .. ")")
267         end
268         client:append("+----[ End of services discovery ]")
269     end
270 end
271
272 function print_text(label,text)
273     return function(name,client)
274         client:append("+----[ "..label.." ]")
275         client:append "|"
276         for line in string.gmatch(text,".-\r?\n") do
277             client:append("| "..string.gsub(line,"\r?\n",""))
278         end
279         client:append "|"
280         client:append("+----[ End of "..string.lower(label).." ]")
281     end
282 end
283
284 function help(name,client,arg)
285     local width = client.env.width
286     local long = (name == "longhelp")
287     local extra = ""
288     if arg then extra = "matching `" .. arg .. "' " end
289     client:append("+----[ Remote control commands "..extra.."]")
290     for i, cmd in ipairs(commands_ordered) do
291         if (cmd == "" or not commands[cmd].adv or long)
292         and (not arg or string.match(cmd,arg)) then
293             local str = "| " .. cmd
294             if cmd ~= "" then
295                 local val = commands[cmd]
296                 if val.aliases then
297                     for _,a in ipairs(val.aliases) do
298                         str = str .. ", " .. a
299                     end
300                 end
301                 if val.args then str = str .. " " .. val.args end
302                 if #str%2 == 1 then str = str .. " " end
303                 str = str .. string.rep(" .",(width-(#str+#val.help)-1)/2)
304                 str = str .. string.rep(" ",width-#str-#val.help) .. val.help
305             end
306             client:append(str)
307         end
308     end
309     client:append("+----[ end of help ]")
310 end
311
312 function input_info(name,client)
313     local categories = vlc.input.info()
314     for cat, infos in pairs(categories) do
315         client:append("+----[ "..cat.." ]")
316         client:append("|")
317         for name, value in pairs(infos) do
318             client:append("| "..name..": "..value)
319         end
320         client:append("|")
321     end
322     client:append("+----[ end of stream info ]")
323 end
324
325 function stats(name,client)
326     local stats_tab = vlc.input.stats()
327
328     client:append("+----[ begin of statistical info")
329     client:append("+-[Incoming]")
330     client:append("| input bytes read : "..string.format("%8.0f kB",stats_tab["read_bytes"]/1000))
331     client:append("| input bitrate    :   "..string.format("%6.0f bB/s",stats_tab["input_bitrate"]*8000))
332     client:append("| demux bytes read : "..string.format("%8.0f kB",stats_tab["demux_read_bytes"]/1000))
333     client:append("| demux bitrate    :   "..string.format("%6.0f kB/s",stats_tab["demux_bitrate"]*8000))
334     client:append("| demux corrupted  :    "..string.format("%5i",stats_tab["demux_corrupted"]))
335     client:append("| discontinuities  :    "..string.format("%5i",stats_tab["demux_discontinuity"]))
336     client:append("|")
337     client:append("+-[Video Decoding]")
338     client:append("| video decoded    :    "..string.format("%5i",stats_tab["decoded_video"]))
339     client:append("| frames displayed :    "..string.format("%5i",stats_tab["displayed_pictures"]))
340     client:append("| frames lost      :    "..string.format("%5i",stats_tab["lost_pictures"]))
341     client:append("|")
342     client:append("+-[Audio Decoding]")
343     client:append("| audio decoded    :    "..string.format("%5i",stats_tab["decoded_audio"]))
344     client:append("| buffers played   :    "..string.format("%5i",stats_tab["played_abuffers"]))
345     client:append("| buffers lost     :    "..string.format("%5i",stats_tab["lost_abuffers"]))
346     client:append("|")
347     client:append("+-[Streaming]")
348     client:append("| packets sent     :    "..string.format("%5i",stats_tab["sent_packets"]))
349     client:append("| bytes sent       : "..string.format("%8.0f kB",stats_tab["sent_bytes"]/1000))
350     client:append("| sending bitrate  :   "..string.format("%6.0f kb/s",stats_tab["send_bitrate"]*8000))
351     client:append("+----[ end of statistical info ]")
352 end
353
354 function playlist_status(name,client)
355     client:append( "( new input: " .. "FIXME" .. " )" )
356     client:append( "( audio volume: " .. tostring(vlc.volume.get()) .. " )")
357     client:append( "( state " .. vlc.playlist.status() .. " )")
358 end
359
360 function is_playing(name,client)
361     if vlc.input.is_playing() then client:append "1" else client:append "0" end
362 end
363
364 function ret_print(foo,start,stop)
365     local start = start or ""
366     local stop = stop or ""
367     return function(discard,client,...) client:append(start..tostring(foo(...))..stop) end
368 end
369
370 function get_time(var)
371     return function(name,client)
372         local input = vlc.object.input()
373         client:append(math.floor(vlc.var.get( input, var )))
374     end
375 end
376
377 function titlechap(name,client,value)
378     local input = vlc.object.input()
379     local var = string.gsub( name, "_.*$", "" )
380     if value then
381         vlc.var.set( input, var, value )
382     else
383         local item = vlc.var.get( input, var )
384         -- Todo: add item name conversion
385         client:append(item)
386     end
387 end
388 function titlechap_offset(client,offset)
389     return function(name,value)
390         local input = vlc.object.input()
391         local var = string.gsub( name, "_.*$", "" )
392         vlc.var.set( input, var, vlc.var.get( input, var )+offset )
393     end
394 end
395
396 function seek(name,client,value)
397     common.seek(value)
398 end
399
400 function volume(name,client,value)
401     if value then
402         common.volume(value)
403     else
404         client:append(tostring(vlc.volume.get()))
405     end
406 end
407
408 function rate(name,client,value)
409     local input = vlc.object.input()
410     if name == "rate" then
411         vlc.var.set(input, "rate", tonumber(value))
412     elseif name == "normal" then
413         vlc.var.set(input,"rate",1)
414     else
415         vlc.var.set(input,"rate-"..name,nil)
416     end
417 end
418
419 function frame(name,client)
420     vlc.var.trigger_callback(vlc.object.input(),"frame-next");
421 end
422
423 function listvalue(obj,var)
424     return function(client,value)
425         local o = vlc.object.find(nil,obj,"anywhere")
426         if not o then return end
427         if value then
428             vlc.var.set( o, var, value )
429         else
430             local c = vlc.var.get( o, var )
431             local v, l = vlc.var.get_list( o, var )
432             client:append("+----[ "..var.." ]")
433             for i,val in ipairs(v) do
434                 local mark = (val==c)and " *" or ""
435                 client:append("| "..tostring(val).." - "..tostring(l[i])..mark)
436             end
437             client:append("+----[ end of "..var.." ]")
438         end
439     end
440 end
441
442 function menu(name,client,value)
443     local map = { on='show', off='hide', up='up', down='down', left='prev', right='next', ['select']='activate' }
444     if map[value] and vlc.osd.menu[map[value]] then
445         vlc.osd.menu[map[value]]()
446     else
447         client:append("Unknown menu command '"..tostring(value).."'")
448     end
449 end
450
451 function hotkey(name, client, value)
452     if not value then
453         client:append("Please specify a hotkey (ie key-quit or quit)")
454     elseif not common.hotkey(value) and not common.hotkey("key-"..value) then
455         client:append("Unknown hotkey '"..value.."'")
456     end
457 end
458
459 function eval(client,val)
460     client:append(tostring(loadstring("return "..val)()))
461 end
462
463 --[[ Declare commands, register their callback functions and provide
464      help strings here.
465      Syntax is:
466      "<command name>"; { func = <function>; [ args = "<str>"; ] help = "<str>"; [ adv = <bool>; ] [ aliases = { ["<str>";]* }; ] }
467      ]]
468 commands_ordered = {
469     { "add"; { func = add; args = "XYZ"; help = "add XYZ to playlist" } };
470     { "enqueue"; { func = add; args = "XYZ"; help = "queue XYZ to playlist" } };
471     { "playlist"; { func = playlist; help = "show items currently in playlist" } };
472     { "search"; { func = playlist; args = "[string]"; help = "search for items in playlist (or reset search)" } };
473     { "sort"; { func = playlist_sort; args = "key"; help = "sort the playlist" } };
474     { "sd"; { func = services_discovery; args = "[sd]"; help = "show services discovery or toggle" } };
475     { "play"; { func = skip2(vlc.playlist.play); help = "play stream" } };
476     { "stop"; { func = skip2(vlc.playlist.stop); help = "stop stream" } };
477     { "next"; { func = skip2(vlc.playlist.next); help = "next playlist item" } };
478     { "prev"; { func = skip2(vlc.playlist.prev); help = "previous playlist item" } };
479     { "goto"; { func = skip2(vlc.playlist.goto); help = "goto item at index" } };
480     { "repeat"; { func = skip2(vlc.playlist.repeat_); args = "[on|off]"; help = "toggle playlist repeat" } };
481     { "loop"; { func = skip2(vlc.playlist.loop); args = "[on|off]"; help = "toggle playlist loop" } };
482     { "random"; { func = skip2(vlc.playlist.random); args = "[on|off]"; help = "toggle playlist random" } };
483     { "clear"; { func = skip2(vlc.playlist.clear); help = "clear the playlist" } };
484     { "status"; { func = playlist_status; help = "current playlist status" } };
485     { "title"; { func = titlechap; args = "[X]"; help = "set/get title in current item" } };
486     { "title_n"; { func = titlechap_offset(1); help = "next title in current item" } };
487     { "title_p"; { func = titlechap_offset(-1); help = "previous title in current item" } };
488     { "chapter"; { func = titlechap; args = "[X]"; help = "set/get chapter in current item" } };
489     { "chapter_n"; { func = titlechap_offset(1); help = "next chapter in current item" } };
490     { "chapter_p"; { func = titlechap_offset(-1); help = "previous chapter in current item" } };
491     { "" };
492     { "seek"; { func = seek; args = "X"; help = "seek in seconds, for instance `seek 12'" } };
493     { "pause"; { func = setarg(common.hotkey,"key-play-pause"); help = "toggle pause" } };
494     { "fastforward"; { func = setarg(common.hotkey,"key-jump+extrashort"); help = "set to maximum rate" } };
495     { "rewind"; { func = setarg(common.hotkey,"key-jump-extrashort"); help = "set to minimum rate" } };
496     { "faster"; { func = rate; help = "faster playing of stream" } };
497     { "slower"; { func = rate; help = "slower playing of stream" } };
498     { "normal"; { func = rate; help = "normal playing of stream" } };
499     { "rate"; { func = rate; args = "[playback rate]"; help = "set playback rate to value" } };
500     { "frame"; { func = frame; help = "play frame by frame" } };
501     { "fullscreen"; { func = skip2(vlc.video.fullscreen); args = "[on|off]"; help = "toggle fullscreen"; aliases = { "f", "F" } } };
502     { "info"; { func = input_info; help = "information about the current stream" } };
503     { "stats"; { func = stats; help = "show statistical information" } };
504     { "get_time"; { func = get_time("time"); help = "seconds elapsed since stream's beginning" } };
505     { "is_playing"; { func = is_playing; help = "1 if a stream plays, 0 otherwise" } };
506     { "get_title"; { func = ret_print(vlc.input.get_title); help = "the title of the current stream" } };
507     { "get_length"; { func = get_time("length"); help = "the length of the current stream" } };
508     { "" };
509     { "volume"; { func = volume; args = "[X]"; help = "set/get audio volume" } };
510     { "volup"; { func = ret_print(vlc.volume.up,"( audio volume: "," )"); args = "[X]"; help = "raise audio volume X steps" } };
511     { "voldown"; { func = ret_print(vlc.volume.down,"( audio volume: "," )"); args = "[X]"; help = "lower audio volume X steps" } };
512     { "adev"; { func = skip(listvalue("aout","audio-device")); args = "[X]"; help = "set/get audio device" } };
513     { "achan"; { func = skip(listvalue("aout","audio-channels")); args = "[X]"; help = "set/get audio channels" } };
514     { "atrack"; { func = skip(listvalue("input","audio-es")); args = "[X]"; help = "set/get audio track" } };
515     { "vtrack"; { func = skip(listvalue("input","video-es")); args = "[X]"; help = "set/get video track" } };
516     { "vratio"; { func = skip(listvalue("vout","aspect-ratio")); args = "[X]"; help = "set/get video aspect ratio" } };
517     { "vcrop"; { func = skip(listvalue("vout","crop")); args = "[X]"; help = "set/get video crop"; aliases = { "crop" } } };
518     { "vzoom"; { func = skip(listvalue("vout","zoom")); args = "[X]"; help = "set/get video zoom"; aliases = { "zoom" } } };
519     { "snapshot"; { func = common.snapshot; help = "take video snapshot" } };
520     { "strack"; { func = skip(listvalue("input","spu-es")); args = "[X]"; help = "set/get subtitles track" } };
521     { "hotkey"; { func = hotkey; args = "[hotkey name]"; help = "simulate hotkey press"; adv = true; aliases = { "key" } } };
522     { "menu"; { func = menu; args = "[on|off|up|down|left|right|select]"; help = "use menu"; adv = true } };
523     { "" };
524     { "set"; { func = set_env; args = "[var [value]]"; help = "set/get env var"; adv = true } };
525     { "save_env"; { func = save_env; help = "save env vars (for future clients)"; adv = true } };
526     { "alias"; { func = skip(alias); args = "[cmd]"; help = "set/get command aliases"; adv = true } };
527     { "description"; { func = print_text("Description",description); help = "describe this module" } };
528     { "license"; { func = print_text("License message",vlc.misc.license()); help = "print VLC's license message"; adv = true } };
529     { "help"; { func = help; args = "[pattern]"; help = "a help message"; aliases = { "?" } } };
530     { "longhelp"; { func = help; args = "[pattern]"; help = "a longer help message" } };
531     { "logout"; { func = logout; help = "exit (if in a socket connection)" } };
532     { "quit"; { func = quit; help = "quit VLC (or logout if in a socket connection)" } };
533     { "shutdown"; { func = shutdown; help = "shutdown VLC" } };
534     }
535
536 if config.eval then
537     commands_ordered[#commands_ordered] = { "eval"; { func = skip(eval); help = "eval some lua (*debug*)"; adv =true } }
538 end
539
540 commands = {}
541 for i, cmd in ipairs( commands_ordered ) do
542     if #cmd == 2 then
543         commands[cmd[1]]=cmd[2]
544         if cmd[2].aliases then
545             for _,a in ipairs(cmd[2].aliases) do
546                 commands[a]=cmd[1]
547             end
548         end
549     end
550     commands_ordered[i]=cmd[1]
551 end
552 --[[ From now on commands_ordered is a list of the different command names
553      and commands is a associative array indexed by the command name. ]]
554
555 -- Compute the column width used when printing a the autocompletion list
556 env.colwidth = 0
557 for c,_ in pairs(commands) do
558     if #c > env.colwidth then env.colwidth = #c end
559 end
560 env.coldwidth = env.colwidth + 1
561
562 -- Count unimplemented functions
563 do
564     local count = 0
565     local list = "("
566     for c,v in pairs(commands) do
567         if v.func == fixme then
568             count = count + 1
569             if count ~= 1 then
570                 list = list..","
571             end
572             list = list..c
573         end
574     end
575     list = list..")"
576     if count ~= 0 and env.welcome and env.welcome ~= "" then
577         env.welcome = env.welcome .. "\r\nWarning: "..count.." functions are still unimplemented "..list.."."
578     end
579 end
580
581 --[[ Utils ]]
582 function split_input(input)
583     local input = strip(input)
584     local s = string.find(input," ")
585     if s then
586         return string.sub(input,0,s-1), strip(string.sub(input,s))
587     else
588         return input
589     end
590 end
591
592 function call_command(cmd,client,arg)
593     if type(commands[cmd]) == type("") then
594         cmd = commands[cmd]
595     end
596     local ok, msg
597     if arg ~= nil then
598         ok, msg = pcall( commands[cmd].func, cmd, client, arg )
599     else
600         ok, msg = pcall( commands[cmd].func, cmd, client )
601     end
602     if not ok then
603         local a = arg or ""
604         if a ~= "" then a = " " .. a end
605         client:append("Error in `"..cmd..a.."' ".. msg)
606     end
607 end
608
609 function call_libvlc_command(cmd,client,arg)
610     local ok, vlcerr, vlcmsg = pcall( vlc.var.libvlc_command, cmd, arg )
611     if not ok then
612         local a = arg or ""
613         if a ~= "" then a = " " .. a end
614         client:append("Error in `"..cmd..a.."' ".. vlcerr) -- when pcall fails, the 2nd arg is the error message.
615     end
616     return vlcerr
617 end
618
619 function call_object_command(cmd,client,arg)
620     local var, val = split_input(arg)
621     local ok, vlcmsg, vlcerr, vlcerrmsg = pcall( vlc.var.command, cmd, var, val )
622     if not ok then
623         client:append("Error in `"..cmd.." "..var.." "..val.."' ".. vlcmsg) -- when pcall fails the 2nd arg is the error message
624     end
625     if vlcmsg ~= "" then
626         client:append(vlcmsg)
627     end
628     return vlcerr
629 end
630
631 --[[ Setup host ]]
632 require("host")
633 h = host.host()
634 -- No auth
635 h.status_callbacks[host.status.password] = function(client)
636     client.env = common.table_copy( env )
637     if client.env.welcome ~= "" then
638         client:send( client.env.welcome .. "\r\n")
639     end
640     client:switch_status(host.status.read)
641 end
642 -- Print prompt when switching a client's status to `read'
643 h.status_callbacks[host.status.read] = function(client)
644     client:send( client.env.prompt )
645 end
646
647 h:listen( config.hosts or config.host or "*console" )
648
649 --[[ The main loop ]]
650 while not vlc.misc.should_die() do
651     h:accept()
652     local write, read = h:select(0.1)
653
654     for _, client in pairs(write) do
655         local len = client:send()
656         client.buffer = string.sub(client.buffer,len+1)
657         if client.buffer == "" then client:switch_status(host.status.read) end
658     end
659
660     for _, client in pairs(read) do
661         local input = client:recv(1000)
662         local done = false
663         if string.match(input,"\n$") then
664             client.buffer = string.gsub(client.buffer..input,"\r?\n$","")
665             done = true
666         elseif client.buffer == ""
667            and ((client.type == host.client_type.stdio and input == "")
668            or  (client.type == host.client_type.net and input == "\004")) then
669             -- Caught a ^D
670             client.buffer = "quit"
671             done = true
672         else
673             client.buffer = client.buffer .. input
674         end
675         if done then
676             local cmd,arg = split_input(client.buffer)
677             client.buffer = ""
678             client:switch_status(host.status.write)
679             if commands[cmd] then
680                 call_command(cmd,client,arg)
681             elseif string.sub(cmd,0,1)=='@'
682             and call_object_command(string.sub(cmd,2,#cmd),client,arg) == 0 then
683                 --
684             elseif client.type == host.client_type.stdio
685             and call_libvlc_command(cmd,client,arg) == 0 then
686                 --
687             else
688                 local choices = {}
689                 if client.env.autocompletion ~= 0 then
690                     for v,_ in common.pairs_sorted(commands) do
691                         if string.sub(v,0,#cmd)==cmd then
692                             table.insert(choices, v)
693                         end
694                     end
695                 end
696                 if #choices == 1 and client.env.autoalias ~= 0 then
697                     -- client:append("Aliasing to \""..choices[1].."\".")
698                     cmd = choices[1]
699                     call_command(cmd,client,arg)
700                 else
701                     client:append("Unknown command `"..cmd.."'. Type `help' for help.")
702                     if #choices ~= 0 then
703                         client:append("Possible choices are:")
704                         local cols = math.floor(client.env.width/(client.env.colwidth+1))
705                         local fmt = "%-"..client.env.colwidth.."s"
706                         for i = 1, #choices do
707                             choices[i] = string.format(fmt,choices[i])
708                         end
709                         for i = 1, #choices, cols do
710                             local j = i + cols - 1
711                             if j > #choices then j = #choices end
712                             client:append("  "..table.concat(choices," ",i,j))
713                         end
714                     end
715                 end
716             end
717         end
718     end
719 end