#!/usr/bin/python
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4

from __future__ import division
from optparse import OptionParser
from os.path import splitext
import os
import sys

vcodecs = {
    'theora': 'theoraenc',
    'dirac': 'schroenc',
}
acodecs = {
    'vorbis': 'vorbisenc',
    'speex': 'speexenc',
    'flac': 'flacenc',
}
containers = {
    'ogg': 'oggmux',
    'matroska': 'matroskamux',
}

def gst2ogg(inputfile, outputfile, options):
    print inputfile, outputfile, options

    #codec
    videocodec = options.videocodec
    if videocodec not in vcodecs:
        videocodec='theora'
    audiocodec = options.audiocodec
    if audiocodec not in acodecs:
        audiocodec='vorbis'

    #crop5
    crop = ""
    if options.cropleft:
        crop += " left=%d" % int(options.cropleft)
    if options.cropright:
        crop += " right=%d" % int(options.cropright)
    if options.croptop:
        crop += " top=%d" % int(options.croptop)
    if options.cropbottom:
        crop += " bottom=%d" % int(options.cropbottom)
    if crop:
        crop = "videocrop " + crop

    #size
    videoscale_caps = None
    if options.width or options.height:
        videoscale_caps = "video/x-raw-yuv,width=%d,height=%d" % (options.width, options.height)
        #after videoscale ! 

    #framerate
    videorate_caps = None
    if options.framerate:
        framerate = options.framerate
        if ':' in framerate or '/' in framerate:
            framerate = "(fraction)%s" % framerate.replace(':', '/')
        else:
            framerate = float(framerate)
        videorate_caps = "video/x-raw-yuv,framerate=%s" % framerate
        #after videorate ! 

    #samplerate
    #audioconvert ! audio/x-raw-float ! audioresample !  audio/x-raw-float,rate=22050,channels=1
    audioresample_caps = None
    if options.samplerate or options.channels:
        audioresample_caps = "audio/x-raw-float"
        if options.samplerate:
            audioresample_caps += ",rate=%d" % options.samplerate
        if options.channels:
            audioresample_caps += ",channels=%d" % options.channels

    print videocodec, audiocodec

def encode():
    pipeline = '''filesrc name=input ! decodebin name=decode decode. ! 
                  queue max-size-buffers=100 max-size-time=0 max-size-bytes=0 !
                  ffmpegcolorspace $scale ! $framerate theoraenc name=videoenc !
                  oggmux name=mux ! filesink name=output
                  decode. ! queue max-size-buffers=100 max-size-bytes=0 max-size-time=0  !
                  audioconvert ! vorbisenc name=audioenc ! mux.'''
    pipeline = gst.parse(pipeline)
#how to do the aspect foobar?
#audioconvert
#deinterlace
#use gst element: deinterlace (but how to detect if input is interlaced?
#crop
# user gst element: videocrop
#gamma
# use gst element: gamma
#brightness, saturation, contrast
# use gst element: videobalance


