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
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT

use ges_sys;
use gio;
use gio_sys;
use glib;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib::value::SetValueOptional;
use glib::GString;
use glib::Value;
use glib_sys;
use gobject_sys;
use std::boxed::Box as Box_;
use std::mem::transmute;
use std::pin::Pin;
use std::ptr;
use Extractable;

glib_wrapper! {
    /// The Assets in the GStreamer Editing Services represent the resources
    /// that can be used. You can create assets for any type that implements the `Extractable`
    /// interface, for example `GESClips`, `Formatter`, and `TrackElement` do implement it.
    /// This means that assets will represent for example a `GESUriClips`, `BaseEffect` etc,
    /// and then you can extract objects of those types with the appropriate parameters from the asset
    /// using the `AssetExt::extract` method:
    ///
    ///
    /// ```text
    /// GESAsset *effect_asset;
    /// GESEffect *effect;
    ///
    /// // You create an asset for an effect
    /// effect_asset = ges_asset_request (GES_TYPE_EFFECT, "agingtv", NULL);
    ///
    /// // And now you can extract an instance of GESEffect from that asset
    /// effect = GES_EFFECT (ges_asset_extract (effect_asset));
    ///
    /// ```
    ///
    /// In that example, the advantages of having a `Asset` are that you can know what effects
    /// you are working with and let your user know about the avalaible ones, you can add metadata
    /// to the `Asset` through the `MetaContainer` interface and you have a model for your
    /// custom effects. Note that `Asset` management is making easier thanks to the `Project` class.
    ///
    /// Each asset is represented by a pair of `extractable_type` and `id` (string). Actually the `extractable_type`
    /// is the type that implements the `Extractable` interface, that means that for example for a `UriClip`,
    /// the type that implements the `Extractable` interface is `Clip`.
    /// The identifier represents different things depending on the `extractable_type` and you should check
    /// the documentation of each type to know what the ID of `Asset` actually represents for that type. By default,
    /// we only have one `Asset` per type, and the `id` is the name of the type, but this behaviour is overriden
    /// to be more useful. For example, for GESTransitionClips, the ID is the vtype of the transition
    /// you will extract from it (ie crossfade, box-wipe-rc etc..) For `Effect` the ID is the
    /// `bin`-description property of the extracted objects (ie the gst-launch style description of the bin that
    /// will be used).
    ///
    /// Each and every `Asset` is cached into GES, and you can query those with the `ges_list_assets` function.
    /// Also the system will automatically register `GESAssets` for `GESFormatters` and `GESTransitionClips`
    /// and standard effects (actually not implemented yet) and you can simply query those calling:
    ///
    /// ```text
    ///    GList *formatter_assets, *tmp;
    ///
    ///    //  List all  the transitions
    ///    formatter_assets = ges_list_assets (GES_TYPE_FORMATTER);
    ///
    ///    // Print some infos about the formatter GESAsset
    ///    for (tmp = formatter_assets; tmp; tmp = tmp->next) {
    ///      g_print ("Name of the formatter: %s, file extension it produces: %s",
    ///        ges_meta_container_get_string (GES_META_CONTAINER (tmp->data), GES_META_FORMATTER_NAME),
    ///        ges_meta_container_get_string (GES_META_CONTAINER (tmp->data), GES_META_FORMATTER_EXTENSION));
    ///    }
    ///
    ///    g_list_free (transition_assets);
    ///
    /// ```
    ///
    /// You can request the creation of `GESAssets` using either `Asset::request` or
    /// `Asset::request_async`. All the `GESAssets` are cached and thus any asset that has already
    /// been created can be requested again without overhead.
    ///
    /// # Implements
    ///
    /// [`AssetExt`](trait.AssetExt.html), [`glib::object::ObjectExt`](../glib/object/trait.ObjectExt.html)
    pub struct Asset(Object<ges_sys::GESAsset, ges_sys::GESAssetClass, AssetClass>);

    match fn {
        get_type => || ges_sys::ges_asset_get_type(),
    }
}

