Пример #1
0
    def test_asset_metadata_on_reload(self):
        mainloop = GLib.MainLoop()

        unused, xges_path = tempfile.mkstemp(suffix=".xges")
        project_uri = Gst.filename_to_uri(os.path.abspath(xges_path))

        asset_uri = Gst.filename_to_uri(
            os.path.join(__file__, "../../assets/audio_video.ogg"))
        xges = """<ges version='0.3'>
                <project properties='properties;' metadatas='metadatas;'>
                    <ressources>
                        <asset id='%(uri)s' extractable-type-name='GESUriClip' properties='properties, supported-formats=(int)6, duration=(guint64)2003000000;' metadatas='metadatas, container-format=(string)Matroska, language-code=(string)und, application-name=(string)Lavc56.60.100, encoder-version=(uint)0, audio-codec=(string)Vorbis, nominal-bitrate=(uint)80000, bitrate=(uint)80000, video-codec=(string)&quot;On2\ VP8&quot;, file-size=(guint64)223340, foo=(string)bar;' >
                        </asset>
                    </ressources>
                </project>
                </ges>""" % {
            "uri": asset_uri
        }
        with open(xges_path, "w") as xges_file:
            xges_file.write(xges)

        def loaded_cb(project, timeline):
            asset = project.list_assets(GES.Extractable)[0]
            self.assertEqual(asset.get_meta("foo"), "bar")
            mainloop.quit()

        loaded_project = GES.Project(uri=project_uri,
                                     extractable_type=GES.Timeline)
        loaded_project.connect("loaded", loaded_cb)
        timeline = loaded_project.extract()
        mainloop.run()
Пример #2
0
    def render(self, dialog):
        """Renders pipeline from @dialog."""
        from pitivi.render import RenderingProgressDialog
        with tempfile.TemporaryDirectory() as temp_dir:
            # Start rendering
            with mock.patch.object(dialog.filebutton,
                                   "get_uri",
                                   return_value=Gst.filename_to_uri(temp_dir)):
                with mock.patch.object(dialog.fileentry,
                                       "get_text",
                                       return_value="outfile"):
                    with mock.patch.object(RenderingProgressDialog, "__new__"):
                        dialog._renderButtonClickedCb(None)

            message = dialog._pipeline.get_bus().timed_pop_filtered(
                Gst.CLOCK_TIME_NONE,
                Gst.MessageType.EOS | Gst.MessageType.ERROR)
            self.assertIsNotNone(message)
            Gst.debug_bin_to_dot_file_with_ts(
                dialog._pipeline, Gst.DebugGraphDetails.ALL,
                "test_rendering_with_profile.dot")

            result_file = Gst.filename_to_uri(os.path.join(
                temp_dir, "outfile"))
            struct = message.get_structure()
            self.assertEqual(message.type, Gst.MessageType.EOS,
                             struct.to_string() if struct else message)
            asset = GES.UriClipAsset.request_sync(result_file)
            self.assertIsNotNone(asset)

            if message:
                dialog._pipeline.get_bus().post(message)
Пример #3
0
    def render(self, dialog):
        """Renders pipeline from @dialog."""
        from pitivi.render import RenderingProgressDialog
        with tempfile.TemporaryDirectory() as temp_dir:
            # Start rendering
            with mock.patch.object(dialog.filebutton, "get_uri",
                                   return_value=Gst.filename_to_uri(temp_dir)):
                with mock.patch.object(dialog.fileentry, "get_text", return_value="outfile"):
                    with mock.patch.object(RenderingProgressDialog, "__new__"):
                        dialog._renderButtonClickedCb(None)

            message = dialog._pipeline.get_bus().timed_pop_filtered(
                10 * Gst.SECOND,
                Gst.MessageType.EOS | Gst.MessageType.ERROR)
            Gst.debug_bin_to_dot_file_with_ts(
                dialog._pipeline, Gst.DebugGraphDetails.ALL,
                "test_rendering_with_profile.dot")

            result_file = Gst.filename_to_uri(os.path.join(temp_dir, "outfile"))
            struct = message.get_structure() if message else None
            self.assertEqual(message.type, Gst.MessageType.EOS,
                             struct.to_string() if struct else message)
            asset = GES.UriClipAsset.request_sync(result_file)
            # FIXME Check more things?
            self.assertIsNotNone(asset)
Пример #4
0
    def test_request_relocated_assets_sync(self):
        path = os.path.join(__file__, "../../../", "png.png")
        with self.assertRaises(GLib.Error):
            GES.UriClipAsset.request_sync(Gst.filename_to_uri(path))

        GES.add_missing_uri_relocation_uri(
            Gst.filename_to_uri(os.path.join(__file__, "../../assets")), False)
        path = os.path.join(__file__, "../../", "png.png")
        self.assertEqual(
            GES.UriClipAsset.request_sync(Gst.filename_to_uri(path)).props.id,
            Gst.filename_to_uri(os.path.join(__file__,
                                             "../../assets/png.png")))
Пример #5
0
    def testSaveProjectWithRemovedProxy(self):
        sample_name = "30fps_numeroted_frames_red.mkv"
        with common.cloned_sample(sample_name):
            self.check_import([sample_name])

            project = self.app.project_manager.current_project
            asset = GES.UriClipAsset.request_sync(common.get_sample_uri(sample_name))
            target = asset.get_proxy_target()
            self.assertEqual(set(project.list_assets(GES.Extractable)), set([target, asset]))

            # Remove the asset
            self.medialibrary.remove_assets_action.emit("activate", None)

            # Make sure that the project has not assets anymore
            self.assertEqual(project.list_assets(GES.Extractable), [])

            # Save the project and reload it, making sure there is no asset
            # in that new project
            project_uri = Gst.filename_to_uri(tempfile.NamedTemporaryFile().name)
            project.save(project.ges_timeline, project_uri, None, True)

            self._customSetUp(project_uri)
            self.assertNotEqual(project, self.app.project_manager.current_project)
            project = self.app.project_manager.current_project
            self.assertEqual(project.list_assets(GES.Extractable), [])
