from gi.repository import Gst, GObject
import time

def need_data(appsrc, need_bytes):
	global timestamp
	str = "TIME: %s:%s:%s" % (time.strftime("%H"), time.strftime("%M"), time.strftime("%S"))
	buffer = Gst.Buffer.new_wrapped(str)
	buffer.pts = timestamp
	buffer.duration = Gst.util_uint64_scale_int (1, Gst.SECOND, 1)
	timestamp += buffer.duration
	appsrc.emit("push-buffer", buffer)

def on_message_eos(bus, message):
	pipeline.set_state(Gst.State.NULL)
	print("Stream closed")

def on_message_error(bus, message):
	pipeline.set_state(Gst.State.NULL)
	err, debug = message.parse_error()
	print("Pipeline Error: %s %s" % (err, debug))


### MAIN ###

timestamp = 0

GObject.threads_init()
Gst.init(None)

pipeline = Gst.parse_launch("matroskamux name=mux ! filesink location=test.mkv name=sink videotestsrc ! queue name=videoqueue ! avenc_mpeg4 ! mux. appsrc name=appsrc caps=text/x-raw,format=utf8 stream-type=0 format=3 is-live=true ! queue name=appqueue ! kateenc category=subtitles name=kateenc ! mux.")

appsrc = pipeline.get_by_name("appsrc")
appsrc.connect("need-data", need_data)

bus = pipeline.get_bus()
bus.add_signal_watch()
bus.connect('message::eos', on_message_eos)
bus.connect('message::error', on_message_error)


loop = GObject.MainLoop()
pipeline.set_state(Gst.State.PLAYING)
loop.run()

