Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/glive.py
blob: 0747e86b365b9c8d30b3f21e6afce04269c03102 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
#Copyright (c) 2008, Media Modifications Ltd.

#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:

#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.

#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.

import os
from gettext import gettext as _
import time

import gi
gi.require_version('Gst', '1.0')
from gi.repository import GdkPixbuf
from gi.repository import GObject
from gi.repository import Gst
from gi.repository import GstVideo

from sugar3.activity.activity import get_bundle_path
import logging

from instance import Instance
import constants
import utils

logger = logging.getLogger('glive')

OGG_TRAITS = {
        0: { 'width': 160, 'height': 120, 'quality': 16 },
        1: { 'width': 400, 'height': 300, 'quality': 16 } }

class Glive:
    PHOTO_MODE_PHOTO = 0
    PHOTO_MODE_AUDIO = 1

    def __init__(self, activity_obj, model):
        
        self.activity = activity_obj
        self.model = model
        self._eos_cb = None
        self._has_camera = False
        self._can_limit_framerate = False
        self._playing = False
        self._pic_exposure_open = False
        self._thumb_exposure_open = False
        self._photo_mode = self.PHOTO_MODE_PHOTO

        self._audio_transcode_handler = None
        self._transcode_id = None
        self._video_transcode_handler = None
        self._thumb_handoff_handler = None

        self._audio_pixbuf = None

        self._detect_camera()

        self._pipeline = Gst.Pipeline()
        self._create_photobin()
        self._create_audiobin()
        self._create_videobin()
        self._create_xbin()
        self._create_pipeline()

        self._thumb_pipes = []
        self._mux_pipes = []

        bus = self._pipeline.get_bus()
        
        bus.add_signal_watch()
        bus.connect('message', self._bus_message_handler)
        
    def _detect_camera(self):
        
        v4l2src = Gst.ElementFactory.make('v4l2src', 'v4l2src')
        
        if v4l2src.props.device_name is None:
            return

        self._has_camera = True

        # Figure out if we can place a framerate limit on the v4l2 element,
        # which in theory will make it all the way down to the hardware.
        # ideally, we should be able to do this by checking caps. However, I
        # can't find a way to do this (at this time, XO-1 cafe camera driver
        # doesn't support framerate changes, but gstreamer caps suggest
        # otherwise)
        pipeline = Gst.Pipeline()
        caps = Gst.Caps.from_string('video/x-raw-yuv,framerate=10/1')
        fsink = Gst.ElementFactory.make('fakesink', 'fakesink')
        pipeline.add(v4l2src)
        # FIXME: TypeError: argument dest: Expected Gst.Element, but got gi.repository.Gst.Caps
        #pipeline.add(caps)
        pipeline.add(fsink)
        v4l2src.link(fsink)
        self._can_limit_framerate = pipeline.set_state(Gst.State.PAUSED) != Gst.StateChangeReturn.FAILURE
        pipeline.set_state(Gst.State.NULL)

    def get_has_camera(self):
        
        return self._has_camera

    def _create_photobin(self):
        
        queue = Gst.ElementFactory.make("queue", "pbqueue")
        queue.set_property("leaky", True)
        queue.set_property("max-size-buffers", 1)

        colorspace = Gst.ElementFactory.make("videoconvert", "pbcolorspace")
        jpeg = Gst.ElementFactory.make("jpegenc", "pbjpeg")

        sink = Gst.ElementFactory.make("fakesink", "pbsink")
        sink.connect("handoff", self._photo_handoff)
        sink.set_property("signal-handoffs", True)

        self._photobin = Gst.Bin()
        self._photobin.add(queue)
        self._photobin.add(colorspace)
        self._photobin.add(jpeg)
        self._photobin.add(sink)

        queue.link(colorspace)
        colorspace.link(jpeg)
        jpeg.link(sink)

        pad = queue.get_static_pad("sink")
        self._photobin.add_pad(Gst.GhostPad.new("sink", pad))

    def _create_audiobin(self):
        
        src = Gst.ElementFactory.make("alsasrc", "absrc")

        # attempt to use direct access to the 0,0 device, solving some A/V
        # sync issues
        src.set_property("device", "plughw:0,0")
        hwdev_available = src.set_state(Gst.State.PAUSED) != Gst.StateChangeReturn.FAILURE
        src.set_state(Gst.State.NULL)
        
        if not hwdev_available:
            src.set_property("device", "default")

        srccaps = Gst.Caps.from_string("audio/x-raw-int,rate=16000,channels=1,depth=16")

        # guarantee perfect stream, important for A/V sync
        rate = Gst.ElementFactory.make("audiorate", 'audiorate')

        # without a buffer here, gstreamer struggles at the start of the
        # recording and then the A/V sync is bad for the whole video
        # (possibly a gstreamer/ALSA bug -- even if it gets caught up, it
        # should be able to resync without problem)
        queue = Gst.ElementFactory.make("queue", "audioqueue")
        queue.set_property("leaky", True) # prefer fresh data
        queue.set_property("max-size-time", 5000000000) # 5 seconds
        queue.set_property("max-size-buffers", 500)
        queue.connect("overrun", self._log_queue_overrun)

        enc = Gst.ElementFactory.make("wavenc", "abenc")

        sink = Gst.ElementFactory.make("filesink", "absink")
        sink.set_property("location", os.path.join(Instance.instancePath, "output.wav"))

        self._audiobin = Gst.Bin()
        self._audiobin.add(src)
        self._audiobin.add(rate)
        self._audiobin.add(queue)
        self._audiobin.add(enc)
        self._audiobin.add(sink)

        rate.link(rate)
        rate.link(queue)
        queue.link(enc)
        enc.link(sink)

    def _create_videobin(self):
        
        queue = Gst.ElementFactory.make("queue", "videoqueue")
        queue.set_property("max-size-time", 5000000000) # 5 seconds
        queue.set_property("max-size-bytes", 33554432) # 32mb
        queue.connect("overrun", self._log_queue_overrun)

        scale = Gst.ElementFactory.make("videoscale", "vbscale")

        scalecapsfilter = Gst.ElementFactory.make("capsfilter", "scalecaps")

        scalecaps = Gst.Caps.from_string('video/x-raw-yuv,width=160,height=120')
        scalecapsfilter.set_property("caps", scalecaps)

        colorspace = Gst.ElementFactory.make("videoconvert", "vbcolorspace")

        enc = Gst.ElementFactory.make("theoraenc", "vbenc")
        enc.set_property("quality", 16)

        mux = Gst.ElementFactory.make("oggmux", "vbmux")

        sink = Gst.ElementFactory.make("filesink", "vbfile")
        sink.set_property("location", os.path.join(Instance.instancePath, "output.ogg"))

        self._videobin = Gst.Bin()
        self._videobin.add(queue)
        self._videobin.add(scale)
        self._videobin.add(scalecapsfilter)
        self._videobin.add(colorspace)
        self._videobin.add(enc)
        self._videobin.add(mux)
        self._videobin.add(sink)

        queue.link(scale)
        scale.link_pads(None, scalecapsfilter, "sink")
        scalecapsfilter.link_pads("src", colorspace, None)
        colorspace.link(enc)
        enc.link(mux)
        mux.link(sink)

        pad = queue.get_static_pad("sink")
        self._videobin.add_pad(Gst.GhostPad.new("sink", pad))

    def _create_xbin(self):
        
        scale = Gst.ElementFactory.make("videoscale", 'videoscale')
        cspace = Gst.ElementFactory.make("videoconvert", 'videoconvert')
        xsink = Gst.ElementFactory.make("ximagesink", "xsink")
        xsink.set_property("force-aspect-ratio", True)

        # http://thread.gmane.org/gmane.comp.video.gstreamer.devel/29644
        xsink.set_property("sync", False)

        self._xbin = Gst.Bin()
        self._xbin.add(scale)
        self._xbin.add(cspace)
        self._xbin.add(xsink)
        
        scale.link(cspace)
        cspace.link(xsink)

        pad = scale.get_static_pad("sink")
        self._xbin.add_pad(Gst.GhostPad.new("sink", pad))

    def _config_videobin(self, quality, width, height):
        
        vbenc = self._videobin.get_by_name("vbenc")
        vbenc.set_property("quality", 16)
        scaps = self._videobin.get_by_name("scalecaps")
        scaps.set_property("caps", Gst.Caps.from_string("video/x-raw-yuv,width=%d,height=%d" % (width, height)))

    def _create_pipeline(self):
        
        if not self._has_camera:
            return

        src = Gst.ElementFactory.make("v4l2src", "camsrc")
        
        try:
            # old gst-plugins-good does not have this property
            src.set_property("queue-size", 2)
            
        except:
            pass

        # if possible, it is important to place the framerate limit directly
        # on the v4l2src so that it gets communicated all the way down to the
        # camera level
        
        if self._can_limit_framerate:
            srccaps = Gst.Caps.from_string('video/x-raw-yuv,framerate=10/1')
            
        else:
            srccaps = Gst.Caps.from_string('video/x-raw-yuv')

        # we attempt to limit the framerate on the v4l2src directly, but we
        # can't trust this: perhaps we are falling behind in our capture,
        # or maybe the kernel driver doesn't provide the exact framerate.
        # the videorate element guarantees a perfect framerate and is important
        # for A/V sync because OGG does not store timestamps, it just stores
        # the FPS value.
        rate = Gst.ElementFactory.make("videorate", 'videorate')
        ratecaps = Gst.Caps.from_string('video/x-raw-yuv,framerate=10/1')

        tee = Gst.ElementFactory.make("tee", "tee")
        queue = Gst.ElementFactory.make("queue", "dispqueue")

        # prefer fresh frames
        queue.set_property("leaky", True)
        queue.set_property("max-size-buffers", 2)

        self._pipeline.add(src)
        self._pipeline.add(rate)
        self._pipeline.add(tee)
        self._pipeline.add(queue)
        src.link(rate)
        # FIXME: TypeError: argument dest: Expected Gst.Element, but got gi.repository.Gst.Caps
        #rate.link(srccaps)
        rate.link(tee)
        #tee.link(ratecaps)
        tee.link(queue)

        self._xvsink = Gst.ElementFactory.make("xvimagesink", "xsink")
        self._xv_available = self._xvsink.set_state(Gst.State.PAUSED) != Gst.StateChangeReturn.FAILURE
        self._xvsink.set_state(Gst.State.NULL)

        # http://thread.gmane.org/gmane.comp.video.gstreamer.devel/29644
        self._xvsink.set_property("sync", False)

        self._xvsink.set_property("force-aspect-ratio", True)

    def _log_queue_overrun(self, queue):
        
        cbuffers = queue.get_property("current-level-buffers")
        cbytes = queue.get_property("current-level-bytes")
        ctime = queue.get_property("current-level-time")
        logger.error("Buffer overrun in %s (%d buffers, %d bytes, %d time)"
            % (queue.get_name(), cbuffers, cbytes, ctime))
 
    def _thumb_element(self, name):
        
        return self._thumb_pipes[-1].get_by_name(name)

    def is_using_xv(self):
        
        return self._pipeline.get_by_name("xsink") == self._xvsink

    def _configure_xv(self):
        
        if self.is_using_xv():
            # nothing to do, Xv already configured
            return self._xvsink

        queue = self._pipeline.get_by_name("dispqueue")
        
        if self._pipeline.get_by_name("xbin"):
            # X sink is configured, so remove it
            queue.unlink(self._xbin)
            self._pipeline.remove(self._xbin)

        self._pipeline.add(self._xvsink)
        queue.link(self._xvsink)
        
        return self._xvsink

    def _configure_x(self):
        
        if self._pipeline.get_by_name("xbin") == self._xbin:
            # nothing to do, X already configured
            return self._xbin.get_by_name("xsink")

        queue = self._pipeline.get_by_name("dispqueue")
        xvsink = self._pipeline.get_by_name("xsink")

        if xvsink:
            # Xv sink is configured, so remove it
            queue.unlink(xvsink)
            self._pipeline.remove(xvsink)

        self._pipeline.add(self._xbin)
        queue.link(self._xbin)
        
        return self._xbin.get_by_name("xsink")
    
    def play(self, use_xv=True):
        
        if self._get_state() == Gst.State.PLAYING:
            return

        if self._has_camera:
            
            if use_xv and self._xv_available:
                xsink = self._configure_xv()
                
            else:
                xsink = self._configure_x()

            # X overlay must be set every time, it seems to forget when you stop
            # the pipeline.
            self.activity.set_glive_sink(xsink)

        self._pipeline.set_state(Gst.State.PLAYING)
        self._playing = True

    def pause(self):
        
        self._pipeline.set_state(Gst.State.PAUSED)
        self._playing = False

    def stop(self):
        
        self._pipeline.set_state(Gst.State.NULL)
        self._playing = False

    def is_playing(self):
        
        return self._playing

    def _get_state(self):
        
        return self._pipeline.get_state(0)[1]

    def stop_recording_audio(self):
        # We should be able to simply pause and remove the audiobin, but
        # this seems to cause a gstreamer segfault. So we stop the whole
        # pipeline while manipulating it.
        # http://dev.laptop.org/ticket/10183
        self._pipeline.set_state(Gst.State.NULL)
        self.model.shutter_sound()
        self._pipeline.remove(self._audiobin)

        audio_path = os.path.join(Instance.instancePath, "output.wav")
        if not os.path.exists(audio_path) or os.path.getsize(audio_path) <= 0:
            # FIXME: inform model of failure?
            return

        if self._audio_pixbuf:
            self.model.still_ready(self._audio_pixbuf)

        line = 'filesrc location=' + audio_path + ' name=audioFilesrc ! wavparse name=audioWavparse ! audioconvert name=audioAudioconvert ! vorbisenc name=audioVorbisenc ! oggmux name=audioOggmux ! filesink name=audioFilesink'
        audioline = gst.parse_launch(line)

        taglist = self._get_tags(constants.TYPE_AUDIO)

        if self._audio_pixbuf:
            pixbuf_b64 = utils.getStringFromPixbuf(self._audio_pixbuf)
            taglist[Gst.TAG_EXTENDED_COMMENT] = "coverart=" + pixbuf_b64

        vorbis_enc = audioline.get_by_name('audioVorbisenc')
        vorbis_enc.merge_tags(taglist, Gst.TAG_MERGE_REPLACE_ALL)

        audioFilesink = audioline.get_by_name('audioFilesink')
        audioOggFilepath = os.path.join(Instance.instancePath, "output.ogg")
        audioFilesink.set_property("location", audioOggFilepath)

        audioBus = audioline.get_bus()
        audioBus.add_signal_watch()
        self._audio_transcode_handler = audioBus.connect('message', self._onMuxedAudioMessageCb, audioline)
        self._transcode_id = GObject.timeout_add(200, self._transcodeUpdateCb, audioline)
        audioline.set_state(Gst.State.PLAYING)

    def _get_tags(self, type):
        
        tl = Gst.TagList()
        tl[Gst.TAG_ARTIST] = self.model.get_nickname()
        tl[Gst.TAG_COMMENT] = "olpc"
        #this is unfortunately, unreliable
        #record.Record.log.debug("self.ca.metadata['title']->" + str(self.ca.metadata['title']) )
        tl[Gst.TAG_ALBUM] = "olpc" #self.ca.metadata['title']
        tl[Gst.TAG_DATE] = utils.getDateString(int(time.time()))
        stringType = constants.MEDIA_INFO[type]['istr']
        
        # Translators: photo by photographer, e.g. "Photo by Mary"
        tl[Gst.TAG_TITLE] = _('%(type)s by %(name)s') % {'type': stringType,
                'name': self.model.get_nickname()}
        return tl

    def _take_photo(self, photo_mode):
        
        if self._pic_exposure_open:
            return

        self._photo_mode = photo_mode
        self._pic_exposure_open = True
        pad = self._photobin.get_static_pad("sink")
        self._pipeline.add(self._photobin)
        self._photobin.set_state(Gst.State.PLAYING)
        self._pipeline.get_by_name("tee").link(self._photobin)

    def take_photo(self):
        
        if self._has_camera:
            self._take_photo(self.PHOTO_MODE_PHOTO)

    def _photo_handoff(self, fsink, buffer, pad, user_data=None):
        
        if not self._pic_exposure_open:
            return

        pad = self._photobin.get_static_pad("sink")
        self._pipeline.get_by_name("tee").unlink(self._photobin)
        self._pipeline.remove(self._photobin)

        self._pic_exposure_open = False
        #pic = GdkPixbuf.PixbufLoader.new_with_mime_type("image/jpeg")
        # FIXME: TypeError: Must be sequence, not Buffer
        #pic.write( buffer )
        #pic.close()
        #pixBuf = pic.get_pixbuf()
        #del pic

        #self.save_photo(pixBuf)

    def save_photo(self, pixbuf):
        
        if self._photo_mode == self.PHOTO_MODE_AUDIO:
            self._audio_pixbuf = pixbuf
            
        else:
            self.model.save_photo(pixbuf)

    def record_video(self, quality):
        
        if not self._has_camera:
            return

        self._ogg_quality = quality
        self._config_videobin(OGG_TRAITS[quality]['quality'],
            OGG_TRAITS[quality]['width'],
            OGG_TRAITS[quality]['height'])

        # If we use pad blocking and adjust the pipeline on-the-fly, the
        # resultant video has bad A/V sync :(
        # If we pause the pipeline while adjusting it, the A/V sync is better
        # but not perfect :(
        # so we stop the whole thing while reconfiguring to get the best results
        self._pipeline.set_state(Gst.State.NULL)
        self._pipeline.add(self._videobin)
        self._pipeline.get_by_name("tee").link(self._videobin)
        self._pipeline.add(self._audiobin)
        self.play()

    def record_audio(self):
        
        if self._has_camera:
            self._audio_pixbuf = None
            self._take_photo(self.PHOTO_MODE_AUDIO)

        # we should be able to add the audiobin on the fly, but unfortunately
        # this results in several seconds of silence being added at the start
        # of the recording. So we stop the whole pipeline while adjusting it.
        # SL#2040
        self._pipeline.set_state(Gst.State.NULL)
        self._pipeline.add(self._audiobin)
        self.play()

    def stop_recording_video(self):
        
        if not self._has_camera:
            return

        # We stop the pipeline while we are adjusting the pipeline to stop
        # recording because if we do it on-the-fly, the following video live
        # feed to the screen becomes several seconds delayed. Weird!
        # FIXME: retest on F11
        # FIXME: could this be the result of audio shortening problems?
        self._eos_cb = self._video_eos
        self._pipeline.get_by_name('camsrc').send_event(Gst.Event.new_eos())
        self._audiobin.get_by_name('absrc').send_event(Gst.Event.new_eos())

    def _video_eos(self):
        
        self._pipeline.set_state(Gst.State.NULL)
        self._pipeline.get_by_name("tee").unlink(self._videobin)
        self._pipeline.remove(self._videobin)
        self._pipeline.remove(self._audiobin)

        self.model.shutter_sound()

        if len(self._thumb_pipes) > 0:
            thumbline = self._thumb_pipes[-1]
            thumbline.get_by_name('thumb_fakesink').disconnect(self._thumb_handoff_handler)

        ogg_path = os.path.join(Instance.instancePath, "output.ogg")
        
        if not os.path.exists(ogg_path) or os.path.getsize(ogg_path) <= 0:
            # FIXME: inform model of failure?
            return

        line = 'filesrc location=' + ogg_path + ' name=thumbFilesrc ! oggdemux name=thumbOggdemux ! theoradec name=thumbTheoradec ! tee name=thumb_tee ! queue name=thumb_queue ! ffmpegcolorspace name=thumbFfmpegcolorspace ! jpegenc name=thumbJPegenc ! fakesink name=thumb_fakesink'
        thumbline = Gst.parse_launch(line)
        thumb_queue = thumbline.get_by_name('thumb_queue')
        thumb_queue.set_property("leaky", True)
        thumb_queue.set_property("max-size-buffers", 1)
        thumb_tee = thumbline.get_by_name('thumb_tee')
        thumb_fakesink = thumbline.get_by_name('thumb_fakesink')
        self._thumb_handoff_handler = thumb_fakesink.connect("handoff", self.copyThumbPic)
        thumb_fakesink.set_property("signal-handoffs", True)
        self._thumb_pipes.append(thumbline)
        self._thumb_exposure_open = True
        thumbline.set_state(Gst.State.PLAYING)

    def copyThumbPic(self, fsink, buffer, pad, user_data=None):
        
        if not self._thumb_exposure_open:
            return

        self._thumb_exposure_open = False
        loader = GdkPibuf.PixbufLoader.new_with_mime_type("image/jpeg")
        loader.write(buffer)
        loader.close()
        self.thumbBuf = loader.get_pixbuf()
        self.model.still_ready(self.thumbBuf)

        self._thumb_element('thumb_tee').unlink(self._thumb_element('thumb_queue'))

        oggFilepath = os.path.join(Instance.instancePath, "output.ogg")
        wavFilepath = os.path.join(Instance.instancePath, "output.wav")
        muxFilepath = os.path.join(Instance.instancePath, "mux.ogg")

        muxline = Gst.parse_launch('filesrc location=' + str(oggFilepath) + ' name=muxVideoFilesrc ! oggdemux name=muxOggdemux ! theoraparse ! oggmux name=muxOggmux ! filesink location=' + str(muxFilepath) + ' name=muxFilesink filesrc location=' + str(wavFilepath) + ' name=muxAudioFilesrc ! wavparse name=muxWavparse ! audioconvert name=muxAudioconvert ! vorbisenc name=muxVorbisenc ! muxOggmux.')
        taglist = self._get_tags(constants.TYPE_VIDEO)
        vorbis_enc = muxline.get_by_name('muxVorbisenc')
        vorbis_enc.merge_tags(taglist, Gst.TAG_MERGE_REPLACE_ALL)

        muxBus = muxline.get_bus()
        muxBus.add_signal_watch()
        self._video_transcode_handler = muxBus.connect('message', self._onMuxedVideoMessageCb, muxline)
        self._mux_pipes.append(muxline)
        #add a listener here to monitor % of transcoding...
        self._transcode_id = GObject.timeout_add(200, self._transcodeUpdateCb, muxline)
        muxline.set_state(Gst.State.PLAYING)

    def _transcodeUpdateCb( self, pipe ):
        
        position, duration = self._query_position( pipe )
        
        if position != Gst.CLOCK_TIME_NONE:
            value = position * 100.0 / duration
            value = value/100.0
            self.model.set_progress(value, _('Saving...'))
            
        return True

    def _query_position(self, pipe):
        
        try:
            position, format = pipe.query_position(Gst.FORMAT_TIME)
            
        except:
            position = Gste.CLOCK_TIME_NONE

        try:
            duration, format = pipe.query_duration(Gst.FORMAT_TIME)
            
        except:
            duration = Gst.CLOCK_TIME_NONE

        return (position, duration)

    def _onMuxedVideoMessageCb(self, bus, message, pipe):
        
        if message.type != Gst.MESSAGE_EOS:
            return True

        GObject.source_remove(self._video_transcode_handler)
        self._video_transcode_handler = None
        GObject.source_remove(self._transcode_id)
        self._transcode_id = None
        pipe.set_state(Gst.State.NULL)
        pipe.get_bus().remove_signal_watch()
        pipe.get_bus().disable_sync_message_emission()

        wavFilepath = os.path.join(Instance.instancePath, "output.wav")
        oggFilepath = os.path.join(Instance.instancePath, "output.ogg")
        muxFilepath = os.path.join(Instance.instancePath, "mux.ogg")
        os.remove( wavFilepath )
        os.remove( oggFilepath )
        self.model.save_video(muxFilepath, self.thumbBuf)
        
        return False

    def _onMuxedAudioMessageCb(self, bus, message, pipe):
        
        if message.type != Gst.MESSAGE_EOS:
            return True

        GObject.source_remove(self._audio_transcode_handler)
        self._audio_transcode_handler = None
        GObject.source_remove(self._transcode_id)
        self._transcode_id = None
        pipe.set_state(Gst.State.NULL)
        pipe.get_bus().remove_signal_watch()
        pipe.get_bus().disable_sync_message_emission()

        wavFilepath = os.path.join(Instance.instancePath, "output.wav")
        oggFilepath = os.path.join(Instance.instancePath, "output.ogg")
        os.remove( wavFilepath )
        self.model.save_audio(oggFilepath, self._audio_pixbuf)
        return False

    def _bus_message_handler(self, bus, message):
        
        t = message.type
        
        if t == Gst.MessageType.EOS:
            if self._eos_cb:
                cb = self._eos_cb
                self._eos_cb = None
                cb()
                
        elif t == Gst.MessageType.ERROR:
            #todo: if we come out of suspend/resume with errors, then get us back up and running...
            #todo: handle "No space left on the resource.gstfilesink.c"
            #err, debug = message.parse_error()
            pass

    def abandonMedia(self):
        
        self.stop()

        if self._audio_transcode_handler:
            GObject.source_remove(self._audio_transcode_handler)
            self._audio_transcode_handler = None
            
        if self._transcode_id:
            GObject.source_remove(self._transcode_id)
            self._transcode_id = None
            
        if self._video_transcode_handler:
            GObject.source_remove(self._video_transcode_handler)
            self._video_transcode_handler = None

        wav_path = os.path.join(Instance.instancePath, "output.wav")
        
        if os.path.exists(wav_path):
            os.remove(wav_path)
            
        ogg_path = os.path.join(Instance.instancePath, "output.ogg")
        
        if os.path.exists(ogg_path):
            os.remove(ogg_path)
            
        mux_path = os.path.join(Instance.instancePath, "mux.ogg")
        
        if os.path.exists(mux_path):
            os.remove(mux_path)