]> git.sesse.net Git - vlc/blob - share/lua/intf/cli.lua
765928387a7bfd5a8f03959804603776d85bd37a
[vlc] / share / lua / intf / cli.lua
1 --[==========================================================================[
2  cli.lua: CLI module for VLC
3 --[==========================================================================[
4  Copyright (C) 2007-2011 the VideoLAN team
5  $Id$
6
7  Authors: Antoine Cellerier <dionoea at videolan dot org>
8           Pierre Ynard
9
10  This program is free software; you can redistribute it and/or modify
11  it under the terms of the GNU General Public License as published by
12  the Free Software Foundation; either version 2 of the License, or
13  (at your option) any later version.
14
15  This program is distributed in the hope that it will be useful,
16  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  GNU General Public License for more details.
19
20  You should have received a copy of the GNU General Public License
21  along with this program; if not, write to the Free Software
22  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 --]==========================================================================]
24
25 description=
26 [============================================================================[
27  Command Line Interface for VLC
28
29  This is a modules/control/rc.c look alike (with a bunch of new features).
30  It also provides a VLM interface copied from the telnet interface.
31
32  Use on local term:
33     vlc -I cli
34  Use on tcp connection:
35     vlc -I cli --lua-config "cli={host='localhost:4212'}"
36  Use on telnet connection:
37     vlc -I cli --lua-config "cli={host='telnet://localhost:4212'}"
38  Use on multiple hosts (term + plain tcp port + telnet):
39     vlc -I cli --lua-config "cli={hosts={'*console','localhost:4212','telnet://localhost:5678'}}"
40
41  Note:
42     -I cli and -I luacli are aliases for -I luaintf --lua-intf cli
43
44  Configuration options settable through the --lua-config option are:
45     * hosts: A list of hosts to listen on.
46     * host: A host to listen on. (won't be used if `hosts' is set)
47     * password: The password used for telnet clients.
48  The following can be set using the --lua-config option or in the interface
49  itself using the `set' command:
50     * prompt: The prompt.
51     * welcome: The welcome message.
52     * width: The default terminal width (used to format text).
53     * autocompletion: When issuing an unknown command, print a list of
54                       possible commands to autocomplete with. (0 to disable,
55                       1 to enable).
56     * autoalias: If autocompletion returns only one possibility, use it
57                  (0 to disable, 1 to enable).
58     * flatplaylist: 0 to disable, 1 to enable.
59 ]============================================================================]
60
61 require("common")
62 skip = common.skip
63 skip2 = function(foo) return skip(skip(foo)) end
64 setarg = common.setarg
65 strip = common.strip
66
67 _ = vlc.gettext._
68 N_ = vlc.gettext.N_
69
70 --[[ Setup default environement ]]
71 env = { prompt = "> ";
72         width = 70;
73         autocompletion = 1;
74         autoalias = 1;
75         welcome = _("Command Line Interface initialized. Type `help' for help.");
76         flatplaylist = 0;
77       }
78
79 --[[ Import custom environement variables from the command line config (if possible) ]]
80 for k,v in pairs(env) do
81     if config[k] then
82         if type(env[k]) == type(config[k]) then
83             env[k] = config[k]
84             vlc.msg.dbg("set environment variable `"..k.."' to "..tostring(env[k]))
85         else
86             vlc.msg.err("environment variable `"..k.."' should be of type "..type(env[k])..". config value will be discarded.")
87         end
88     end
89 end
90
91 --[[ Command functions ]]
92 function set_env(name,client,value)
93     if value then
94         local var,val = split_input(value)
95         if val then
96             local s = string.gsub(val,"\"(.*)\"","%1")
97             if type(client.env[var])==type(1) then
98                 client.env[var] = tonumber(s)
99             else
100                 client.env[var] = s
101             end
102         else
103             client:append( tostring(client.env[var]) )
104         end
105     else
106         for e,v in common.pairs_sorted(client.env) do
107             client:append(e.."="..v)
108         end
109     end
110 end
111
112 function save_env(name,client,value)
113     env = common.table_copy(client.env)
114 end
115
116 function alias(client,value)
117     if value then
118         local var,val = split_input(value)
119         if commands[var] and type(commands[var]) ~= type("") then
120             client:append("Error: cannot use a primary command as an alias name")
121         else
122             if commands[val] then
123                 commands[var]=val
124             else
125                 client:append("Error: unknown primary command `"..val.."'.")
126             end
127         end
128     else
129         for c,v in common.pairs_sorted(commands) do
130             if type(v)==type("") then
131                 client:append(c.."="..v)
132             end
133         end
134     end
135 end
136
137 function lock(name,client)
138     if client.type == host.client_type.telnet then
139         client:switch_status( host.status.password )
140         client.buffer = ""
141     else
142         client:append("Error: the prompt can only be locked when logged in through telnet")
143     end
144 end
145
146 function logout(name,client)
147     if client.type == host.client_type.net
148     or client.type == host.client_type.telnet then
149         client:send("Bye-bye!\r\n")
150         client:del()
151     else
152         client:append("Error: Can't logout of stdin/stdout. Use quit or shutdown to close VLC.")
153     end
154 end
155
156 function shutdown(name,client)
157     client:append("Bye-bye!")
158     h:broadcast("Shutting down.\r\n")
159     vlc.msg.info("Requested shutdown.")
160     vlc.misc.quit()
161 end
162
163 function quit(name,client)
164     if client.type == host.client_type.net
165     or client.type == host.client_type.telnet then
166         logout(name,client)
167     else
168         shutdown(name,client)
169     end
170 end
171
172 function add(name,client,arg)
173     -- TODO: parse single and double quotes properly
174     local f
175     if name == "enqueue" then
176         f = vlc.playlist.enqueue
177     else
178         f = vlc.playlist.add
179     end
180     local options = {}
181     for o in string.gmatch(arg," +:([^ ]*)") do
182         table.insert(options,o)
183     end
184     arg = string.gsub(arg," +:.*$","")
185     local uri = vlc.strings.make_uri(arg)
186     f({{path=uri,options=options}})
187 end
188
189 function playlist_is_tree( client )
190     if client.env.flatplaylist == 0 then
191         return true
192     else
193         return false
194     end
195 end
196
197 function playlist(name,client,arg)
198     function playlist0(item,prefix)
199         local prefix = prefix or ""
200         if not item.flags.disabled then
201             local str = "| "..prefix..tostring(item.id).." - "..item.name
202             if item.duration > 0 then
203                 str = str.." ("..common.durationtostring(item.duration)..")"
204             end
205             if item.nb_played > 0 then
206                 str = str.." [played "..tostring(item.nb_played).." time"
207                 if item.nb_played > 1 then
208                     str = str .. "s"
209                 end
210                 str = str .. "]"
211             end
212             client:append(str)
213         end
214         if item.children then
215             for _, c in ipairs(item.children) do
216                 playlist0(c,prefix.."  ")
217             end
218         end
219     end
220     local playlist
221     local tree = playlist_is_tree(client)
222     if name == "search" then
223         playlist = vlc.playlist.search(arg or "", tree)
224     else
225         if tonumber(arg) then
226             playlist = vlc.playlist.get(tonumber(arg), tree)
227         elseif arg then
228             playlist = vlc.playlist.get(arg, tree)
229         else
230             playlist = vlc.playlist.get(nil, tree)
231         end
232     end
233     if name == "search" then
234         client:append("+----[ Search - "..(arg or "`reset'").." ]")
235     else
236         client:append("+----[ Playlist - "..playlist.name.." ]")
237     end
238     if playlist.children then
239         for _, item in ipairs(playlist.children) do
240             playlist0(item)
241         end
242     else
243         playlist0(playlist)
244     end
245     if name == "search" then
246         client:append("+----[ End of search - Use `search' to reset ]")
247     else
248         client:append("+----[ End of playlist ]")
249     end
250 end
251
252 function playlist_sort(name,client,arg)
253     if not arg then
254         client:append("Valid sort keys are: id, title, artist, genre, random, duration, album.")
255     else
256         local tree = playlist_is_tree(client)
257         vlc.playlist.sort(arg,false,tree)
258     end
259 end
260
261 function services_discovery(name,client,arg)
262     if arg then
263         if vlc.sd.is_loaded(arg) then
264             vlc.sd.remove(arg)
265             client:append(arg.." disabled.")
266         else
267             vlc.sd.add(arg)
268             client:append(arg.." enabled.")
269         end
270     else
271         local sd = vlc.sd.get_services_names()
272         client:append("+----[ Services discovery ]")
273         for n,ln in pairs(sd) do
274             local status
275             if vlc.sd.is_loaded(n) then
276                 status = "enabled"
277             else
278                 status = "disabled"
279             end
280             client:append("| "..n..": " .. ln .. " (" .. status .. ")")
281         end
282         client:append("+----[ End of services discovery ]")
283     end
284 end
285
286 function load_vlm(name, client, value)
287     if vlm == nil then
288         vlm = vlc.vlm()
289     end
290 end
291
292 function print_text(label,text)
293     return function(name,client)
294         client:append("+----[ "..label.." ]")
295         client:append "|"
296         for line in string.gmatch(text,".-\r?\n") do
297             client:append("| "..string.gsub(line,"\r?\n",""))
298         end
299         client:append "|"
300         client:append("+----[ End of "..string.lower(label).." ]")
301     end
302 end
303
304 function help(name,client,arg)
305     if arg == nil and vlm ~= nil then
306         client:append("+----[ VLM commands ]")
307         local message, vlc_err = vlm:execute_command("help")
308         vlm_message_to_string( client, message, "|" )
309     end
310
311     local width = client.env.width
312     local long = (name == "longhelp")
313     local extra = ""
314     if arg then extra = "matching `" .. arg .. "' " end
315     client:append("+----[ CLI commands "..extra.."]")
316     for i, cmd in ipairs(commands_ordered) do
317         if (cmd == "" or not commands[cmd].adv or long)
318         and (not arg or string.match(cmd,arg)) then
319             local str = "| " .. cmd
320             if cmd ~= "" then
321                 local val = commands[cmd]
322                 if val.aliases then
323                     for _,a in ipairs(val.aliases) do
324                         str = str .. ", " .. a
325                     end
326                 end
327                 if val.args then str = str .. " " .. val.args end
328                 if #str%2 == 1 then str = str .. " " end
329                 str = str .. string.rep(" .",(width-(#str+#val.help)-1)/2)
330                 str = str .. string.rep(" ",width-#str-#val.help) .. val.help
331             end
332             client:append(str)
333         end
334     end
335     client:append("+----[ end of help ]")
336 end
337
338 function input_info(name,client)
339     local item = vlc.input.item()
340     if(item == nil) then return end
341     local categories = item:info()
342     for cat, infos in pairs(categories) do
343         client:append("+----[ "..cat.." ]")
344         client:append("|")
345         for name, value in pairs(infos) do
346             client:append("| "..name..": "..value)
347         end
348         client:append("|")
349     end
350     client:append("+----[ end of stream info ]")
351 end
352
353 function stats(name,client)
354     local item = vlc.input.item()
355     if(item == nil) then return end
356     local stats_tab = item:stats()
357
358     client:append("+----[ begin of statistical info")
359     client:append("+-[Incoming]")
360     client:append("| input bytes read : "..string.format("%8.0f KiB",stats_tab["read_bytes"]/1024))
361     client:append("| input bitrate    :   "..string.format("%6.0f kb/s",stats_tab["input_bitrate"]*8000))
362     client:append("| demux bytes read : "..string.format("%8.0f KiB",stats_tab["demux_read_bytes"]/1024))
363     client:append("| demux bitrate    :   "..string.format("%6.0f kb/s",stats_tab["demux_bitrate"]*8000))
364     client:append("| demux corrupted  :    "..string.format("%5i",stats_tab["demux_corrupted"]))
365     client:append("| discontinuities  :    "..string.format("%5i",stats_tab["demux_discontinuity"]))
366     client:append("|")
367     client:append("+-[Video Decoding]")
368     client:append("| video decoded    :    "..string.format("%5i",stats_tab["decoded_video"]))
369     client:append("| frames displayed :    "..string.format("%5i",stats_tab["displayed_pictures"]))
370     client:append("| frames lost      :    "..string.format("%5i",stats_tab["lost_pictures"]))
371     client:append("|")
372     client:append("+-[Audio Decoding]")
373     client:append("| audio decoded    :    "..string.format("%5i",stats_tab["decoded_audio"]))
374     client:append("| buffers played   :    "..string.format("%5i",stats_tab["played_abuffers"]))
375     client:append("| buffers lost     :    "..string.format("%5i",stats_tab["lost_abuffers"]))
376     client:append("|")
377     client:append("+-[Streaming]")
378     client:append("| packets sent     :    "..string.format("%5i",stats_tab["sent_packets"]))
379     client:append("| bytes sent       : "..string.format("%8.0f KiB",stats_tab["sent_bytes"]/1024))
380     client:append("| sending bitrate  :   "..string.format("%6.0f kb/s",stats_tab["send_bitrate"]*8000))
381     client:append("+----[ end of statistical info ]")
382 end
383
384 function playlist_status(name,client)
385     local item = vlc.input.item()
386     if(item ~= nil) then
387         client:append( "( new input: " .. vlc.strings.decode_uri(item:uri()) .. " )" )
388     end
389     client:append( "( audio volume: " .. tostring(vlc.volume.get()) .. " )")
390     client:append( "( state " .. vlc.playlist.status() .. " )")
391 end
392
393 function is_playing(name,client)
394     if vlc.input.is_playing() then client:append "1" else client:append "0" end
395 end
396
397 function get_title(name,client)
398     local item = vlc.input.item()
399     if item then
400         client:append(item:name())
401     else
402         client:append("")
403     end
404 end
405
406 function ret_print(foo,start,stop)
407     local start = start or ""
408     local stop = stop or ""
409     return function(discard,client,...) client:append(start..tostring(foo(...))..stop) end
410 end
411
412 function get_time(var)
413     return function(name,client)
414         local input = vlc.object.input()
415         if input then
416             client:append(math.floor(vlc.var.get( input, var )))
417         else
418             client:append("")
419         end
420     end
421 end
422
423 function titlechap(name,client,value)
424     local input = vlc.object.input()
425     local var = string.gsub( name, "_.*$", "" )
426     if value then
427         vlc.var.set( input, var, value )
428     else
429         local item = vlc.var.get( input, var )
430         -- Todo: add item name conversion
431         client:append(item)
432     end
433 end
434
435 function titlechap_offset(var,offset)
436     local input = vlc.object.input()
437     vlc.var.set( input, var, vlc.var.get( input, var ) + offset )
438 end
439
440 function title_next(name,client,value)
441     titlechap_offset('title', 1)
442 end
443
444 function title_previous(name,client,value)
445     titlechap_offset('title', -1)
446 end
447
448 function chapter_next(name,client,value)
449     titlechap_offset('chapter', 1)
450 end
451
452 function chapter_previous(name,client,value)
453     titlechap_offset('chapter', -1)
454 end
455
456 function seek(name,client,value)
457     common.seek(value)
458 end
459
460 function volume(name,client,value)
461     if value then
462         common.volume(value)
463     else
464         client:append(tostring(vlc.volume.get()))
465     end
466 end
467
468 function rate(name,client,value)
469     local input = vlc.object.input()
470     if name == "rate" then
471         vlc.var.set(input, "rate", common.us_tonumber(value))
472     elseif name == "normal" then
473         vlc.var.set(input,"rate",1)
474     else
475         vlc.var.set(input,"rate-"..name,nil)
476     end
477 end
478
479 function frame(name,client)
480     vlc.var.trigger_callback(vlc.object.input(),"frame-next");
481 end
482
483 function listvalue(obj,var)
484     return function(client,value)
485         local o
486         if obj == "input" then
487             o = vlc.object.input()
488         elseif obj == "aout" then
489             o = vlc.object.aout()
490         elseif obj == "vout" then
491             o = vlc.object.vout()
492         end
493         if not o then return end
494         if value then
495             vlc.var.set( o, var, value )
496         else
497             local c = vlc.var.get( o, var )
498             local v, l = vlc.var.get_list( o, var )
499             client:append("+----[ "..var.." ]")
500             for i,val in ipairs(v) do
501                 local mark = (val==c)and " *" or ""
502                 client:append("| "..tostring(val).." - "..tostring(l[i])..mark)
503             end
504             client:append("+----[ end of "..var.." ]")
505         end
506     end
507 end
508
509 function menu(name,client,value)
510     local map = { on='show', off='hide', up='up', down='down', left='prev', right='next', ['select']='activate' }
511     if map[value] and vlc.osd.menu[map[value]] then
512         vlc.osd.menu[map[value]]()
513     else
514         client:append("Unknown menu command '"..tostring(value).."'")
515     end
516 end
517
518 function hotkey(name, client, value)
519     if not value then
520         client:append("Please specify a hotkey (ie key-quit or quit)")
521     elseif not common.hotkey(value) and not common.hotkey("key-"..value) then
522         client:append("Unknown hotkey '"..value.."'")
523     end
524 end
525
526 --[[ Declare commands, register their callback functions and provide
527      help strings here.
528      Syntax is:
529      "<command name>"; { func = <function>; [ args = "<str>"; ] help = "<str>"; [ adv = <bool>; ] [ aliases = { ["<str>";]* }; ] }
530      ]]
531 commands_ordered = {
532     { "add"; { func = add; args = "XYZ"; help = "add XYZ to playlist" } };
533     { "enqueue"; { func = add; args = "XYZ"; help = "queue XYZ to playlist" } };
534     { "playlist"; { func = playlist; help = "show items currently in playlist" } };
535     { "search"; { func = playlist; args = "[string]"; help = "search for items in playlist (or reset search)" } };
536     { "sort"; { func = playlist_sort; args = "key"; help = "sort the playlist" } };
537     { "sd"; { func = services_discovery; args = "[sd]"; help = "show services discovery or toggle" } };
538     { "play"; { func = skip2(vlc.playlist.play); help = "play stream" } };
539     { "stop"; { func = skip2(vlc.playlist.stop); help = "stop stream" } };
540     { "next"; { func = skip2(vlc.playlist.next); help = "next playlist item" } };
541     { "prev"; { func = skip2(vlc.playlist.prev); help = "previous playlist item" } };
542     { "goto"; { func = skip2(vlc.playlist.gotoitem); help = "goto item at index" ; aliases = { "gotoitem" } } };
543     { "repeat"; { func = skip2(vlc.playlist.repeat_); args = "[on|off]"; help = "toggle playlist repeat" } };
544     { "loop"; { func = skip2(vlc.playlist.loop); args = "[on|off]"; help = "toggle playlist loop" } };
545     { "random"; { func = skip2(vlc.playlist.random); args = "[on|off]"; help = "toggle playlist random" } };
546     { "clear"; { func = skip2(vlc.playlist.clear); help = "clear the playlist" } };
547     { "status"; { func = playlist_status; help = "current playlist status" } };
548     { "title"; { func = titlechap; args = "[X]"; help = "set/get title in current item" } };
549     { "title_n"; { func = title_next; help = "next title in current item" } };
550     { "title_p"; { func = title_previous; help = "previous title in current item" } };
551     { "chapter"; { func = titlechap; args = "[X]"; help = "set/get chapter in current item" } };
552     { "chapter_n"; { func = chapter_next; help = "next chapter in current item" } };
553     { "chapter_p"; { func = chapter_previous; help = "previous chapter in current item" } };
554     { "" };
555     { "seek"; { func = seek; args = "X"; help = "seek in seconds, for instance `seek 12'" } };
556     { "pause"; { func = skip2(vlc.playlist.pause); help = "toggle pause" } };
557     { "fastforward"; { func = setarg(common.hotkey,"key-jump+extrashort"); help = "set to maximum rate" } };
558     { "rewind"; { func = setarg(common.hotkey,"key-jump-extrashort"); help = "set to minimum rate" } };
559     { "faster"; { func = rate; help = "faster playing of stream" } };
560     { "slower"; { func = rate; help = "slower playing of stream" } };
561     { "normal"; { func = rate; help = "normal playing of stream" } };
562     { "rate"; { func = rate; args = "[playback rate]"; help = "set playback rate to value" } };
563     { "frame"; { func = frame; help = "play frame by frame" } };
564     { "fullscreen"; { func = skip2(vlc.video.fullscreen); args = "[on|off]"; help = "toggle fullscreen"; aliases = { "f", "F" } } };
565     { "info"; { func = input_info; help = "information about the current stream" } };
566     { "stats"; { func = stats; help = "show statistical information" } };
567     { "get_time"; { func = get_time("time"); help = "seconds elapsed since stream's beginning" } };
568     { "is_playing"; { func = is_playing; help = "1 if a stream plays, 0 otherwise" } };
569     { "get_title"; { func = get_title; help = "the title of the current stream" } };
570     { "get_length"; { func = get_time("length"); help = "the length of the current stream" } };
571     { "" };
572     { "volume"; { func = volume; args = "[X]"; help = "set/get audio volume" } };
573     { "volup"; { func = ret_print(vlc.volume.up,"( audio volume: "," )"); args = "[X]"; help = "raise audio volume X steps" } };
574     { "voldown"; { func = ret_print(vlc.volume.down,"( audio volume: "," )"); args = "[X]"; help = "lower audio volume X steps" } };
575     -- { "adev"; { func = skip(listvalue("aout","audio-device")); args = "[X]"; help = "set/get audio device" } };
576     { "achan"; { func = skip(listvalue("aout","stereo-mode")); args = "[X]"; help = "set/get stereo audio output mode" } };
577     { "atrack"; { func = skip(listvalue("input","audio-es")); args = "[X]"; help = "set/get audio track" } };
578     { "vtrack"; { func = skip(listvalue("input","video-es")); args = "[X]"; help = "set/get video track" } };
579     { "vratio"; { func = skip(listvalue("vout","aspect-ratio")); args = "[X]"; help = "set/get video aspect ratio" } };
580     { "vcrop"; { func = skip(listvalue("vout","crop")); args = "[X]"; help = "set/get video crop"; aliases = { "crop" } } };
581     { "vzoom"; { func = skip(listvalue("vout","zoom")); args = "[X]"; help = "set/get video zoom"; aliases = { "zoom" } } };
582     { "vdeinterlace"; { func = skip(listvalue("vout","deinterlace")); args = "[X]"; help = "set/get video deinterlace" } };
583     { "vdeinterlace_mode"; { func = skip(listvalue("vout","deinterlace-mode")); args = "[X]"; help = "set/get video deinterlace mode" } };
584     { "snapshot"; { func = common.snapshot; help = "take video snapshot" } };
585     { "strack"; { func = skip(listvalue("input","spu-es")); args = "[X]"; help = "set/get subtitles track" } };
586     { "hotkey"; { func = hotkey; args = "[hotkey name]"; help = "simulate hotkey press"; adv = true; aliases = { "key" } } };
587     { "menu"; { func = menu; args = "[on|off|up|down|left|right|select]"; help = "use menu"; adv = true } };
588     { "" };
589     { "vlm"; { func = load_vlm; help = "load the VLM" } };
590     { "set"; { func = set_env; args = "[var [value]]"; help = "set/get env var"; adv = true } };
591     { "save_env"; { func = save_env; help = "save env vars (for future clients)"; adv = true } };
592     { "alias"; { func = skip(alias); args = "[cmd]"; help = "set/get command aliases"; adv = true } };
593     { "description"; { func = print_text("Description",description); help = "describe this module" } };
594     { "license"; { func = print_text("License message",vlc.misc.license()); help = "print VLC's license message"; adv = true } };
595     { "help"; { func = help; args = "[pattern]"; help = "a help message"; aliases = { "?" } } };
596     { "longhelp"; { func = help; args = "[pattern]"; help = "a longer help message" } };
597     { "lock"; { func = lock; help = "lock the telnet prompt" } };
598     { "logout"; { func = logout; help = "exit (if in a socket connection)" } };
599     { "quit"; { func = quit; help = "quit VLC (or logout if in a socket connection)" } };
600     { "shutdown"; { func = shutdown; help = "shutdown VLC" } };
601     }
602
603 commands = {}
604 for i, cmd in ipairs( commands_ordered ) do
605     if #cmd == 2 then
606         commands[cmd[1]]=cmd[2]
607         if cmd[2].aliases then
608             for _,a in ipairs(cmd[2].aliases) do
609                 commands[a]=cmd[1]
610             end
611         end
612     end
613     commands_ordered[i]=cmd[1]
614 end
615 --[[ From now on commands_ordered is a list of the different command names
616      and commands is a associative array indexed by the command name. ]]
617
618 -- Compute the column width used when printing a the autocompletion list
619 env.colwidth = 0
620 for c,_ in pairs(commands) do
621     if #c > env.colwidth then env.colwidth = #c end
622 end
623 env.coldwidth = env.colwidth + 1
624
625 --[[ Utils ]]
626 function split_input(input)
627     local input = strip(input)
628     local s = string.find(input," ")
629     if s then
630         return string.sub(input,0,s-1), strip(string.sub(input,s))
631     else
632         return input
633     end
634 end
635
636 function vlm_message_to_string(client,message,prefix)
637     local prefix = prefix or ""
638     if message.value then
639         client:append(prefix .. message.name .. " : " .. message.value)
640     else
641         client:append(prefix .. message.name)
642     end
643     if message.children then
644         for i,c in ipairs(message.children) do
645             vlm_message_to_string(client,c,prefix.."    ")
646         end
647     end
648 end
649
650 --[[ Command dispatch ]]
651 function call_command(cmd,client,arg)
652     if type(commands[cmd]) == type("") then
653         cmd = commands[cmd]
654     end
655     local ok, msg
656     if arg ~= nil then
657         ok, msg = pcall( commands[cmd].func, cmd, client, arg )
658     else
659         ok, msg = pcall( commands[cmd].func, cmd, client )
660     end
661     if not ok then
662         local a = arg and " "..arg or ""
663         client:append("Error in `"..cmd..a.."' ".. msg)
664     end
665 end
666
667 function call_vlm_command(cmd,client,arg)
668     if vlm == nil then
669         return -1
670     end
671     if arg ~= nil then
672         cmd = cmd.." "..arg
673     end
674     local message, vlc_err = vlm:execute_command( cmd )
675     -- the VLM doesn't let us know if the command exists,
676     -- so we need this ugly hack
677     if vlc_err ~= 0 and message.value == "Unknown VLM command" then
678         return vlc_err
679     end
680     vlm_message_to_string( client, message )
681     return 0
682 end
683
684 function call_libvlc_command(cmd,client,arg)
685     local ok, vlcerr = pcall( vlc.var.libvlc_command, cmd, arg )
686     if not ok then
687         local a = arg and " "..arg or ""
688         client:append("Error in `"..cmd..a.."' ".. vlcerr) -- when pcall fails, the 2nd arg is the error message.
689     end
690     return vlcerr
691 end
692
693 function call_object_command(cmd,client,arg)
694     local var, val
695     if arg ~= nil then
696         var, val = split_input(arg)
697     end
698     local ok, vlcmsg, vlcerr = pcall( vlc.var.command, cmd, var, val )
699     if not ok then
700         local v = var and " "..var or ""
701         local v2 = val and " "..val or ""
702         client:append("Error in `"..cmd..v..v2.."' ".. vlcmsg) -- when pcall fails the 2nd arg is the error message
703     end
704     if vlcmsg ~= "" then
705         client:append(vlcmsg)
706     end
707     return vlcerr
708 end
709
710 function client_command( client )
711     local cmd,arg = split_input(client.buffer)
712     client.buffer = ""
713
714     if commands[cmd] then
715         call_command(cmd,client,arg)
716     elseif string.sub(cmd,0,1)=='@'
717     and call_object_command(string.sub(cmd,2,#cmd),client,arg) == 0 then
718         --
719     elseif call_vlm_command(cmd,client,arg) == 0 then
720         --
721     elseif client.type == host.client_type.stdio
722     and call_libvlc_command(cmd,client,arg) == 0 then
723         --
724     else
725         local choices = {}
726         if client.env.autocompletion ~= 0 then
727             for v,_ in common.pairs_sorted(commands) do
728                 if string.sub(v,0,#cmd)==cmd then
729                     table.insert(choices, v)
730                 end
731             end
732         end
733         if #choices == 1 and client.env.autoalias ~= 0 then
734             -- client:append("Aliasing to \""..choices[1].."\".")
735             cmd = choices[1]
736             call_command(cmd,client,arg)
737         else
738             client:append("Unknown command `"..cmd.."'. Type `help' for help.")
739             if #choices ~= 0 then
740                 client:append("Possible choices are:")
741                 local cols = math.floor(client.env.width/(client.env.colwidth+1))
742                 local fmt = "%-"..client.env.colwidth.."s"
743                 for i = 1, #choices do
744                     choices[i] = string.format(fmt,choices[i])
745                 end
746                 for i = 1, #choices, cols do
747                     local j = i + cols - 1
748                     if j > #choices then j = #choices end
749                     client:append("  "..table.concat(choices," ",i,j))
750                 end
751             end
752         end
753     end
754 end
755
756 --[[ Some telnet command special characters ]]
757 WILL = "\251" -- Indicates the desire to begin performing, or confirmation that you are now performing, the indicated option.
758 WONT = "\252" -- Indicates the refusal to perform, or continue performing, the indicated option.
759 DO   = "\253" -- Indicates the request that the other party perform, or confirmation that you are expecting the other party to perform, the indicated option.
760 DONT = "\254" -- Indicates the demand that the other party stop performing, or confirmation that you are no longer expecting the other party to perform, the indicated option.
761 IAC  = "\255" -- Interpret as command
762
763 ECHO = "\001"
764
765 function telnet_commands( client )
766     -- remove telnet command replies from the client's data
767     client.buffer = string.gsub( client.buffer, IAC.."["..DO..DONT..WILL..WONT.."].", "" )
768 end
769
770 --[[ Client status change callbacks ]]
771 function on_password( client )
772     client.env = common.table_copy( env )
773     if client.type == host.client_type.telnet then
774         client:send( "Password: " ..IAC..WILL..ECHO )
775     else
776         if client.env.welcome ~= "" then
777             client:send( client.env.welcome .. "\r\n")
778         end
779         client:switch_status( host.status.read )
780     end
781 end
782 -- Print prompt when switching a client's status to `read'
783 function on_read( client )
784     client:send( client.env.prompt )
785 end
786 function on_write( client )
787 end
788
789 --[[ Setup host ]]
790 require("host")
791 h = host.host()
792
793 h.status_callbacks[host.status.password] = on_password
794 h.status_callbacks[host.status.read] = on_read
795 h.status_callbacks[host.status.write] = on_write
796
797 h:listen( config.hosts or config.host or "*console" )
798 password = config.password or "admin"
799
800 --[[ The main loop ]]
801 while not vlc.misc.should_die() do
802     local write, read = h:accept_and_select()
803
804     for _, client in pairs(write) do
805         local len = client:send()
806         client.buffer = string.sub(client.buffer,len+1)
807         if client.buffer == "" then client:switch_status(host.status.read) end
808     end
809
810     for _, client in pairs(read) do
811         local input = client:recv(1000)
812
813         if input == nil -- the telnet client program has left
814             or ((client.type == host.client_type.net
815                  or client.type == host.client_type.telnet)
816                 and input == "\004") then
817             -- Caught a ^D
818             client.cmds = "quit\n"
819         else
820             client.cmds = client.cmds .. input
821         end
822
823         client.buffer = ""
824         -- split the command at the first '\n'
825         while string.find(client.cmds, "\n") do
826             -- save the buffer to send to the client
827             local saved_buffer = client.buffer
828
829             -- get the next command
830             local index = string.find(client.cmds, "\n")
831             client.buffer = strip(string.sub(client.cmds, 0, index - 1))
832             client.cmds = string.sub(client.cmds, index + 1)
833
834             -- Remove telnet commands from the command line
835             if client.type == host.client_type.telnet then
836                 telnet_commands( client )
837             end
838
839             -- Run the command
840             if client.status == host.status.password then
841                 if client.buffer == password then
842                     client:send( IAC..WONT..ECHO.."\r\nWelcome, Master\r\n" )
843                     client.buffer = ""
844                     client:switch_status( host.status.write )
845                 elseif client.buffer == "quit" then
846                     client_command( client )
847                 else
848                     client:send( "\r\nWrong password\r\nPassword: " )
849                     client.buffer = ""
850                 end
851             else
852                 client:switch_status( host.status.write )
853                 client_command( client )
854             end
855             client.buffer = saved_buffer .. client.buffer
856         end
857     end
858 end
859
860 --[[ Clean up ]]
861 vlm = nil