#!/bin/bash

YOUTUBE_STREAM_KEY=Kane.Root.qzmc-deax-c89a-1htc
TWITCH_STREAM_KEY=live_74998353_jJXuFOm62scAeVACKeTktCI5Vz9RL3

if [ $# -lt 1 ]
then
    echo "Usage : ./$0 (youtube|twitch|filename) [url]"
    exit 1
fi

# audio
AUDIO_RATE=44100
THREADS="4"
CBR="128k"              # audio bitrate

RATE=48000

# video
QUALITY="ultrafast"
VIDEO_CBR="1000k"
GOP=20
GOPMIN=30
VRATE=24

# stream info
CHROMIUM_BIN='chromium-browser'
CHROMIUM_OPTS='--use-fake-ui-for-media-stream --use-fake-device-for-media-stream -start-maximized --app'
CHROMIUM_URL='https://meet.jitsi.org/test'
#CHROMIUM_URL='http://t.karchnu.fr/autre/test-video.html'

if [ $# -gt 1 ] ; then
    CHROMIUM_URL=$2
fi

#RESOLUTION="426x240"
#RESOLUTION="1024x768"
RESOLUTION="1280x720"
JACK_APP_NAME=myrecord

case "$1" in

    youtube)
        echo "stream Youtube"
        STREAM_KEY=$YOUTUBE_STREAM_KEY
        URL_STREAM='rtmp://a.rtmp.youtube.com/live2'
        OUTPUT="${URL_STREAM}/${STREAM_KEY}"
        ;;

    twitch)
        echo "stream Twitch"
        STREAM_KEY=$TWITCH_STREAM_KEY
        URL_STREAM='rtmp://live-lhr.justin.tv/app'
        OUTPUT="${URL_STREAM}/${STREAM_KEY}"
        ;;

    *) 
        OUTPUT_FILE="$1"
        echo "output in the file $OUTPUT_FILE"
        OUTPUT="${OUTPUT_FILE}"
        ;;
esac

function var_display() {

    echo "to play : $CHROMIUM_BIN $CHROMIUM_OPTS $CHROMIUM_URL"
    echo "or play : mplayer Big_Buck_Bunny.mp4"
    echo "OUTPUT : $OUTPUT"

}

function record() {

    # audio has to be optimized (buffer problems ?)
    avconv -y -f jack -i ${JACK_APP_NAME} \
        -f x11grab -s ${RESOLUTION} -i ${DISPLAY}.0+0,0 -r $VRATE \
        -vcodec libx264 -s ${RESOLUTION} -preset $QUALITY \
        -b:v $VIDEO_CBR -minrate $VIDEO_CBR -maxrate $VIDEO_CBR \
        -pix_fmt yuv420p \
        -g $GOP -keyint_min $GOPMIN \
        -acodec libmp3lame -ar 44100 -threads ${THREADS} -aq 2 \
        -bufsize 16m -minrate $CBR -maxrate $CBR -ac 2 \
        -f flv "${OUTPUT}" &

}

function play_smth() {

    if [ $# -gt 1 ] ; then
        $CHROMIUM_BIN $CHROMIUM_OPTS $CHROMIUM_URL &
    else
        mplayer Big_Buck_Bunny.mp4
    fi
}

# start jackd
jackd -r -d dummy 2>/dev/null 1>/dev/null &

sleep 1

# create two jack interfaces (capture and playback)
# with the names cloop and ploop
# capture loop is capturing the alsa playback interface
# see /etc/asound.conf

alsa_in -j cloop -dcloop -r $RATE 2>/dev/null 1>/dev/null &
alsa_out -j ploop -dploop -r $RATE 2>/dev/null 1>/dev/null &

# start the X virtual Frame Buffer
Xvfb -screen 0 ${RESOLUTION}x${VRATE} 1>/dev/null 2>/dev/null &
export DISPLAY=:0

sleep 2

record
play_smth

sleep 1

# connect the jack interfaces (capture loop and audio stream recording)
jack_connect cloop:capture_1 ${JACK_APP_NAME}:input_1
jack_connect cloop:capture_2 ${JACK_APP_NAME}:input_2

exit 0