Пример #6
0
    def add_music_file(self, filepath):
        contents = open(filepath, "r")

        disc = GstPbutils.Discoverer.new(50000000000)
        file_uri = Gst.filename_to_uri(filepath)
        info = disc.discover_uri(file_uri)
        tags = info.get_tags()
        artist = album = title = "Unknown"
        track_num = 0
        tagged, tag = tags.get_string('artist')
        if tagged:
            artist = unicode(tag, "UTF-8")
        tagged, tag = tags.get_string('album')
        if tagged:
            album = unicode(tag, "UTF-8")
        tagged, tag = tags.get_string('title')
        if tagged:
            title = unicode(tag, "UTF-8")
        tagged, tag = tags.get_uint('track-number')
        if tagged:
            track_num = tag

        headers = []
        headers.append(["X-Object-Meta-Artist", artist])
        headers.append(["X-Object-Meta-Album", album])
        headers.append(["X-Object-Meta-Title", title])
        headers.append(["X-Object-Meta-Track-Num", str(track_num)])

        obj_name = "%s/%s" % (album, title)
        if not self.container_exists(artist):
            self.conn.put_container(artist)
        self.conn.put_object(artist, obj_name, contents, headers=headers)
        contents.close()

        return artist, album, title, track_num
Пример #7
0
    def run(self):
        self.playbin = Gst.ElementFactory.make("playbin", None)

        if self.playbin:
            if Gst.uri_is_valid(self.uri):
                uri = self.uri
            else:
                uri = Gst.filename_to_uri(self.uri)
            self.playbin.set_property('uri', uri)
            self.playbin.set_property('volume', self.volume_level)

            bus = self.playbin.get_bus()
            bus.add_signal_watch()
            bus.connect("message", self.bus_call, self.loop)
            bus.connect("message::tag", self.on_tag)

            self.playbin.set_state(Gst.State.PLAYING)
            self.loop = GLib.MainLoop()
            try:
                self.stats.update(dict(status='playing'))
                self.notify()
                self.loop.run()
            except OSError as e:
                pass
            finally:
                self.loop.quit()
                self.playbin.set_state(Gst.State.NULL)
                self.stats.update(dict(status='stopped'))
                self.notify()
Пример #8
0
 def start(self):
     Media.start(self)
     if not Gst.uri_is_valid(self.uri):
         self.uri = Gst.filename_to_uri(self.uri)
     source = Gst.ElementFactory.make("uridecodebin", None)
     source.set_property("uri", self.uri)
     queue = Gst.ElementFactory.make("queue2", None)
     queue.set_property("max-size-buffers", 5)
     convert = Gst.ElementFactory.make("videoconvert", None)
     sink = Gst.ElementFactory.make("appsink", None)
     sink.set_property("emit-signals", True)
     sink.set_property("max-buffers", 1)
     caps = Gst.caps_from_string("video/x-raw, format=(string){RGBA}")
     sink.set_property("caps", caps)
     self.pipeline.add(source)
     self.pipeline.add(queue)
     self.pipeline.add(convert)
     self.pipeline.add(sink)
     source.connect("pad-added", self.on_pad_added, queue)
     queue.link(convert)
     convert.link(sink)
     sink.connect("new-sample", self.on_frame_cpu)
     # Creates a bus and set callbacks to receive errors
     bus = self.pipeline.get_bus()
     bus.add_signal_watch()
     bus.connect("message::eos", self.on_eos)
     bus.connect("message::error", self.on_error)
     self.pipeline.set_state(Gst.State.PLAYING)
Пример #9
0
    def __init__(self, uri, archivo, tipo):

        GObject.GObject.__init__(self)

        self.tipo = tipo

        if not archivo.endswith(".ogg"):
            archivo = "%s%s" % (archivo, ".ogg")
            #archivo = "%s%s" % (archivo, ".mp3")

        self.patharchivo = archivo
        self.actualizador = False
        self.control = 0
        self.tamanio = 0
        self.uri = ""

        self.pipeline = None
        self.player = None
        self.archivo = None
        self.bus = None

        self.__reset()

        if os.path.exists(uri):
            # FIXME: Analizar
            uri = Gst.filename_to_uri(uri)

        if Gst.uri_is_valid(uri):
            self.archivo.set_property("location", self.patharchivo)
            self.player.set_property("uri", uri)
            self.__play()
            self.__new_handle(True)

        else:
            self.emit("endfile")
Пример #10
0
 def onSelectionActivated(self, listbox, row):
     selected_song = getattr(row, "path")
     name = getattr(row, "name")
     selected_song = Gst.filename_to_uri(selected_song)
     self.player.setUri(selected_song)
     self.headerBar.set_title(name)
     self.onPlay()
Пример #11
0
    def add_music_file(self, filepath):
        contents = open(filepath, "r")

        disc = GstPbutils.Discoverer.new(50000000000)
        file_uri = Gst.filename_to_uri(filepath)
        info = disc.discover_uri(file_uri)
        tags = info.get_tags()
        artist = album = title = "Unknown"
        track_num = 0
        tagged, tag = tags.get_string('artist')
        if tagged:
            artist = unicode(tag, "UTF-8")
        tagged, tag = tags.get_string('album')
        if tagged:
            album = unicode(tag, "UTF-8")
        tagged, tag = tags.get_string('title')
        if tagged:
            title = unicode(tag, "UTF-8")
        tagged, tag = tags.get_uint('track-number')
        if tagged:
            track_num = tag

        headers = []
        headers.append(["X-Object-Meta-Artist", artist])
        headers.append(["X-Object-Meta-Album", album])
        headers.append(["X-Object-Meta-Title", title])
        headers.append(["X-Object-Meta-Track-Num", str(track_num)])

        obj_name = "%s/%s" % (album, title)
        if not self.container_exists(artist):
            self.conn.put_container(artist)
        self.conn.put_object(artist, obj_name, contents, headers=headers)
        contents.close()

        return artist, album, title, track_num
