#!/usr/bin/env gjs

const GLib = imports.gi.GLib;
const Gio = imports.gi.Gio;
const System = imports.system;

const Iface = '<node><interface name="org.gnome.Shell.Screencast">\
    <method name="Screencast">\
      <arg type="s" direction="in" name="file_template"/>\
      <arg type="a{sv}" direction="in" name="options"/>\
      <arg type="b" direction="out" name="success"/>\
      <arg type="s" direction="out" name="filename_used"/>\
    </method>\
    <method name="StopScreencast">\
      <arg type="b" direction="out" name="success"/>\
    </method>\
  </interface></node>';
const Proxy = Gio.DBusProxy.makeProxyWrapper(Iface);

let proxy = new Proxy(Gio.DBus.session, 'org.gnome.Shell.Screencast', '/org/gnome/Shell/Screencast');

let framerate = 30;
let pipeline = 'vp8enc min_quantizer=13 max_quantizer=13 cpu-used=5 deadline=1000000 threads=%T ! queue ! webmmux name=mux  pulsesrc device=alsa_output.pci-0000_00_1b.0.analog-stereo.monitor ! queue ! audioconvert ! vorbisenc ! mux.';
let draw_cursor = true;

let result = proxy.ScreencastSync("audio_screencast_%d_%t.webm",
                       { 'draw-cursor': GLib.Variant.new_boolean(draw_cursor),
                         'pipeline': GLib.Variant.new_string(pipeline),
                         'framerate': GLib.Variant.new_int32(framerate)
                       });
if (!result[0])
    System.exit(1);
print ("Recording to " + result[1]);
print ("Press enter to stop");

let stdin = new Gio.UnixInputStream({'fd': 0, 'close_fd':false});
stdin.read_bytes(10, null);

let stop_result = proxy.StopScreencastSync();
if (!stop_result)
    print ("Error stopping screencast");
