gaupol/player.py

Source code for module gaupol.player from file gaupol/player.py.

  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
# -*- coding: utf-8 -*-

# Copyright (C) 2012 Osmo Salomaa
#
# 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 3 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, see <http://www.gnu.org/licenses/>.

"""GStreamer video player."""

import aeidon
import gaupol
_ = aeidon.i18n._

from gi.repository import Gdk
from gi.repository import Gtk

try:
    from gi.repository import GdkX11
    from gi.repository import Gst
    from gi.repository import GstPbutils
    from gi.repository import GstVideo
except Exception:
    pass

__all__ = ("VideoPlayer",)


class VideoPlayer(aeidon.Observable):

    """
    GStreamer video player.

    :ivar audio_track: Current audio track as integer
    :ivar calc: The instance of :class:`aeidon.Calculator` used
    :ivar _in_default_segment: ``True`` if in the default playback segment
    :ivar _info: :class:`Gst.DiscovererInfo` from current URI
    :ivar _playbin: GStreamer "playbin" element
    :ivar _prev_state: Previous state of `_playbin`
    :ivar subtitle_text: Current text shown in the subtitle overlay
    :ivar subtitle_text_raw: `subtitle_text` before removal of tags
    :ivar _text_overlay: GStreamer "textoverlay" element
    :ivar _time_overlay: GStreamer "timeoverlay" element
    :ivar volume: Current audio stream volume
    :ivar widget: :class:`Gtk.DrawingArea` used to render video
    :ivar _xid: `widget`'s X resource (window)

    Signals and their arguments for callback functions:
     * ``state-changed``: player new state
    """

    signals = ("state-changed",)

    def __init__(self):
        """Initialize a :class:`VideoPlayer` instance."""
        aeidon.Observable.__init__(self)
        self.calc = aeidon.Calculator()
        self._in_default_segment = True
        self._info = None
        self._playbin = None
        self._prev_state = None
        self.subtitle_text_raw = ""
        self._text_overlay = None
        self._time_overlay = None
        self.widget = None
        self._xid = None
        self._init_text_overlay()
        self._init_time_overlay()
        self._init_pipeline()
        self._init_bus()
        self._init_widget()

    @property
    def audio_track(self):
        """Return number of the current audio track."""
        track = self._playbin.props.current_audio
        # If at the default value, the first track is used,
        # which is (probably?) zero.
        track = (0 if track == -1 else track)
        return track

    @audio_track.setter
    def audio_track(self, track):
        """Set the current audio track."""
        self._playbin.props.current_audio = track

    def _ensure_default_segment(self):
        """
        Reset playback start and stop positions.

        When using `play_segment`, the playback limits are set to those
        (instead of the default 0 and -1). To be able to do useful things,
        we often need to reset those segment limits to their defaults.
        Any methods that need to rely on the whole duration being
        accessible, should as first thing call this method.
        """
        if self._in_default_segment: return
        # XXX: There's got to be a simpler way to do this.
        pos = self.get_position(aeidon.modes.SECONDS) * Gst.SECOND
        seek_flags = Gst.SeekFlags.FLUSH | Gst.SeekFlags.ACCURATE
        end = self.get_duration(aeidon.modes.SECONDS) * Gst.SECOND
        self._playbin.seek(rate=1.0,
                           format=Gst.Format.TIME,
                           flags=seek_flags,
                           start_type=Gst.SeekType.SET,
                           start=0,
                           stop_type=Gst.SeekType.SET,
                           stop=end)

        self._playbin.seek_simple(Gst.Format.TIME, seek_flags, pos)
        self._in_default_segment = True

    def get_audio_languages(self):
        """Return a sequence of audio languages or ``None``."""
        if self._info is None: return None
        return tuple(x.get_language() for x in self._info.get_audio_streams())

    def get_duration(self, mode=None):
        """
        Return duration of video stream or ``None``.

        `mode` can be ``None`` to return duration in internal :mod:`GStreamer`
        units, which can be faster if data is fed back to :mod:`GStreamer`.
        """
        success, duration = self._playbin.query_duration(Gst.Format.TIME)
        if not success: return None
        if mode is None: return duration
        duration = duration / Gst.SECOND
        if mode == aeidon.modes.SECONDS:
            return duration
        if mode == aeidon.modes.TIME:
            return self.calc.to_time(duration)
        if mode == aeidon.modes.FRAME:
            return self.calc.to_frame(duration)
        raise ValueError("Invalid mode: {}".format(repr(mode)))

    def get_position(self, mode=None):
        """
        Return current position in video stream or ``None``.

        `mode` can be ``None`` to return position in internal :mod:`GStreamer`
        units, which can be faster if data is fed back to :mod:`GStreamer`.
        """
        success, pos = self._playbin.query_position(Gst.Format.TIME)
        if not success: return None
        if mode is None: return pos
        pos = pos / Gst.SECOND
        if mode == aeidon.modes.SECONDS:
            return pos
        if mode == aeidon.modes.TIME:
            return self.calc.to_time(pos)
        if mode == aeidon.modes.FRAME:
            return self.calc.to_frame(pos)
        raise ValueError("Invalid mode: {}".format(repr(mode)))

    def _init_bus(self):
        """Initialize the GStreamer message bus."""
        bus = self._playbin.get_bus()
        bus.enable_sync_message_emission()
        bus.connect("sync-message::element", self._on_bus_sync_message)
        bus.add_signal_watch()
        bus.connect("message::eos", self._on_bus_message_eos)
        bus.connect("message::error", self._on_bus_message_error)
        bus.connect("message::state-changed",
                    self._on_bus_message_state_changed)

    def _init_pipeline(self):
        """Initialize the GStreamer playback pipeline."""
        self._playbin = Gst.ElementFactory.make("playbin", None)
        if gaupol.conf.video_player.volume is not None:
            self.volume = gaupol.conf.video_player.volume
        sink = Gst.ElementFactory.make("autovideosink", None)
        bin = Gst.Bin()
        bin.add(self._time_overlay)
        bin.add(self._text_overlay)
        pad = self._time_overlay.get_static_pad("video_sink")
        bin.add_pad(Gst.GhostPad.new("sink", pad))
        bin.add(sink)
        self._time_overlay.link(self._text_overlay)
        self._text_overlay.link(sink)
        self._playbin.props.video_sink = bin
        # We need to disable playbin's own subtitle rendering, since we don't
        # want embedded subtitles to be displayed, but rather what we
        # explicitly set to our own overlays. Since Gst.PlayFlags is not
        # available via introspection, we need to use Gst.util_set_object_arg.
        # Playbin's default values can be found via 'gst-inspect playbin'.
        Gst.util_set_object_arg(self._playbin,
                                "flags",
                                "+".join(("soft-colorbalance",
                                          "deinterlace",
                                          "soft-volume",
                                          "audio",
                                          "video")))

    def _init_text_overlay(self):
        """Initialize the text overlay element."""
        self._text_overlay = Gst.ElementFactory.make("textoverlay", None)
        conf = gaupol.conf.video_player
        callback = self._on_conf_notify_subtitle_property
        conf.connect("notify::subtitle_font", callback)
        conf.connect("notify::subtitle_color", callback)
        conf.connect("notify::subtitle_alpha", callback)
        conf.connect("notify::subtitle_background", callback)
        self._on_conf_notify_subtitle_property()

    def _init_time_overlay(self):
        """Initialize the time overlay element."""
        self._time_overlay = Gst.ElementFactory.make("timeoverlay", None)
        conf = gaupol.conf.video_player
        callback = self._on_conf_notify_time_property
        conf.connect("notify::time_font", callback)
        conf.connect("notify::time_color", callback)
        conf.connect("notify::time_alpha", callback)
        conf.connect("notify::time_background", callback)
        self._on_conf_notify_time_property()

    def _init_widget(self):
        """Initialize the rendering widget."""
        self.widget = Gtk.DrawingArea()
        color = Gdk.RGBA()
        success = color.parse("black")
        if not success: return
        state = Gtk.StateFlags.NORMAL
        self.widget.override_background_color(state, color)

    def is_playing(self):
        """Return ``True`` if playing video."""
        # GStreamer's state information is far too detailed for our purposes.
        # Let's consider the state to be playing also if undergoing a state
        # change and/or having a pending playing state.
        success, current, pending = self._playbin.get_state(timeout=1)
        return (success == Gst.StateChangeReturn.ASYNC or
                current == Gst.State.PLAYING or
                pending == Gst.State.PLAYING)

    def _on_bus_message_eos(self, bus, message):
        """Handle EOS message from the bus."""
        self._ensure_default_segment()
        self.pause()

    def _on_bus_message_error(self, bus, message):
        """Handle error message from the bus."""
        title, message = message.parse_error()
        dialog = gaupol.ErrorDialog(None, title, message)
        dialog.add_button(_("_OK"), Gtk.ResponseType.OK)
        dialog.set_default_response(Gtk.ResponseType.OK)
        gaupol.util.flash_dialog(dialog)

    def _on_bus_message_state_changed(self, bus, message):
        """Emit signal if state changed in a relevant manner."""
        old, new, pending = message.parse_state_changed()
        states = (Gst.State.NULL, Gst.State.PAUSED, Gst.State.PLAYING)
        if not new in states: return
        if new == self._prev_state: return
        self.emit("state-changed", new)
        self._prev_state = new

    def _on_bus_sync_message(self, bus, message):
        """Handle sync messages from the bus."""
        struct = message.get_structure()
        if struct.get_name() == "prepare-window-handle":
            message.src.set_window_handle(self._xid)

    def _on_conf_notify_subtitle_property(self, *args):
       """Update subtitle text overlay properties."""
       conf = gaupol.conf.video_player
       self._text_overlay.props.font_desc = conf.subtitle_font
       self._text_overlay.props.halignment = "center"
       self._text_overlay.props.valignment = "bottom"
       self._text_overlay.props.line_alignment = conf.line_alignment
       self._text_overlay.props.shaded_background = conf.subtitle_background
       alpha = "{:02x}".format(int(conf.subtitle_alpha * 255))
       color = conf.subtitle_color.replace("#", "")
       color = int(float.fromhex("".join((alpha, color))))
       self._text_overlay.props.color = color

    def _on_conf_notify_time_property(self, *args):
       """Update time overlay properties."""
       conf = gaupol.conf.video_player
       self._time_overlay.props.font_desc = conf.time_font
       self._time_overlay.props.halignment = "right"
       self._time_overlay.props.valignment = "top"
       self._time_overlay.props.shaded_background = conf.time_background
       alpha = "{:02x}".format(int(conf.time_alpha * 255))
       color = conf.time_color.replace("#", "")
       color = int(float.fromhex("".join((alpha, color))))
       self._time_overlay.props.color = color

    def pause(self):
        """Pause."""
        self._playbin.set_state(Gst.State.PAUSED)

    def play(self):
        """Play."""
        self._playbin.set_state(Gst.State.PLAYING)

    def play_segment(self, start, end):
        """
        Play from `start` to `end`.

        `start` and `end` can be either time, frame or seconds.
        """
        self._in_default_segment = False
        seek_flags = Gst.SeekFlags.FLUSH | Gst.SeekFlags.ACCURATE
        start = max(0, self.calc.to_seconds(start)) * Gst.SECOND
        duration = self.get_duration(aeidon.modes.SECONDS)
        end = min(duration, self.calc.to_seconds(end)) * Gst.SECOND
        self._playbin.seek(rate=1.0,
                           format=Gst.Format.TIME,
                           flags=seek_flags,
                           start_type=Gst.SeekType.SET,
                           start=start,
                           stop_type=Gst.SeekType.SET,
                           stop=end)

        self.play()

    def seek(self, pos):
        """
        Seek to `pos`.

        `pos` can be either time, frame or seconds.
        """
        self._ensure_default_segment()
        seek_flags = Gst.SeekFlags.FLUSH | Gst.SeekFlags.ACCURATE
        pos = self.calc.to_seconds(pos) * Gst.SECOND
        self._playbin.seek_simple(Gst.Format.TIME, seek_flags, pos)

    def seek_relative(self, offset):
        """
        Seek to `offset` relative to current position.

        `offset` can be either time, frame or seconds.
        """
        self._ensure_default_segment()
        pos = self.get_position(aeidon.modes.SECONDS)
        duration = self.get_duration(aeidon.modes.SECONDS)
        if pos is None or duration is None: return
        pos = pos + self.calc.to_seconds(offset)
        pos = max(0, min(pos, duration))
        pos = pos * Gst.SECOND
        seek_flags = Gst.SeekFlags.FLUSH | Gst.SeekFlags.ACCURATE
        self._playbin.seek_simple(Gst.Format.TIME, seek_flags, pos)

    def set_path(self, path):
        """
        Set the path of the file to play.

        You should have a window visible before calling `set_path`.
        """
        self.set_uri(aeidon.util.path_to_uri(path))

    def set_uri(self, uri):
        """
        Set the URI of the file to play.

        You should have a window visible before calling `set_uri`.
        """
        self._playbin.props.uri = uri
        # XXX: We need platform-specific calls here.
        self._xid = self.widget.get_window().get_xid()
        self.subtitle_text = ""
        try:
            # Find out the exact framerate to be able
            # to convert between position types.
            discoverer = GstPbutils.Discoverer()
            self._info = discoverer.discover_uri(uri)
            stream = self._info.get_video_streams()[0]
            num = float(stream.get_framerate_num())
            denom = float(stream.get_framerate_denom())
            self.calc = aeidon.Calculator(num/denom)
        except Exception:
            # If any of this fails, playback probably fails
            # as well and we'll show an error dialog then.
            pass

    def stop(self):
        """Stop."""
        self._playbin.set_state(Gst.State.NULL)
        self.subtitle_text = ""

    @property
    def subtitle_text(self):
        """Return text shown in the subtitle overlay."""
        return self._text_overlay.props.text

    @subtitle_text.setter
    def subtitle_text(self, text):
        """Set `text` to the subtitle overlay."""
        self.subtitle_text_raw = text
        text = aeidon.RE_ANY_TAG.sub("", text)
        self._text_overlay.props.text = text

    @property
    def volume(self):
        """Return the current volume, in range [0,1]."""
        return self._playbin.props.volume

    @volume.setter
    def volume(self, volume):
        """Set the volume to use, in range [0,1]."""
        volume = round(max(0, min(1, volume)), 2)
        if abs(volume - self.volume) < 0.001: return
        self._playbin.props.volume = volume
        gaupol.conf.video_player.volume = volume