Пример #12
0
    def test_serialize_invert(self):
        timeline = GES.Timeline.new()
        timeline.add_track(GES.VideoTrack.new())
        layer = timeline.append_layer()

        clip1 = GES.TransitionClip.new_for_nick("crossfade")
        clip1.props.duration = Gst.SECOND
        self.assertTrue(layer.add_clip(clip1))

        vtransition, = clip1.children
        vtransition.set_inverted(True)
        self.assertEqual(vtransition.props.invert, True)

        with tempfile.NamedTemporaryFile() as tmpxges:
            uri = Gst.filename_to_uri(tmpxges.name)
            timeline.save_to_uri(uri, None, True)

            timeline = GES.Timeline.new_from_uri(uri)
            project = timeline.get_asset()
            mainloop = common.create_main_loop()
            project.connect("loaded", lambda _, __: mainloop.quit())
            mainloop.run()
            self.assertIsNotNone(timeline)
            layer, = timeline.get_layers()
            clip, = layer.get_clips()
            vtransition, = clip.children
            self.assertEqual(vtransition.props.invert, True)
Пример #13
0
    def test_load_project_clip_speed(self):
        sources_count = 2
        clip, = self.layer.get_clips()
        clip.props.duration = Gst.SECOND

        self.timeline_container.timeline.selection.select([clip])
        self.speed_box._speed_adjustment.props.value = 0.5
        self.assert_applied_rate(sources_count, 0.5, 2 * Gst.SECOND)

        with tempfile.NamedTemporaryFile() as temp_file:
            uri = Gst.filename_to_uri(temp_file.name)
            project_manager = self.app.project_manager
            self.assertTrue(project_manager.save_project(uri=uri, backup=False))

            mainloop = common.create_main_loop()

            project_manager.connect("new-project-loaded", lambda *args: mainloop.quit())
            project_manager.connect("closing-project", lambda *args: True)
            self.assertTrue(project_manager.close_running_project())
            project_manager.load_project(uri)
            mainloop.run()

        new_clip, = self.layer.get_clips()
        self.assertNotEqual(new_clip, clip)

        self.timeline_container.timeline.selection.select([new_clip])
        self.assert_applied_rate(sources_count, 0.5, 2 * Gst.SECOND)
Пример #14
0
def process_next(bus, message):
    print ('got EOS')
    
    if 'datetime' in latest_tag:
        del latest_tag['datetime']
    
    tags.append(latest_tag)
    
    global latest_tags
    latest_tags = {}

    try:
        fname = fnames.pop(0)
    except IndexError:
        print ('No more files to process, exit')

        with open('metadata.pickle', 'wb') as f:
            pickle.dump(tags, f)

        loop.quit()
        return False

    print ('fname:', fname)
    uri = Gst.filename_to_uri(fname)
    latest_tag['uri'] = uri

    pipe.set_state(Gst.State.NULL)
    pipe.get_by_name('decoder').set_property('uri', uri)
    pipe.set_state(Gst.State.PLAYING)
Пример #15
0
def created_project_file(asset_uri):
    """Creates a project file.

    Yields:
        str: The URI of the new project
    """
    unused_fd, xges_path = tempfile.mkstemp()
    with open(xges_path, "w") as xges:
        xges.write("""
<ges version='0.1'>
  <project>
    <ressources>
      <asset id='%(asset_uri)s' extractable-type-name='GESUriClip' />
    </ressources>
    <timeline>
      <track caps='video/x-raw' track-type='4' track-id='0' />
      <layer priority='0'>
        <clip id='0' asset-id='%(asset_uri)s'
            type-name='GESUriClip' layer-priority='0' track-types='4'
            start='0' duration='2590000000' inpoint='0' rate='0' />
      </layer>
    </timeline>
</project>
</ges>""" % {'asset_uri': asset_uri})

    yield Gst.filename_to_uri(xges_path)

    os.remove(xges_path)
Пример #16
0
    def __init__(self, uri, archivo, tipo):

        GObject.GObject.__init__(self)

        self.tipo = tipo

        if not archivo.endswith(".ogg"):
            archivo = "%s%s" % (archivo, ".ogg")
            #archivo = "%s%s" % (archivo, ".mp3")

        self.patharchivo = archivo
        self.actualizador = False
        self.control = 0
        self.tamanio = 0
        self.uri = ""

        self.pipeline = None
        self.player = None
        self.archivo = None
        self.bus = None

        self.__reset()

        if os.path.exists(uri):
            # FIXME: Analizar
            uri = Gst.filename_to_uri(uri)

        if Gst.uri_is_valid(uri):
            self.archivo.set_property("location", self.patharchivo)
            self.player.set_property("uri", uri)
            self.__play()
            self.__new_handle(True)

        else:
            self.emit("endfile")
Пример #17
0
    def createTempProject(self):
        """
        Created a temporary project

        Always generate projects with missing assets for now

        Returns:
            str: The path of the new project
            str: The URI of the new project
        """
        unused_fd, xges_path = tempfile.mkstemp()
        with open(xges_path, "w") as xges:
            xges.write("""
<ges version='0.1'>
  <project>
    <ressources>
      <asset id='file:///icantpossiblyexist.png'
            extractable-type-name='GESUriClip' />
    </ressources>
    <timeline>
      <track caps='video/x-raw' track-type='4' track-id='0' />
      <layer priority='0'>
        <clip id='0' asset-id='file:///icantpossiblyexist.png'
            type-name='GESUriClip' layer-priority='0' track-types='4'
            start='0' duration='2590000000' inpoint='0' rate='0' />
      </layer>
    </timeline>
</project>
</ges>""")

        return xges_path, Gst.filename_to_uri(xges_path)
