/* Copyright 2011-2013 Yorba Foundation
 * 
 * This is a Vala-rewrite of GStreamer snapshot example. Adapted from earlier 
 * work from Wim Taymans.
 *
 * This software is licensed under the GNU LGPL (version 2.1 or later).
 * See the COPYING file in this distribution.
 */

// Shotwell Thumbnailer takes in a video file and returns a thumbnail to stdout.  This is
// a replacement for totem-video-thumbnailer
class ShotwellThumbnailer {
    const string caps_string = """video/x-raw,format=RGB,pixel-aspect-ratio=1/1""";
    
    public static int main(string[] args) {
        string descr;
        Gdk.Pixbuf pixbuf;
        
        Gst.init(ref args);
        
        if (args.length != 2) {
            stdout.printf("usage: %s [filename]\n Writes video thumbnail to stdout\n", args[0]);
            return 1;
        }
        
        descr = "filesrc location=\"%s\" ! decodebin ! videoconvert ! videoscale ! ".printf(args[1]) +
            "appsink name=sink caps=\"%s\"".printf(caps_string);

        string ls_stdout;
        string ls_stderr;
        int ls_status;

        try {
            uint8[]? pngdata;
            Process.spawn_command_line_sync("totem-video-thumbnailer -s 360 " + args[1] + " /tmp/tmp.L0v1S70AiM.png", out ls_stdout, out ls_stderr, out ls_status);
            stderr.puts(ls_stdout);
            stderr.printf("stderr:\n");
            stderr.puts(ls_stderr);
            stderr.printf ("status: %d\n", ls_status);

            pixbuf = new Gdk.Pixbuf.from_file("/tmp/tmp.L0v1S70AiM.png");
                
            // Save the pixbuf.
            pixbuf.save_to_buffer(out pngdata, "png");
            stdout.write(pngdata);
            
        } catch (Error e) {
            stderr.printf(e.message);
            return 2;
        }
        
        return 0;
    }
}

