Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/JAMediaReproductor.py
blob: 83d75f6fddddc549dcfc2e1ecb34b4eb9772a4d4 (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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#   JAMediaReproductor.py por:
#   Flavio Danesse <fdanesse@gmail.com>
#   CeibalJAM! - Uruguay
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

# Se remplaza:
# Depends: python-gst0.10,
#    gstreamer0.10-plugins-good,
#    gstreamer0.10-plugins-ugly,
#    gstreamer0.10-plugins-bad,
#    gstreamer0.10-ffmpeg

# Con:
# Depends: python-gi,
#    gir1.2-gstreamer-1.0,
#    gir1.2-gst-plugins-base-1.0,
#    gstreamer1.0-plugins-good,
#    gstreamer1.0-plugins-ugly,
#    gstreamer1.0-plugins-bad,
#    gstreamer1.0-libav
    
# https://wiki.ubuntu.com/Novacut/GStreamer1.0#Using_GStreamer_1.0_from_Python
# http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer/html/GstBus.html#gst-bus-create-watch
# http://www.roojs.org/seed/gir-1.1-gtk-2.0/Gst.MessageType.html#expand

import os

import gi
gi.require_version('Gst', '1.0')

from gi.repository import GObject
from gi.repository import Gst
from gi.repository import GstVideo

GObject.threads_init()
Gst.init(None)

class JAMediaReproductor(GObject.GObject):
    """
    Reproductor de Audio, Video y Streaming de
    Radio y Television. Implementado sobre:
        
        python 2.7.3
        Gtk 3
        Gstreamer 1.0
    """
    
    __gsignals__ = {"endfile":(GObject.SIGNAL_RUN_FIRST,
    GObject.TYPE_NONE, []),
    "estado":(GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE,
    (GObject.TYPE_STRING,)),
    "newposicion":(GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE,
    (GObject.TYPE_INT,)),
    "volumen":(GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE,
    (GObject.TYPE_FLOAT,))}

    # Estados: playing, paused, None
    
    def __init__(self, ventana_id):
        """ Recibe el id de un DrawingArea
        para mostrar el video. """
        
        GObject.GObject.__init__(self)
        self.name = "JAMediaReproductor"
        self.ventana_id = ventana_id
        self.pipeline = None
        self.estado = None
        
        self.duracion = 0
        self.posicion = 0
        self.actualizador = None
        
        self.player = None
        self.bus = None

        self.set_pipeline()
        
    def set_pipeline(self):
        """Crea el pipe de Gst. (playbin)"""
        
        if self.pipeline: del(self.pipeline)
        
        self.pipeline = Gst.Pipeline()
        self.bus = self.pipeline.get_bus()
        self.bus.add_signal_watch()
        self.bus.connect('message', self.on_mensaje)
        
        self.bus.enable_sync_message_emission()
        self.bus.connect('sync-message', self.sync_message)
        
        self.player = Gst.ElementFactory.make("playbin", "player")
        self.pipeline.add(self.player)

    def sync_message(self, bus, mensaje):
        """Captura los mensajes en el bus del pipe Gst."""
        
        try:
            if mensaje.get_structure().get_name() == 'prepare-window-handle':
                mensaje.src.set_window_handle(self.ventana_id)
                return
        except:
            pass
            
        if mensaje.type == Gst.MessageType.STATE_CHANGED:
            old, new, pending = mensaje.parse_state_changed()
            if old == Gst.State.PAUSED and new == Gst.State.PLAYING:
                if self.estado != new:
                    self.estado = new
                    self.emit("estado", "playing")
                    self.new_handle(True)
                    return
            elif old == Gst.State.READY and new == Gst.State.PAUSED:
                if self.estado != new:
                    self.estado = new
                    self.emit("estado", "paused")
                    self.new_handle(False)
                    return
            elif old == Gst.State.READY and new == Gst.State.NULL:
                if self.estado != new:
                    self.estado = new
                    self.emit("estado", "None")
                    self.new_handle(False)
                    return
            elif old == Gst.State.PLAYING and new == Gst.State.PAUSED:
                if self.estado != new:
                    self.estado = new
                    self.emit("estado", "paused")
                    self.new_handle(False)
                    return
            elif old == Gst.State.NULL and new == Gst.State.READY:
                pass
            elif old == Gst.State.PAUSED and new == Gst.State.READY:
                pass
            else:
                #print ">>>", old, new, pending
                return
        
        elif mensaje.type == Gst.MessageType.ASYNC_DONE:
            #print mensaje.get_structure().get_name()
            return
        elif mensaje.type == Gst.MessageType.NEW_CLOCK:
            return
        elif mensaje.type == Gst.MessageType.STREAM_STATUS:
            #print mensaje.parse_stream_status()
            return
        elif mensaje.type == Gst.MessageType.TAG:
            return
        elif mensaje.type == Gst.MessageType.ERROR:
            err, debug = mensaje.parse_error()
            print "***", 'sync_message'
            print err, debug
            self.new_handle(False)
            #self.pipeline.set_state(Gst.State.NULL)
            #self.pipeline.set_state(Gst.State.READY)
            #return self.set_pipeline()
            return
        elif mensaje.type == Gst.MessageType.EOS:
            return
        else:
            try:
                nombre = mensaje.get_structure().get_name()
                if nombre == "playbin-stream-changed":
                    #print "Nuevo src:", mensaje.get_structure().to_string()
                    pass
                elif nombre == "have-window-handle":
                    pass
                elif nombre == "prepare-window-handle":
                    pass
                else:
                    pass
            except:
                print "sync_message", mensaje.type
            return
                
    def on_mensaje(self, bus, mensaje):
        """Captura los mensajes en el bus del pipe Gst."""
        
        #if mensaje.type == Gst.MessageType.ASYNC_DONE:
        #    print mensaje.get_structure().get_name()
        #elif mensaje.type == Gst.MessageType.NEW_CLOCK:
        #    pass
        
        if mensaje.type == Gst.MessageType.ELEMENT:
            nombre = mensaje.get_structure().get_name()
            # playbin-stream-changed , prepare-window-handle, have-window-handle
            #if nombre == 'prepare-window-handle':
            #    mensaje.src.set_window_handle(self.ventana_id)
            #else:
            #    print nombre
            
            '''
            elif mensaje.type == Gst.MessageType.STATE_CHANGED:
                old, new, pending = mensaje.parse_state_changed()
                if old == Gst.State.PAUSED and new == Gst.State.PLAYING:
                    if self.estado != new:
                        self.estado = new
                        #self.emit("estado", "playing")
                elif old == Gst.State.READY and new == Gst.State.PAUSED:
                    if self.estado != new:
                        self.estado = new
                        #self.emit("estado", "paused")
                else:
                    if self.F: print old, new, pending
                    pass
            elif mensaje.type == Gst.MessageType.STREAM_STATUS:
                pass
            elif mensaje.type == Gst.MessageType.TAG:
                #print mensaje.get_structure().to_string()
                pass'''
        
        if mensaje.type == Gst.MessageType.EOS:
            #self.pipeline.seek_simple(Gst.Format.TIME,
            #Gst.SeekFlags.FLUSH | Gst.SeekFlags.KEY_UNIT, 0)
            self.new_handle(False)
            self.set_pipeline()
            self.emit("endfile")
            
        elif mensaje.type == Gst.MessageType.QOS:
            pass
        elif mensaje.type == Gst.MessageType.WARNING:
            print mensaje.get_structure().to_string()
            #self.new_handle(False)
            #self.pipeline.set_state(Gst.State.NULL)
            #self.set_pipeline()
            
        elif mensaje.type == Gst.MessageType.ERROR:
            err, debug = mensaje.parse_error()
            print "***", 'sync_message'
            print err, debug
            self.new_handle(False)
            #self.pipeline.set_state(Gst.State.NULL)
            #self.set_pipeline()
            self.pipeline.set_state(Gst.State.READY)
            
        elif mensaje.type == Gst.MessageType.LATENCY:
            #print mensaje.type
            pass
        else:
            #print "on_mensaje", mensaje.type
            pass
        
    def load(self, uri):
        """Carga un archivo o stream en el pipe de Gst."""
        
        self.stop()
        if os.path.exists(uri):
            direccion = Gst.filename_to_uri(uri)
            self.player.set_property("uri", direccion)
            self.play()
        else:
            # FIXME: Funciona con la radio pero no con la Tv
            direccion = uri
            #Gst.uri_get_protocol(uri)
            if Gst.uri_is_valid(uri):
                self.player.set_property("uri", direccion)
                self.play()
            #print Gst.uri_protocol_is_supported(uri, Gst.uri_get_protocol(uri))
            #print Gst.uri_protocol_is_valid(Gst.uri_get_protocol(uri))
            #self.player.set_property("buffer-size", 1024)
            #self.player.set_property("force-aspect-ratio", False)
        
    def play(self):
        """Pone el pipe de Gst en Gst.State.PLAYING"""
        
        self.pipeline.set_state(Gst.State.PLAYING)
        
    def stop(self):
        """Pone el pipe de Gst en Gst.State.NULL"""
        
        self.pipeline.set_state(Gst.State.NULL)
        self.pipeline.set_state(Gst.State.READY)
        
    def pause(self):
        """Pone el pipe de Gst en Gst.State.PAUSED"""
        
        self.pipeline.set_state(Gst.State.PAUSED)
    
    def pause_play(self):
        """Llama a play() o pause()
        segun el estado actual del pipe de Gst."""
        
        if self.estado == Gst.State.PAUSED \
            or self.estado == Gst.State.NULL \
            or self.estado == Gst.State.READY:
            self.play()
        elif self.estado == Gst.State.PLAYING:
            self.pause()
        else:
            print self.estado
            
    def new_handle(self, reset):
        """Elimina o reinicia la funcion que
        envia los datos de actualizacion para
        la barra de progreso del reproductor."""
        
        if self.actualizador:
            GObject.source_remove(self.actualizador)
            self.actualizador = None
        if reset:
            self.actualizador = GObject.timeout_add(300, self.handle)
        
    def handle(self):
        """Funcion que envia los datos de actualizacion para
        la barra de progreso del reproductor."""
        
        bool1, valor1 = self.pipeline.query_duration(Gst.Format.TIME)
        bool2, valor2 = self.pipeline.query_position(Gst.Format.TIME)
        
        duracion = float(valor1)
        posicion = float(valor2)
        
        pos = 0
        try:
            pos = int(posicion * 100 / duracion)
        except:
            pass
        
        if pos < 0 or pos > self.duracion: return True
        
        if self.duracion != duracion: self.duracion = duracion
        
        if pos != self.posicion:
            self.posicion = pos
            self.emit("newposicion", self.posicion)
            # print "***", gst.video_convert_frame(self.player.get_property("frame"))
            
        return True
    
    def set_position(self, posicion):
        """Funcion que permite desplazarse por
        el archivo que se esta reproduciendo."""
        
        if self.duracion < posicion:
            self.emit("newposicion", self.posicion)
            return
        posicion = self.duracion * posicion / 100
        self.pipeline.seek_simple(Gst.Format.TIME,
        Gst.SeekFlags.FLUSH, posicion)
    
    def get_volumen(self):
        pass
    
    def set_volumen(self, valor):
        pass