Пример #18
0
 def load(self, path):
     self.pause()
     uri = path if Gst.uri_is_valid(path) else Gst.filename_to_uri(path)
     self.pipeline.set_state(Gst.State.READY)
     self.playbin.set_property('uri', uri)
     self.play()
     self.pause()
    def check_reload_timeline(self):
        tmpf = tempfile.NamedTemporaryFile(suffix='.xges')
        uri = Gst.filename_to_uri(tmpf.name)
        self.assertTrue(self.timeline.save_to_uri(uri, None, True))
        project = GES.Project.new(uri)
        mainloop = create_main_loop()

        def loaded_cb(unused_project, unused_timeline):
            mainloop.quit()

        project.connect("loaded", loaded_cb)
        reloaded_timeline = project.extract()

        mainloop.run()
        self.assertIsNotNone(reloaded_timeline)

        layers = self.timeline.get_layers()
        reloaded_layers = reloaded_timeline.get_layers()
        self.assertEqual(len(layers), len(reloaded_layers))
        for layer, reloaded_layer in zip(layers, reloaded_layers):
            clips = layer.get_clips()
            reloaded_clips = reloaded_layer.get_clips()
            self.assertEqual(len(clips), len(reloaded_clips))
            for clip, reloaded_clip in zip(clips, reloaded_clips):
                self.assertElementAreEqual(clip, reloaded_clip)

        return reloaded_timeline
Пример #20
0
def transcode(input_file, output_file, profile=None):
    Gst.init()
    if not Gst.uri_is_valid (input_file):
        input_file = Gst.filename_to_uri (input_file)
    ensure_directory(os.path.dirname(output_file))
    if profile is None:
        profile=create_encoding_profile()

    loop = GObject.MainLoop()

    pipeline = Gst.Pipeline()
    uridecodebin = Gst.ElementFactory.make('uridecodebin')
    encodebin = Gst.ElementFactory.make('encodebin')
    sink = Gst.ElementFactory.make('filesink')
    pipeline.add(uridecodebin)
    pipeline.add(encodebin)
    pipeline.add(sink)

    encodebin.link(sink)

    uridecodebin.set_property('uri', input_file)
    sink.set_property('location', output_file)
    encodebin.set_property('profile', profile)
    uridecodebin.connect('pad-added', on_pad_added, (pipeline, encodebin))

    bus = pipeline.get_bus()
    bus.add_watch(0, on_message, (pipeline, loop))

    pipeline.set_state(Gst.State.PLAYING)
    loop.run()
Пример #21
0
def created_project_file(asset_uri="file:///icantpossiblyexist.png"):
    """
    Create a project file.

    Yields:
        str: The URI of the new project
    """
    unused_fd, xges_path = tempfile.mkstemp()
    with open(xges_path, "w") as xges:
        xges.write("""
<ges version='0.1'>
  <project>
    <ressources>
      <asset id='%(asset_uri)s' extractable-type-name='GESUriClip' />
    </ressources>
    <timeline>
      <track caps='video/x-raw' track-type='4' track-id='0' />
      <layer priority='0'>
        <clip id='0' asset-id='%(asset_uri)s'
            type-name='GESUriClip' layer-priority='0' track-types='4'
            start='0' duration='2590000000' inpoint='0' rate='0' />
      </layer>
    </timeline>
</project>
</ges>""" % {'asset_uri': asset_uri})

    yield Gst.filename_to_uri(xges_path)

    os.remove(xges_path)
Пример #22
0
    def test_scaled_proxy_size(self):
        app = common.create_pitivi_mock(default_scaled_proxy_width=123,
                                        default_scaled_proxy_height=456)
        manager = ProjectManager(app)
        project = manager.new_blank_project()
        self.assertFalse(project.has_scaled_proxy_size())
        self.assertEqual(project.scaled_proxy_width, 123)
        self.assertEqual(project.scaled_proxy_height, 456)

        with tempfile.NamedTemporaryFile() as temp_file:
            uri = Gst.filename_to_uri(temp_file.name)
            manager.save_project(uri=uri, backup=False)
            app2 = common.create_pitivi_mock(default_scaled_proxy_width=12,
                                             default_scaled_proxy_height=45)
            project2 = ProjectManager(app2).load_project(uri)
            self.assertFalse(project2.has_scaled_proxy_size())
            self.assertEqual(project2.scaled_proxy_width, 12)
            self.assertEqual(project2.scaled_proxy_height, 45)

        project.scaled_proxy_width = 123
        project.scaled_proxy_height = 456
        self.assertTrue(project.has_scaled_proxy_size())
        self.assertEqual(project.scaled_proxy_width, 123)
        self.assertEqual(project.scaled_proxy_height, 456)

        with tempfile.NamedTemporaryFile() as temp_file:
            manager.save_project(uri=uri, backup=False)
            app2 = common.create_pitivi_mock(default_scaled_proxy_width=1,
                                             default_scaled_proxy_height=4)
            project2 = ProjectManager(app2).load_project(uri)
            self.assertTrue(project2.has_scaled_proxy_size())
            self.assertEqual(project2.scaled_proxy_width, 123)
            self.assertEqual(project2.scaled_proxy_height, 456)
    def test_save_project_with_removed_proxy(self):
        sample_name = "30fps_numeroted_frames_red.mkv"
        with common.cloned_sample(sample_name):
            self.check_import([sample_name])

            project = self.app.project_manager.current_project
            asset = GES.UriClipAsset.request_sync(
                common.get_sample_uri(sample_name))
            target = asset.get_proxy_target()
            self.assertEqual(set(project.list_assets(GES.Extractable)),
                             set([target, asset]))

            # Remove the asset
            self.medialibrary.remove_assets_action.emit("activate", None)

            # Make sure that the project has not assets anymore
            self.assertEqual(project.list_assets(GES.Extractable), [])

            # Save the project and reload it, making sure there is no asset
            # in that new project
            project_uri = Gst.filename_to_uri(
                tempfile.NamedTemporaryFile().name)
            project.save(project.ges_timeline, project_uri, None, True)

            self._custom_set_up(project_uri)
            self.assertNotEqual(project,
                                self.app.project_manager.current_project)
            project = self.app.project_manager.current_project
            self.assertEqual(project.list_assets(GES.Extractable), [])