def main():
    parser = OptionParser()
    parser.add_option('-P', '--pid', dest='pid', help='write pid to file')
    parser.add_option('-o', '--output', dest='output', help='')
    parser.add_option('-k', '--skeleton', dest='skeleton', help='')
    parser.add_option('', '--no-skeleton', dest='no_skeleton', help='')
    #parser.add_option('-f', '--format', dest='format', help='this is ignored')
    parser.add_option('-F', '--framerate', dest='framerate', help='')
    parser.add_option('-x', '--widht', dest='width', help='')
    parser.add_option('-y', '--height', dest='height', help='')
    parser.add_option('', '--xy', dest='xy', help='')
    parser.add_option('-v', '--videoquality', dest='videoquality', help='')
    parser.add_option('-V', '--videorate', dest='videorate', help='')
    parser.add_option('-a', '--audioquality', dest='audioquality', help='')
    parser.add_option('-A', '--audiorate', dest='audiorate', help='')
    parser.add_option('-S', '--sharpness', dest='sharpness', help='')
    parser.add_option('-K', '--keyint', dest='keyint', help='')
    parser.add_option('-d', '--deinterlace', dest='deinterlace', help='')
    parser.add_option('-H', '--samplerate', dest='samplerate', help='')
    parser.add_option('-c', '--channels', dest='channels', help='')
    parser.add_option('-G', '--gamma', dest='gamma', help='')
    parser.add_option('-B', '--brightness', dest='brightness', help='')
    parser.add_option('-Z', '--saturation', dest='saturation', help='')
    parser.add_option('-C', '--contrast', dest='contrast', help='')
    parser.add_option('', '--nosound', dest='nosound', help='')
    parser.add_option('', '--noaudio', dest='noaudio', help='')
    parser.add_option('', '--novideo', dest='novideo', help='')
    #parser.add_option('', '--vhook', dest='vhook', help='') #unlikely, needs other gst replacement
    parser.add_option('', '--aspect', dest='aspect', help='')
    parser.add_option('-p', '--preset', dest='preset', help='')

    parser.add_option('-N', '--nice', dest='nice', help='')

    parser.add_option('', '--croptop', dest='croptop', help='')
    parser.add_option('', '--cropbottom', dest='cropbottom', help='')
    parser.add_option('', '--cropright', dest='cropright', help='')
    parser.add_option('', '--cropleft', dest='cropleft', help='')

    #parser.add_option('', '--inputfps', dest='inputfps', help='') #unlikely

    parser.add_option('', '--audiostream', dest='audiostream', help='')
    #FIXME; how does that work in gst

    #needs kate plugin for gstreamer, would work in mkv right now
    '''
    parser.add_option('', '--subtitles', dest='subtitles', help='')
    parser.add_option('', '--subtitles-encoding', dest='subtitles-encoding', help='')
    parser.add_option('', '--subtitles-ignore-non-utf8', dest='subtitles-ignore-non-utf8', help='')
    parser.add_option('', '--subtitles-language', dest='subtitles-language', help='')
    parser.add_option('', '--subtitles-category', dest='subtitles-category', help='')
    '''

    parser.add_option('-s', '--starttime', dest='starttime', help='')
    parser.add_option('-e', '--endtime', dest='endtime', help='')
    #parser.add_option('', '--sync', dest='sync', help='this will be ignored')
    parser.add_option('', '--optimize', dest='optimize', help='')
    parser.add_option('', '--speedlevel', dest='speedlevel', help='')

    parser.add_option('', '--frontend', dest='frontend', help='')

    #metadata needs changes to gst theoraenc / vorbisenc?
    '''
    parser.add_option('', '--artist', dest='artist', help='')
    parser.add_option('', '--title', dest='title', help='')
    parser.add_option('', '--date', dest='date', help='')
    parser.add_option('', '--location', dest='location', help='')
    parser.add_option('', '--organization', dest='organization', help='')
    parser.add_option('', '--copyright', dest='copyright', help='')
    parser.add_option('', '--license', dest='license', help='')
    parser.add_option('', '--contact', dest='contact', help='')
    parser.add_option('', '--source-hash', dest='source-hash', help='')
    '''

    parser.add_option('', '--vcodec', dest='videocodec', help='Select video codec. options: %s' % ', '.join(sorted(vcodecs.keys())))
    parser.add_option('', '--acodec', dest='audiocodec', help='Select audio codec. options: %s' % ', '.join(sorted(acodecs.keys())))
    #parser.add_option('', '--container', dest='container', help='Select output media container. options: %s' % ', '.join(sorted(containers.keys())))

    (opts, args) = parser.parse_args()
    print opts, args
    if not args:
      parser.print_help()
      sys.exit(1)
    inputfile = args[0]
    outputfile = opts.output
    if not outputfile:
        outputfile = "%s.ogv" % splitext(inputfile)[0]
    
    print "%s -> %s" % (inputfile, outputfile)
    if not inputfile:
        parser.print_help()
        sys.exit(1)

    gst2ogg(inputfile, outputfile, opts)

if __name__ == '__main__':
  main()