impl Asset {
    /// Sets an asset from the internal cache as needing reload. An asset needs reload
    /// in the case where, for example, we were missing a GstPlugin to use it and that
    /// plugin has been installed, or, that particular asset content as changed
    /// meanwhile (in the case of the usage of proxies).
    ///
    /// Once an asset has been set as "needs reload", requesting that asset again
    /// will lead to it being re discovered, and reloaded as if it was not in the
    /// cache before.
    /// ## `extractable_type`
    /// The `glib::Type` of the object that can be extracted from the
    ///  asset to be reloaded.
    /// ## `id`
    /// The identifier of the asset to mark as needing reload
    ///
    /// # Returns
    ///
    /// `true` if the asset was in the cache and could be set as needing reload,
    /// `false` otherwise.
    pub fn needs_reload(extractable_type: glib::types::Type, id: &str) -> bool {
        assert_initialized_main_thread!();
        unsafe {
            from_glib(ges_sys::ges_asset_needs_reload(
                extractable_type.to_glib(),
                id.to_glib_none().0,
            ))
        }
    }

    /// Create a `Asset` in the most simple cases, you should look at the `extractable_type`
    /// documentation to see if that constructor can be called for this particular type
    ///
    /// As it is recommanded not to instanciate assets for GESUriClip synchronously,
    /// it will not work with this method, but you can instead use the specific
    /// `UriClipAsset::request_sync` method if you really want to.
    /// ## `extractable_type`
    /// The `glib::Type` of the object that can be extracted from the new asset.
    /// ## `id`
    /// The Identifier or `None`
    ///
    /// # Returns
    ///
    /// A reference to the wanted `Asset` or `None`
    pub fn request(
        extractable_type: glib::types::Type,
        id: Option<&str>,
    ) -> Result<Option<Asset>, glib::Error> {
        assert_initialized_main_thread!();
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ges_sys::ges_asset_request(
                extractable_type.to_glib(),
                id.to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// The `callback` will be called from a running `glib::MainLoop` which is iterating a `glib::MainContext`.
    /// Note that, users should ensure the `glib::MainContext`, since this method will notify
    /// `callback` from the thread which was associated with a thread default
    /// `glib::MainContext` at calling `ges_init`.
    /// For example, if a user wants non-default `glib::MainContext` to be associated
    /// with `callback`, `ges_init` must be called after g_main_context_push_thread_default ()
    /// with custom `glib::MainContext`.
    ///
    /// Request a new `Asset` asyncronously, `callback` will be called when the materail is
    /// ready to be used or if an error occured.
    ///
    /// Example of request of a GESAsset async:
    ///
    /// ```text
    /// // The request callback
    /// static void
    /// asset_loaded_cb (GESAsset * source, GAsyncResult * res, gpointer user_data)
    /// {
    ///   GESAsset *asset;
    ///   GError *error = NULL;
    ///
    ///   asset = ges_asset_request_finish (res, &error);
    ///   if (asset) {
    ///    g_print ("The file: %s is usable as a FileSource",
    ///        ges_asset_get_id (asset));
    ///   } else {
    ///    g_print ("The file: %s is *not* usable as a FileSource because: %s",
    ///        ges_asset_get_id (source), error->message);
    ///   }
    ///
    ///   gst_object_unref (mfs);
    /// }
    ///
    /// // The request:
    /// ges_asset_request_async (GES_TYPE_URI_CLIP, some_uri, NULL,
    ///    (GAsyncReadyCallback) asset_loaded_cb, user_data);
    /// ```
    /// ## `extractable_type`
    /// The `glib::Type` of the object that can be extracted from the
    ///  new asset. The class must implement the `Extractable` interface.
    /// ## `id`
    /// The Identifier of the asset we want to create. This identifier depends of the extractable,
    /// type you want. By default it is the name of the class itself (or `None`), but for example for a
    /// GESEffect, it will be the pipeline description, for a GESUriClip it
    /// will be the name of the file, etc... You should refer to the documentation of the `Extractable`
    /// type you want to create a `Asset` for.
    /// ## `cancellable`
    /// optional `gio::Cancellable` object, `None` to ignore.
    /// ## `callback`
    /// a `GAsyncReadyCallback` to call when the initialization is finished,
    /// Note that the `source` of the callback will be the `Asset`, but you need to
    /// make sure that the asset is properly loaded using the `Asset::request_finish`
    /// method. This asset can not be used as is.
    /// ## `user_data`
    /// The user data to pass when `callback` is called
    pub fn request_async<
        P: IsA<gio::Cancellable>,
        Q: FnOnce(Result<Asset, glib::Error>) + Send + 'static,
    >(
        extractable_type: glib::types::Type,
        id: &str,
        cancellable: Option<&P>,
        callback: Q,
    ) {
        assert_initialized_main_thread!();
        let user_data: Box_<Q> = Box_::new(callback);
        unsafe extern "C" fn request_async_trampoline<
            Q: FnOnce(Result<Asset, glib::Error>) + Send + 'static,
        >(
            _source_object: *mut gobject_sys::GObject,
            res: *mut gio_sys::GAsyncResult,
            user_data: glib_sys::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let ret = ges_sys::ges_asset_request_finish(res, &mut error);
            let result = if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<Q> = Box_::from_raw(user_data as *mut _);
            callback(result);
        }
        let callback = request_async_trampoline::<Q>;
        unsafe {
            ges_sys::ges_asset_request_async(
                extractable_type.to_glib(),
                id.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    pub fn request_async_future(
        extractable_type: glib::types::Type,
        id: &str,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<Asset, glib::Error>> + 'static>> {
        let id = String::from(id);
        Box_::pin(gio::GioFuture::new(&(), move |_obj, send| {
            let cancellable = gio::Cancellable::new();
            Self::request_async(extractable_type, &id, Some(&cancellable), move |res| {
                send.resolve(res);
            });

            cancellable
        }))
    }
}

pub const NONE_ASSET: Option<&Asset> = None;

/// Trait containing all `Asset` methods.
///
/// # Implementors
///
/// [`Asset`](struct.Asset.html), [`Project`](struct.Project.html)
pub trait AssetExt: 'static {
    /// Extracts a new `gobject::Object` from `asset`. The type of the object is
    /// defined by the extractable-type of `asset`, you can check what
    /// type will be extracted from `asset` using
    /// `AssetExt::get_extractable_type`
    ///
    /// # Returns
    ///
    /// A newly created `Extractable`
    fn extract(&self) -> Result<Option<Extractable>, glib::Error>;

    ///
    /// # Returns
    ///
    /// The `glib::Error` of the asset or `None` if
    /// the asset was loaded without issue
    fn get_error(&self) -> Option<glib::Error>;

    /// Gets the type of object that can be extracted from `self`
    ///
    /// # Returns
    ///
    /// the type of object that can be extracted from `self`
    fn get_extractable_type(&self) -> glib::types::Type;

    /// Gets the ID of a `Asset`
    ///
    /// # Returns
    ///
    /// The ID of `self`
    fn get_id(&self) -> Option<GString>;

    ///
    /// # Returns
    ///
    /// The proxy in use for `self`
    fn get_proxy(&self) -> Option<Asset>;

    ///
    /// # Returns
    ///
    /// The `Asset` that is proxied by `self`
    fn get_proxy_target(&self) -> Option<Asset>;

    ///
    /// # Returns
    ///
    /// The list of proxies `self` has. Note that the default asset to be
    /// used is always the first in that list.
    fn list_proxies(&self) -> Vec<Asset>;

    /// A proxying asset is an asset that can substitue the real `self`. For example if you
    /// have a full HD `UriClipAsset` you might want to set a lower resolution (HD version
    /// of the same file) as proxy. Note that when an asset is proxied, calling
    /// `Asset::request` will actually return the proxy asset.
    /// ## `proxy`
    /// The `Asset` that should be used as default proxy for `self` or
    /// `None` if you want to use the currently set proxy. Note that an asset can proxy one and only
    /// one other asset.
    ///
    /// # Returns
    ///
    /// `true` if `proxy` has been set on `self`, `false` otherwise.
    fn set_proxy<P: IsA<Asset>>(&self, proxy: Option<&P>) -> Result<(), glib::error::BoolError>;

    /// Removes `proxy` from the list of known proxies for `self`.
    /// If `proxy` was the current proxy for `self`, stop using it.
    /// ## `proxy`
    /// The `Asset` to stop considering as a proxy for `self`
    ///
    /// # Returns
    ///
    /// `true` if `proxy` was a known proxy for `self`, `false` otherwise.
    fn unproxy<P: IsA<Asset>>(&self, proxy: &P) -> Result<(), glib::error::BoolError>;

    fn set_property_proxy_target<P: IsA<Asset> + SetValueOptional>(&self, proxy_target: Option<&P>);

    fn connect_property_proxy_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;

    fn connect_property_proxy_target_notify<F: Fn(&Self) + 'static>(&self, f: F)
        -> SignalHandlerId;
}

impl<O: IsA<Asset>> AssetExt for O {
    fn extract(&self) -> Result<Option<Extractable>, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ges_sys::ges_asset_extract(self.as_ref().to_glib_none().0, &mut error);
            if error.is_null() {
                Ok(from_glib_none(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    fn get_error(&self) -> Option<glib::Error> {
        unsafe { from_glib_none(ges_sys::ges_asset_get_error(self.as_ref().to_glib_none().0)) }
    }

    fn get_extractable_type(&self) -> glib::types::Type {
        unsafe {
            from_glib(ges_sys::ges_asset_get_extractable_type(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn get_id(&self) -> Option<GString> {
        unsafe { from_glib_none(ges_sys::ges_asset_get_id(self.as_ref().to_glib_none().0)) }
    }

    fn get_proxy(&self) -> Option<Asset> {
        unsafe { from_glib_none(ges_sys::ges_asset_get_proxy(self.as_ref().to_glib_none().0)) }
    }

    fn get_proxy_target(&self) -> Option<Asset> {
        unsafe {
            from_glib_none(ges_sys::ges_asset_get_proxy_target(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn list_proxies(&self) -> Vec<Asset> {
        unsafe {
            FromGlibPtrContainer::from_glib_none(ges_sys::ges_asset_list_proxies(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn set_proxy<P: IsA<Asset>>(&self, proxy: Option<&P>) -> Result<(), glib::error::BoolError> {
        unsafe {
            glib_result_from_gboolean!(
                ges_sys::ges_asset_set_proxy(
                    self.as_ref().to_glib_none().0,
                    proxy.map(|p| p.as_ref()).to_glib_none().0
                ),
                "Failed to set proxy"
            )
        }
    }

    fn unproxy<P: IsA<Asset>>(&self, proxy: &P) -> Result<(), glib::error::BoolError> {
        unsafe {
            glib_result_from_gboolean!(
                ges_sys::ges_asset_unproxy(
                    self.as_ref().to_glib_none().0,
                    proxy.as_ref().to_glib_none().0
                ),
                "Failed to unproxy asset"
            )
        }
    }

    fn set_property_proxy_target<P: IsA<Asset> + SetValueOptional>(
        &self,
        proxy_target: Option<&P>,
    ) {
        unsafe {
            gobject_sys::g_object_set_property(
                self.to_glib_none().0 as *mut gobject_sys::GObject,
                b"proxy-target\0".as_ptr() as *const _,
                Value::from(proxy_target).to_glib_none().0,
            );
        }
    }

    fn connect_property_proxy_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_proxy_trampoline<P, F: Fn(&P) + 'static>(
            this: *mut ges_sys::GESAsset,
            _param_spec: glib_sys::gpointer,
            f: glib_sys::gpointer,
        ) where
            P: IsA<Asset>,
        {
            let f: &F = &*(f as *const F);
            f(&Asset::from_glib_borrow(this).unsafe_cast())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::proxy\0".as_ptr() as *const _,
                Some(transmute(notify_proxy_trampoline::<Self, F> as usize)),
                Box_::into_raw(f),
            )
        }
    }

    fn connect_property_proxy_target_notify<F: Fn(&Self) + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn notify_proxy_target_trampoline<P, F: Fn(&P) + 'static>(
            this: *mut ges_sys::GESAsset,
            _param_spec: glib_sys::gpointer,
            f: glib_sys::gpointer,
        ) where
            P: IsA<Asset>,
        {
            let f: &F = &*(f as *const F);
            f(&Asset::from_glib_borrow(this).unsafe_cast())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::proxy-target\0".as_ptr() as *const _,
                Some(transmute(
                    notify_proxy_target_trampoline::<Self, F> as usize,
                )),
                Box_::into_raw(f),
            )
        }
    }
}