Пример #24
0
    def __init__(self, args):
        super().__init__()

        self.ignore_tracker = False
        self.file_index = 0

        app = QApplication(sys.argv)

        self.create_window(args)

        self.player = Player(args)

        self.player.state_changed.connect(self.update_state)
        self.player.duration_changed.connect(self.update_tracker_duration)
        self.player.position_updated.connect(self.update_tracker_position)

        self.tracker.valueChanged.connect(self.tracker_value_changed)

        #self.play_button.clicked.connect(functools.partial(self.button_clicked, "play"))
        self.play_button.clicked.connect(self.play)
        self.pause_button.clicked.connect(self.pause)
        self.stop_button.clicked.connect(self.stop)
        self.seek_backward_button.clicked.connect(self.player.step_backward)
        self.seek_forward_button.clicked.connect(self.player.step_forward)
        self.media_next_button.clicked.connect(self.next_media)
        self.media_previous_button.clicked.connect(self.previous_media)

        self.window.show()

        self.video_widget.set_overlay(self.player.playbin)

        self.update_state(PlayerState.STOPPED)

        self.files = [x.replace("\n", " ") for x in args.files]

        files = []
        for index, file in enumerate(self.files):
            print((index, file))
            if os.path.isdir(file):
                pattern = "*.wmv"
                files.extend(
                    glob.iglob(file + "/**/" + pattern, recursive=True))
            elif os.path.isfile(file):
                files.append(file)
        self.files = files

        if self.file_index >= 0 and self.file_index < len(self.files):
            uri = Gst.filename_to_uri(self.files[self.file_index])
            self.player.set_uri(uri)
        #self.player.set_property("prop_gint", 12)

        self.state = None

        self.player.pause()

        ret = app.exec_()

        self.player.dispose()
        self.player = None
Пример #25
0
    def test_marker_load_project(self):
        """Checks marker addition."""
        # TODO: When there is nothing connected to closing-project,
        # the default reply is "False", which means "abort saving". It should mean
        # "OK" to get rid off the handler.  The meaning of the default (False)
        # must be changed
        def closing(unused_manager, unused_project):
            return True

        def loaded_cb(project, timeline):
            mainloop.quit()

        markers = self.timeline.get_marker_list("markers")
        markers.add(10)
        markers.add(20)
        self.assert_markers(markers, [(10, None), (20, None)])

        project_uri = Gst.filename_to_uri(tempfile.NamedTemporaryFile().name)
        self.app.project_manager.save_project(project_uri)
        self.app.project_manager.connect("closing-project", closing)

        self.app.project_manager.close_running_project()
        project = self.app.project_manager.new_blank_project()
        markers = project.ges_timeline.get_marker_list("markers")
        self.assert_markers(markers, [])

        self.app.project_manager.close_running_project()
        project = self.app.project_manager.load_project(project_uri)
        project.connect("loaded", loaded_cb)
        mainloop = common.create_main_loop()
        mainloop.run()
        self.action_log = self.app.action_log

        markers = project.ges_timeline.get_marker_list("markers")
        self.assert_markers(markers, [(10, None), (20, None)])

        ges_markers = markers.get_markers()
        marker1, marker2 = ges_markers

        with self.action_log.started("new comment"):
            marker1.set_string("comment", "comment 1")
        self.assert_markers(markers, [(10, "comment 1"), (20, None)])

        with self.action_log.started("new comment"):
            marker2.set_string("comment", "comment 2")
        self.assert_markers(markers, [(10, "comment 1"), (20, "comment 2")])

        for _ in range(4):
            self.action_log.undo()
            self.assert_markers(markers, [(10, "comment 1"), (20, None)])

            self.action_log.undo()
            self.assert_markers(markers, [(10, None), (20, None)])

            self.action_log.redo()
            self.assert_markers(markers, [(10, "comment 1"), (20, None)])

            self.action_log.redo()
            self.assert_markers(markers, [(10, "comment 1"), (20, "comment 2")])
Пример #26
0
 def play(self, pos=0):
     fname = self.playlist.jump(pos)
     uri = Gst.filename_to_uri(fname)
     playbin = Gst.ElementFactory.make('playbin', 'playbin')
     #bus = playbin.get_bus()
     #bus.add_signal_watch()
     playbin.set_property('uri', uri)
     playbin.set_state(Gst.State.PLAYING)
def created_project_file(xges):
    _, xges_path = tempfile.mkstemp(suffix=".xges")
    with open(xges_path, "w") as f:
        f.write(xges)

    yield Gst.filename_to_uri(os.path.abspath(xges_path))

    os.remove(xges_path)
Пример #28
0
 def _scan_dir(self, folder):
     """Scans the folder recursively and yields the URIs of the files."""
     self.log("Scanning folder %s", folder)
     for path, dirs, files in os.walk(folder):
         if self.stopme.is_set():
             return
         for afile in files:
             yield Gst.filename_to_uri(os.path.join(path, afile))
Пример #29
0
    def create_project_file_from_xges(self, xges):
        unused, xges_path = tempfile.mkstemp(suffix=".xges")
        proj_uri = Gst.filename_to_uri(os.path.abspath(xges_path))

        with open(xges_path, "w") as xges_file:
            xges_file.write(xges)

        return proj_uri
Пример #30
0
 def _scan_dir(self, folder):
     """Scans the folder recursively and yields the URIs of the files."""
     self.log("Scanning folder %s", folder)
     for path, unused_dirs, files in os.walk(folder):
         if self.stopme.is_set():
             return
         for afile in files:
             yield Gst.filename_to_uri(os.path.join(path, afile))
Пример #31
0
    def create_project_file_from_xges(self, app, xges):
        unused, xges_path = tempfile.mkstemp(suffix=".xges")
        proj_uri = Gst.filename_to_uri(os.path.abspath(xges_path))
        app.project_manager.saveProject(uri=proj_uri)

        with open(xges_path, "w") as f:
            f.write(xges)

        return proj_uri
Пример #32
0
 def test_scanning_dir(self):
     """Checks the scanning of the directory URIs."""
     assets_dir = os.path.dirname(os.path.abspath(__file__))
     valid_dir_uri = Gst.filename_to_uri(os.path.join(assets_dir, "samples"))
     uris = [valid_dir_uri]
     received_uris = self._scan(uris)
     self.assertGreater(len(received_uris), 1, received_uris)
     valid_uri = common.get_sample_uri("tears_of_steel.webm")
     self.assertIn(valid_uri, received_uris)
Пример #33
0
    def create_project_file_from_xges(self, app, xges):
        unused, xges_path = tempfile.mkstemp(suffix=".xges")
        proj_uri = Gst.filename_to_uri(os.path.abspath(xges_path))
        app.project_manager.saveProject(uri=proj_uri)

        with open(xges_path, "w") as f:
            f.write(xges)

        return proj_uri
Пример #34
0
    def test_request_relocated_twice(self):
        GES.add_missing_uri_relocation_uri(
            Gst.filename_to_uri(os.path.join(__file__, "../../")), True)
        proj = GES.Project.new()

        asset = proj.create_asset_sync("file:///png.png", GES.UriClip)
        self.assertIsNotNone(asset)
        asset = proj.create_asset_sync("file:///png.png", GES.UriClip)
        self.assertIsNotNone(asset)
Пример #35
0
    def __load(self, uri):

        if os.path.exists(uri):
            direccion = Gst.filename_to_uri(uri)
            self.player.set_property("uri", direccion)

        else:
            if Gst.uri_is_valid(uri):
                self.player.set_property("uri", uri)
Пример #36
0
    def __load(self, uri):

        if os.path.exists(uri):
            direccion = Gst.filename_to_uri(uri)
            self.player.set_property("uri", direccion)

        else:
            if Gst.uri_is_valid(uri):
                self.player.set_property("uri", uri)
Пример #37
0
 def test_scanning_dir(self):
     """Checks the scanning of the directory URIs."""
     assets_dir = os.path.dirname(os.path.abspath(__file__))
     valid_dir_uri = Gst.filename_to_uri(os.path.join(assets_dir, "samples"))
     uris = [valid_dir_uri]
     received_uris = self._scan(uris)
     self.assertGreater(len(received_uris), 1, received_uris)
     valid_uri = common.get_sample_uri("tears_of_steel.webm")
     self.assertIn(valid_uri, received_uris)
Пример #38
0
    def start(self):
        assert len(self.queue) > 0
        fname = self.queue.pop(0)
        self.files.append(fname)
        self.metadata.append({'fname': {fname}})
        uri = Gst.filename_to_uri(fname)

        self.pipe.set_state(Gst.State.NULL)
        self.pipe.get_by_name('decoder').set_property('uri', uri)
        self.pipe.set_state(Gst.State.PLAYING)
def created_video_asset(uri=None, num_bufs=30):
    with tempfile.NamedTemporaryFile(suffix=".ogg") as f:
        if not uri:
            uri = Gst.filename_to_uri(f.name)
        transcoder = GstTranscoder.Transcoder.new(
            "testbin://video,num-buffers=%s" % num_bufs, uri,
            "application/ogg:video/x-theora:audio/x-vorbis")
        transcoder.run()

        yield uri
Пример #40
0
    def __init__(self, parent=0, path=None, rect=sf.Rectangle()):

        self._texture = sf.Texture.create(1,1)
        self._sprite = sf.Sprite(self._texture)
        self.path = path

        #The player
        self.player = Gst.ElementFactory.make("playbin", "player")

        #Config the video output
        binVideo = Gst.Bin()
        videoScale = Gst.ElementFactory.make("videoscale", "videoScale")
        videoScale.set_property("method", 0)
        self.videoFilter = Gst.ElementFactory.make("capsfilter", "videoFiltered")
        videoConvert = Gst.ElementFactory.make("videoconvert", "videoConvert")
        self.videoSink=Gst.ElementFactory.make("appsink", "videoSink")
        self.videoSink.set_property("max_buffers", 8)
        self.videoSink.set_property("drop", True)
        self.videoSink.set_property("sync", True)
        self.videoSink.set_property("async", False)
        self.videoSink.set_property("emit-signals", True)
        self.videoSink.connect("new-preroll", self.initTexture)

        videoCaps = Gst.Caps("video/x-raw, format=(string)RGBx")
        self.videoFilter.set_property("caps", videoCaps)
        self.videoCaps = Gst.Caps(videoCaps.to_string())

        #Add and link the elements to the bin video
        binVideo.add(videoScale)
        binVideo.add(self.videoFilter)
        binVideo.add(videoConvert)
        binVideo.add(self.videoSink)
        videoScale.link(self.videoFilter)
        self.videoFilter.link(videoConvert)
        videoConvert.link(self.videoSink)
        pad = videoScale.get_static_pad("sink")
        ghostPad = Gst.GhostPad.new("sink", pad)
        binVideo.add_pad(ghostPad)

        self.player.set_property("video-sink", binVideo)

        if path:
            self.player.set_property("uri", Gst.filename_to_uri(path))
        self.player.set_state(Gst.State.PLAYING)

        Widget.__init__(self, parent, rect)
        self.pos = rect.position
        self.size = rect.size

        self._speed = 1
        self.requestTime = 10**9*60
        self._canSetSpeed = False

        self.bus = self.player.get_bus()
        self.streamStart = False
Пример #41
0
def quote_uri(uri):
    """
    Encode a URI/path according to RFC 2396, without touching the file:/// part.
    """
    # Split off the "file:///" part, if present.
    parts = urlsplit(uri, allow_fragments=False)
    # Make absolutely sure the string is unquoted before quoting again!
    raw_path = unquote(parts.path)
    # For computing thumbnail md5 hashes in the media library, we must adhere to
    # RFC 2396. It is quite tricky to handle all corner cases, leave it to Gst:
    return Gst.filename_to_uri(raw_path)
Пример #42
0
 def _play_next(self):
     for filepath in self.playlist:
         if not os.path.isfile(filepath):
             print("is not a file:", filepath)
             continue
         filepath = os.path.realpath(filepath)
         self.player.set_property("uri", Gst.filename_to_uri(filepath))
         self.player.set_state(Gst.State.PLAYING)
         print("now playing:", filepath)
         return True
     return False
Пример #43
0
 def __load(self, uri):
     if os.path.exists(uri):
         # Archivo
         direccion = Gst.filename_to_uri(uri)
         self.player.set_property("uri", direccion)
         self.__play()
     else:
         # Streaming
         if Gst.uri_is_valid(uri):
             self.player.set_property("uri", uri)
             self.__play()
Пример #44
0
 def __load(self, uri):
     if os.path.exists(uri):
         # Archivo
         direccion = Gst.filename_to_uri(uri)
         self.player.set_property("uri", direccion)
         self.__play()
     else:
         # Streaming
         if Gst.uri_is_valid(uri):
             self.player.set_property("uri", uri)
             self.__play()
Пример #45
0
    def __init__(self):
        Gst.Pipeline.__init__(self)

        self.music_file = os.path.join("resources", "usmtheme.wav")
        self.music_uri = Gst.filename_to_uri(self.music_file)

        self.playbin = Gst.ElementFactory.make("playbin")
        self.playbin.set_property("uri", self.music_uri)
        self.playbin.set_state(Gst.State.NULL)
        self.playbin.connect("about-to-finish", self.on_about_to_finish)
        self.add(self.playbin)
Пример #46
0
def quote_uri(uri):
    """
    Encode a URI/path according to RFC 2396, without touching the file:/// part.
    """
    # Split off the "file:///" part, if present.
    parts = urlsplit(uri, allow_fragments=False)
    # Make absolutely sure the string is unquoted before quoting again!
    raw_path = unquote(parts.path)
    # For computing thumbnail md5 hashes in the media library, we must adhere to
    # RFC 2396. It is quite tricky to handle all corner cases, leave it to Gst:
    return Gst.filename_to_uri(raw_path)
Пример #47
0
    def add_file(self, filepath):
        '''Method that adds the file to the GtkStore and GESTimeline'''
        idf = len(self.clips)    # id field is a counter

        uri = Gst.filename_to_uri (filepath)   # conver the filepath into a valid URI
        duration, tlobj = self.engine.add_file(uri)    # add the uri to the GESTimeline

        # add to the GtkStore and internal list
        self.timeline_store.append([idf, os.path.basename(filepath), 0,
                                   duration, 0])
        # clips[id] = uri, start, duration, in_point, max_duration, timelineobj
        self.clips[idf] = [uri, 0, duration, 0, duration, tlobj]
Пример #48
0
    def play_next(self):
        try:
            fname = self.queue.pop(0)
        except:
            self.finished.emit()
            return

        uri = Gst.filename_to_uri(fname)

        if not hasattr(self, 'pipe'):
            self.make_pipe()

        self.pipe.set_state(Gst.State.NULL)
        self.pipe.set_property('uri', uri)
        self.pipe.set_state(Gst.State.PLAYING)
Пример #49
0
    def process_next(self):
        try:
            fname = self.queue.pop(0)
            self.files.append(fname)
            self.metadata.append({'fname': fname})
        except IndexError:
            self.pipe.set_state(Gst.State.NULL)
            print('No more files on queue')
            self.finished.emit()
            return

        print('fname:', fname)
        uri = Gst.filename_to_uri(fname)

        self.pipe.set_state(Gst.State.NULL)
        self.pipe.get_by_name('decoder').set_property('uri', uri)
        self.pipe.set_state(Gst.State.PLAYING)
Пример #50
0
 def load(self, uri):
     """
     Carga un archivo o stream en el pipe de Gst.
     """
     
     self.stop()
     self.__reset()
     
     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
         if Gst.uri_is_valid(uri):
             self.player.set_property("uri", uri)
             self.__play()
Пример #51
0
    def get_video_info(self):
        """Return information about the current video.
        """
        uri = self.get_uri()
        if not Gst.uri_is_valid(uri):
            # Let's try to interpret it as a filename
            uri = Gst.filename_to_uri(uri)
        d = GstPbutils.Discoverer()
        try:
            info = d.discover_uri(uri)
        except Exception as e:
            logger.error("Cannot find video info: %s", e.message)
            info = None
        default = {
            'uri': uri,
            'framerate_denom': 1,
            'framerate_num': config.data.preferences['default-fps'],
            'width': 640,
            'height': 480,
            'duration': 0,
        }
        if info is None:
            # Return default data.
            logger.warn("Could not find information about video, using absurd defaults.")
            return default
        if not info.get_video_streams():
            # Could be an audio file.
            default['duration'] = info.get_duration() / Gst.MSECOND
            return default

        stream = info.get_video_streams()[0]
        return {
            'uri': uri,
            'framerate_denom': stream.get_framerate_denom(),
            'framerate_num': stream.get_framerate_num(),
            'width': stream.get_width(),
            'height': stream.get_height(),
            'duration': info.get_duration() / Gst.MSECOND,
        }
Пример #52
0
    def _populate_library(self, uri, artist, album, title, track):
        """
        for track in LIBRARY:
            if artist not already there: add it
            if album not already there: add it as a child of the artist
            add the track title and URI
        """
        # Avoid adding tracks when searching,
        # unless they would be a search result anyway
        search_text = \
            self.builder.get_object("search_entry").get_text().lower()
        if not search_text == "":
            if search_text not in artist.lower() and \
                    search_text not in album.lower() and \
                    search_text not in title.lower():
                return

        # A list of tracks (and URIs) in a dic of albums in a dic of artists:
        if not Gst.uri_is_valid(uri):
            uri = Gst.filename_to_uri(uri)
        if artist not in self.library:
            self.library[artist] = {}
            artist_iter = self.library_store.append(None, [artist])
            if album not in self.library[artist]:
                self.library[artist][album] = []
                self.library_store.append(artist_iter, [album])
        else:
            if album not in self.library[artist]:
                column = 0
                artist_iter = self.library_store.get_iter_first()
                while (artist != \
                      self.library_store.get_value (artist_iter, column)) and \
                      (artist != None):
                    artist_iter = self.library_store.iter_next (artist_iter)

                self.library[artist][album] = []
                self.library_store.append(artist_iter, [album])

        self.library[artist][album].append([title, uri, track])
Пример #53
0
 def _playRenderedFileButtonClickedCb(self, unused_button):
     uri = Gst.filename_to_uri(self.main_render_dialog.outfile)
     Gio.AppInfo.launch_default_for_uri(uri, None)
Пример #54
0
def get_sample_uri(sample):
    tests_dir = os.path.dirname(os.path.abspath(__file__))
    return Gst.filename_to_uri(os.path.join(tests_dir, "samples", sample))
Пример #55
0
            loggy.log('Tagger got ' + str(self.tags))
            #self.player.set_state(Gst.State.NULL)
            #TODO: replace mime types with Gstreamer alternative from Gst.extend
            self.callback()
        elif (message.type == Gst.MessageType.DURATION_CHANGED):   #Gst.MESSAGE_DURATION: ?does this ever happen
            
            self.tags['duration'] = int ((int(self.playbin.query_duration(Gst.Format.TIME)[1]) / Gst.SECOND))
            loggy.warn('got duration huzzah!') #TODO not working at present
        elif (message.type == Gst.MessageType.ERROR):   #Gst.MESSAGE_ERROR:
            err, debug = message.parse_error()
            loggy.warn( "Player GST_MESSAGE_ERROR: " + str(err) + str(debug)) #TODO: sort out unicode
            self.error = str(debug)
            if self.error:
                self.player.set_state(Gst.State.NULL)
                self.__init__()
                self.callback()
        else:
            loggy.warn( "Player GST message unhandled:" + str(message.type))

if __name__ == "__main__":
    # Setting GST_DEBUG_DUMP_DOT_DIR environment variable enables us to have a dotfile generated
    import os
    os.environ["GST_DEBUG_DUMP_DOT_DIR"] = "tmp"
    os.putenv('GST_DEBUG_DUMP_DIR_DIR', 'tmp')
    
    tagger1 = tagger()
    tagger1.load_uri(Gst.filename_to_uri('/home/sam/Music/Darwin Deez/Songs for Imaginative People/04. No Love.mp3'), tagger1.test)
    global testmainloop
    testmainloop = GObject.MainLoop()
    testmainloop.run()
Пример #56
0
 def discover_metadata(self, location):
     file_uri = Gst.filename_to_uri(location)
     info = self.disc.discover_uri_async(file_uri)
Пример #57
0
    decoder.connect('pad-removed', lambda d, p: print('pad removed!'))

    return pipe


Gst.init()

fnames = argv[1:]
pipe = make_pipe()
pipe.set_state(Gst.State.NULL)

tags = []
latest_tag = {}

bus = pipe.get_bus()
bus.connect('message::tag', add_tag)
bus.connect('message::eos', process_next)
bus.connect('message::error', raise_error)

fname = fnames.pop(0)
uri = Gst.filename_to_uri(fname)
latest_tag['uri'] = uri

pipe.get_by_name('decoder').set_property('uri', uri)
pipe.set_state(Gst.State.PLAYING)


loop = GLib.MainLoop()
loop.run()

Пример #58
0
    def display_position(self, scale, value):
        secs = int(value)
        min = secs // 60
        secs %= 60
        return '{0}:{1}'.format(min, secs)


if __name__ == '__main__':
    from sys import argv

    Gtk.init(argv)
    Gst.init(argv)

    w = Gtk.Window()
    
    pb = Gst.ElementFactory.make('playbin', 'playbin')
    
    w.add(PositionWidget(pb))
    w.connect('destroy', lambda w: Gtk.main_quit())

    pb.set_state(Gst.State.NULL)
    pb.set_property('uri', Gst.filename_to_uri(argv[1]))
    pb.set_state(Gst.State.PLAYING)

    w.show_all()
    w.resize(400, 400)

    Gtk.main()

Пример #59
0
 def set_uri(self, uri):
     self.player.set_state(Gst.State.READY)
     uri = Gst.filename_to_uri(uri)
     logging.debug('URI: %s', uri)
     self.player.set_property('uri', uri)