-
Notifications
You must be signed in to change notification settings - Fork 289
/
xges.py
3783 lines (3491 loc) · 149 KB
/
xges.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright Contributors to the OpenTimelineIO project
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
"""OpenTimelineIO GStreamer Editing Services XML Adapter."""
import re
import os
import warnings
import numbers
try:
from urllib.parse import quote
from urllib.parse import unquote
from urllib.parse import urlparse
from urllib.parse import parse_qs
except ImportError: # python2
from urllib import quote
from urllib import unquote
from urlparse import urlparse
from urlparse import parse_qs
from fractions import Fraction
from xml.etree import ElementTree
from xml.dom import minidom
import itertools
import colorsys
import opentimelineio as otio
META_NAMESPACE = "XGES"
_TRANSITION_MAP = {
"crossfade": otio.schema.TransitionTypes.SMPTE_Dissolve
}
# Two way map
_TRANSITION_MAP.update(dict([(v, k) for k, v in _TRANSITION_MAP.items()]))
class XGESReadError(otio.exceptions.OTIOError):
"""An incorrectly formatted xges string."""
class UnhandledValueError(otio.exceptions.OTIOError):
"""Received value is not handled."""
def __init__(self, name, value):
otio.exceptions.OTIOError.__init__(
self, "Unhandled value {!r} for {}.".format(value, name))
class InvalidValueError(otio.exceptions.OTIOError):
"""Received value is invalid."""
def __init__(self, name, value, expect):
otio.exceptions.OTIOError.__init__(
self, "Invalid value {!r} for {}. Expect {}.".format(
value, name, expect))
class DeserializeError(otio.exceptions.OTIOError):
"""Receive an incorrectly serialized value."""
MAX_LEN = 20
def __init__(self, read, reason):
if len(read) > self.MAX_LEN:
read = read[:self.MAX_LEN] + "..."
otio.exceptions.OTIOError.__init__(
self, "Could not deserialize the string ({}) because it {}."
"".format(read, reason))
class UnhandledOtioError(otio.exceptions.OTIOError):
"""Received otio object is not handled."""
def __init__(self, otio_obj):
otio.exceptions.OTIOError.__init__(
self, "Unhandled otio schema {}.".format(
otio_obj.schema_name()))
def _show_ignore(msg):
"""Tell user we found an error with 'msg', but we are ignoring it."""
warnings.warn(msg + ".\nIGNORING.", stacklevel=2)
def _show_otio_not_supported(otio_obj, effect):
"""
Tell user that we do not properly support an otio type for 'otio_obj'.
'effect' is a message to the user about what will happen instead.
"""
warnings.warn(
"The schema {} is not currently supported.\n{}.".format(
otio_obj.schema_name(), effect),
stacklevel=2)
def _wrong_type_for_arg(val, expect_type_name, arg_name):
"""
Raise exception in response to the 'arg_name' argument being given the
value 'val', when we expected it to be of the type corresponding to
'expect_type_name'.
"""
raise TypeError(
"Expect a {} type for the '{}' argument. Received a {} type."
"".format(expect_type_name, arg_name, type(val).__name__))
def _force_gst_structure_name(struct, struct_name, owner=""):
"""
If the GstStructure 'struct' does not have the given 'struct_name',
change its name to match with a warning.
'owner' is used for the message to tell the user which object the
structure belongs to.
"""
if struct.name != struct_name:
if owner:
start = "{}'s".format(owner)
else:
start = "The"
warnings.warn(
"{} structure name is \"{}\" rather than the expected \"{}\"."
"\nOverwriting with the expected name.".format(
start, struct.name, struct_name))
struct.name = struct_name
# TODO: remove unicode_to_str once python2 has ended:
def unicode_to_str(value):
"""If python2, returns unicode as a utf8 str"""
if type(value) is not str and isinstance(value, type(u"")):
value = value.encode("utf8")
return value
class GESTrackType:
"""
Class for storing the GESTrackType types, and converting them to
the otio.schema.TrackKind.
"""
UNKNOWN = 1 << 0
AUDIO = 1 << 1
VIDEO = 1 << 2
TEXT = 1 << 3
CUSTOM = 1 << 4
OTIO_TYPES = (VIDEO, AUDIO)
NON_OTIO_TYPES = (UNKNOWN, TEXT, CUSTOM)
ALL_TYPES = OTIO_TYPES + NON_OTIO_TYPES
@staticmethod
def to_otio_kind(track_type):
"""
Convert from GESTrackType 'track_type' to otio.schema.TrackKind.
"""
if track_type == GESTrackType.AUDIO:
return otio.schema.TrackKind.Audio
elif track_type == GESTrackType.VIDEO:
return otio.schema.TrackKind.Video
raise UnhandledValueError("track_type", track_type)
@staticmethod
def from_otio_kind(*otio_kinds):
"""
Convert the list of otio.schema.TrackKind 'otio_kinds' to an
GESTrackType.
"""
track_type = 0
for kind in otio_kinds:
if kind == otio.schema.TrackKind.Audio:
track_type |= GESTrackType.AUDIO
elif kind == otio.schema.TrackKind.Video:
track_type |= GESTrackType.VIDEO
else:
raise UnhandledValueError("track kind", kind)
return track_type
GST_SECOND = 1000000000
class XGES:
"""
Class for converting an xges string, which stores GES projects, to an
otio.schema.Timeline.
"""
# The xml elements found in the given xges are converted as:
#
# + A <ges>, its <project>, its <timeline> and its <track>s are
# converted to an otio.schema.Stack.
# + A GESMarker on the <timeline> is converted to an
# otio.schema.Marker.
# + A <layer> is converted to otio.schema.Track, one for each track
# type found.
# + A <clip> + <asset> is converted to an otio.schema.Composable, one
# for each track type found:
# + A GESUriClip becomes an otio.schema.Clip with an
# otio.schema.ExternalReference.
# + A GESUriClip that references a sub-project instead becomes an
# otio.schema.Stack of the sub-project.
# + A GESTransitionClip becomes an otio.schema.Transition.
# + An <effect> on a uriclip is converted to an otio.schema.Effect.
# + An <asset> is wrapped
#
# TODO: Some parts of the xges are not converted.
# <clip> types to support:
# + GESTestClip, probably to a otio.schema.Clip with an
# otio.schema.GeneratorReference
# + GESTitleClip, maybe to a otio.schema.Clip with an
# otio.schema.MissingReference?
# + GESOverlayClip, difficult to convert since otio.schema.Clips can
# not overlap generically. Maybe use a separate otio.schema.Track?
# + GESBaseEffectClip, same difficulty.
#
# Also, for <clip>, we're missing
# + <source>, which contains <binding> elements that describe the
# property bindings.
#
# For <project>, we're missing:
# + <encoding-profile>, not vital.
#
# For <asset>, we're missing:
# + <stream-info>.
#
# For <timeline>, we're missing:
# + <groups>, and its children <group> elements.
#
# For <effect>, we're missing:
# + <binding>, same as the missing <clip> <binding>
def __init__(self, ges_obj):
"""
'ges_obj' should be the root of the xges xml tree (called "ges").
If it is not an ElementTree, it will first be parsed as a string
to ElementTree.
"""
if not isinstance(ges_obj, ElementTree.Element):
ges_obj = ElementTree.fromstring(ges_obj)
if ges_obj.tag != "ges":
raise XGESReadError(
"The root element for the received xml is tagged as "
"{} rather than the expected 'ges' for xges".format(
ges_obj.tag))
self.ges_xml = ges_obj
self.rate = 25.0
@staticmethod
def _findall(xmlelement, path):
"""
Return a list of all child xml elements found under 'xmlelement'
at 'path'.
"""
found = xmlelement.findall(path)
if found is None:
return []
return found
@classmethod
def _findonly(cls, xmlelement, path, allow_none=False):
"""
Find exactly one child xml element found under 'xmlelement' at
'path' and return it. If we find multiple, we raise an error. If
'allow_none' is False, we also error when we find no element,
otherwise we can return None.
"""
found = cls._findall(xmlelement, path)
if allow_none and not found:
return None
if len(found) != 1:
raise XGESReadError(
"Found {:d} xml elements under the path {} when only "
"one was expected.".format(len(found), path))
return found[0]
@staticmethod
def _get_attrib(xmlelement, key, expect_type):
"""
Get the xml attribute at 'key', try to convert it to the python
'expect_type', and return it. Otherwise, raise an error.
"""
val = xmlelement.get(key)
if val is None:
raise XGESReadError(
"The xges {} element is missing the {} "
"attribute.".format(xmlelement.tag, key))
try:
val = expect_type(val)
except (ValueError, TypeError):
raise XGESReadError(
"The xges {} element '{}' attribute has the value {}, "
"which is not of the expected {} type.".format(
xmlelement.tag, key, val, expect_type.__name__))
return val
@staticmethod
def _get_structure(xmlelement, attrib_name, struct_name=None):
"""
Try to find the GstStructure with the name 'struct_name' under
the 'attrib_name' attribute of 'xmlelement'. If we can not do so
we return an empty structure with the same name. If no
'struct_name' is given, we use the 'attrib_name'.
"""
if struct_name is None:
struct_name = attrib_name
read_struct = xmlelement.get(attrib_name, struct_name + ";")
try:
struct = GstStructure.new_from_str(read_struct)
except DeserializeError as err:
_show_ignore(
"The {} attribute of {} could not be read as a "
"GstStructure:\n{!s}".format(
struct_name, xmlelement.tag, err))
return GstStructure(struct_name)
_force_gst_structure_name(struct, struct_name, xmlelement.tag)
return struct
@classmethod
def _get_properties(cls, xmlelement):
"""Get the properties GstStructure from an xges 'xmlelement'."""
return cls._get_structure(xmlelement, "properties")
@classmethod
def _get_metadatas(cls, xmlelement):
"""Get the metadatas GstStructure from an xges 'xmlelement'."""
return cls._get_structure(xmlelement, "metadatas")
@classmethod
def _get_children_properties(cls, xmlelement):
"""
Get the children-properties GstStructure from an xges
'xmlelement'.
"""
return cls._get_structure(
xmlelement, "children-properties", "properties")
@classmethod
def _get_from_properties(
cls, xmlelement, fieldname, expect_type, default=None):
"""
Try to get the property under 'fieldname' of the 'expect_type'
type name from the properties GstStructure of an xges element.
Otherwise return 'default'.
"""
structure = cls._get_properties(xmlelement)
return structure.get_typed(fieldname, expect_type, default)
@classmethod
def _get_from_metadatas(
cls, xmlelement, fieldname, expect_type, default=None):
"""
Try to get the metadata under 'fieldname' of the 'expect_type'
type name from the metadatas GstStructure of an xges element.
Otherwise return 'default'.
"""
structure = cls._get_metadatas(xmlelement)
return structure.get_typed(fieldname, expect_type, default)
@staticmethod
def _get_from_caps(caps, fieldname, structname=None, default=None):
"""
Extract a GstCaps from the 'caps' string and search it for the
first GstStructure (optionally, with the 'structname' name) with
the 'fieldname' field, and return its value. Otherwise, return
'default'.
"""
try:
with warnings.catch_warnings():
# unknown types may raise a warning. This will
# usually be irrelevant since we are searching for
# a specific field
caps = GstCaps.new_from_str(caps)
except DeserializeError as err:
_show_ignore(
"Failed to read the fields in the caps ({}):\n\t"
"{!s}".format(caps, err))
else:
for struct in caps:
if structname is not None:
if struct.name != structname:
continue
# use below method rather than fields.get(fieldname) to
# allow us to want any value back, including None
for key in struct.fields:
if key == fieldname:
return struct[key]
return default
def _set_rate_from_timeline(self, timeline):
"""
Set the rate of 'self' to the rate found in the video track
element of the xges 'timeline'.
"""
video_track = timeline.find("./track[@track-type='4']")
if video_track is None:
return
res_caps = self._get_from_properties(
video_track, "restriction-caps", "string")
if res_caps is None:
return
rate = self._get_from_caps(res_caps, "framerate")
if rate is None:
return
try:
rate = Fraction(rate)
except (ValueError, TypeError):
_show_ignore("Read a framerate that is not a fraction")
else:
self.rate = float(rate)
def _to_rational_time(self, ns_timestamp):
"""
Converts the GstClockTime 'ns_timestamp' (nanoseconds as an int)
to an otio.opentime.RationalTime object.
"""
return otio.opentime.RationalTime(
(float(ns_timestamp) * self.rate) / float(GST_SECOND),
self.rate
)
@staticmethod
def _add_to_otio_metadata(otio_obj, key, val, parent_key=None):
"""
Add the data 'val' to the metadata of 'otio_obj' under 'key'.
If 'parent_key' is given, it is instead added to the
sub-dictionary found under 'parent_key'.
The needed dictionaries are automatically created.
"""
xges_dict = otio_obj.metadata.get(META_NAMESPACE)
if xges_dict is None:
otio_obj.metadata[META_NAMESPACE] = {}
xges_dict = otio_obj.metadata[META_NAMESPACE]
if parent_key is None:
_dict = xges_dict
else:
sub_dict = xges_dict.get(parent_key)
if sub_dict is None:
xges_dict[parent_key] = {}
sub_dict = xges_dict[parent_key]
_dict = sub_dict
_dict[key] = val
@classmethod
def _add_properties_and_metadatas_to_otio(
cls, otio_obj, element, parent_key=None):
"""
Add the properties and metadatas attributes of the xges 'element'
to the metadata of 'otio_obj', as GstStructures. Optionally under
the 'parent_key'.
"""
cls._add_to_otio_metadata(
otio_obj, "properties",
cls._get_properties(element), parent_key)
cls._add_to_otio_metadata(
otio_obj, "metadatas",
cls._get_metadatas(element), parent_key)
@classmethod
def _add_children_properties_to_otio(
cls, otio_obj, element, parent_key=None):
"""
Add the children-properties attribute of the xges 'element' to the
metadata of 'otio_obj', as GstStructures. Optionally under the
'parent_key'.
"""
cls._add_to_otio_metadata(
otio_obj, "children-properties",
cls._get_children_properties(element), parent_key)
def to_otio(self):
"""
Convert the xges given to 'self' to an otio.schema.Timeline
object, and returns it.
"""
otio_timeline = otio.schema.Timeline()
project = self._fill_otio_stack_from_ges(otio_timeline.tracks)
otio_timeline.name = self._get_from_metadatas(
project, "name", "string", "")
return otio_timeline
def _fill_otio_stack_from_ges(self, otio_stack):
"""
Converts the top <ges> element given to 'self' into an
otio.schema.Stack by setting the metadata of the given
'otio_stack', and filling it with otio.schema.Tracks.
Returns the <project> element found under <ges>.
"""
project = self._findonly(self.ges_xml, "./project")
timeline = self._findonly(project, "./timeline")
self._set_rate_from_timeline(timeline)
self._add_timeline_markers_to_otio_stack(timeline, otio_stack)
tracks = self._findall(timeline, "./track")
tracks.sort(
key=lambda trk: self._get_attrib(trk, "track-id", int))
xges_tracks = []
for track in tracks:
try:
caps = GstCaps.new_from_str(
self._get_attrib(track, "caps", str))
except DeserializeError as err:
_show_ignore(
"Could not deserialize the caps attribute for "
"track {:d}:\n{!s}".format(
self._get_attrib(track, "track-id", int), err))
else:
xges_tracks.append(
XgesTrack(
caps,
self._get_attrib(track, "track-type", int),
self._get_properties(track),
self._get_metadatas(track)))
self._add_properties_and_metadatas_to_otio(
otio_stack, project, "project")
self._add_properties_and_metadatas_to_otio(
otio_stack, timeline, "timeline")
self._add_to_otio_metadata(otio_stack, "tracks", xges_tracks)
self._add_layers_to_otio_stack(timeline, otio_stack)
return project
def _add_timeline_markers_to_otio_stack(
self, timeline, otio_stack):
"""
Add the markers found in the GESMarkerlList metadata of the xges
'timeline' to 'otio_stack' as otio.schema.Markers.
"""
metadatas = self._get_metadatas(timeline)
for marker_list in metadatas.values_of_type("GESMarkerList"):
for marker in marker_list:
if marker.is_colored():
otio_stack.markers.append(
self._otio_marker_from_ges_marker(marker))
def _otio_marker_from_ges_marker(self, ges_marker):
"""Convert the GESMarker 'ges_marker' to an otio.schema.Marker."""
with warnings.catch_warnings():
# don't worry about not being string typed
name = ges_marker.metadatas.get_typed("comment", "string", "")
marked_range = otio.opentime.TimeRange(
self._to_rational_time(ges_marker.position),
self._to_rational_time(0))
return otio.schema.Marker(
name=name, color=ges_marker.get_nearest_otio_color(),
marked_range=marked_range)
def _add_layers_to_otio_stack(self, timeline, otio_stack):
"""
Add the <layer> elements under the xges 'timeline' to 'otio_stack'
as otio.schema.Tracks.
"""
sort_otio_tracks = []
for layer in self._findall(timeline, "./layer"):
priority = self._get_attrib(layer, "priority", int)
for otio_track in self._otio_tracks_from_layer_clips(layer):
sort_otio_tracks.append((otio_track, priority))
sort_otio_tracks.sort(key=lambda ent: ent[1], reverse=True)
# NOTE: smaller priority is later in the list
for otio_track in (ent[0] for ent in sort_otio_tracks):
otio_stack.append(otio_track)
def _otio_tracks_from_layer_clips(self, layer):
"""
Convert the xges 'layer' into otio.schema.Tracks, one for each
otio.schema.TrackKind.
"""
otio_tracks = []
for track_type in GESTrackType.OTIO_TYPES:
otio_items, otio_transitions = \
self._create_otio_composables_from_layer_clips(
layer, track_type)
if not otio_items and not otio_transitions:
continue
otio_track = otio.schema.Track()
otio_track.kind = GESTrackType.to_otio_kind(track_type)
self._add_otio_composables_to_otio_track(
otio_track, otio_items, otio_transitions)
self._add_properties_and_metadatas_to_otio(otio_track, layer)
otio_tracks.append(otio_track)
for track_type in GESTrackType.NON_OTIO_TYPES:
layer_clips = self._layer_clips_for_track_type(
layer, track_type)
if layer_clips:
_show_ignore(
"The xges layer of priority {:d} contains clips "
"{!s} of the unhandled track type {:d}".format(
self._get_attrib(layer, "priority", int),
[self._get_name(clip) for clip in layer_clips],
track_type))
return otio_tracks
@classmethod
def _layer_clips_for_track_type(cls, layer, track_type):
"""
Return the <clip> elements found under the xges 'layer' whose
"track-types" overlaps with track_type.
"""
return [
clip for clip in cls._findall(layer, "./clip")
if cls._get_attrib(clip, "track-types", int) & track_type]
@classmethod
def _clip_effects_for_track_type(cls, clip, track_type):
"""
Return the <effect> elements found under the xges 'clip' whose
"track-type" matches 'track_type'.
"""
return [
effect for effect in cls._findall(clip, "./effect")
if cls._get_attrib(effect, "track-type", int) & track_type]
# NOTE: the attribute is 'track-type', not 'track-types'
def _create_otio_composables_from_layer_clips(
self, layer, track_type):
"""
For all the <clip> elements found in the xges 'layer' that overlap
the given 'track_type', attempt to create an
otio.schema.Composable.
Note that the created composables do not have their timing set.
Instead, the timing information of the <clip> is stored in a
dictionary alongside the composable.
Returns a list of otio item dictionaries, and a list of otio
transition dictionaries.
Within the item dictionary:
"item" points to the actual otio.schema.Item,
"start", "duration" and "inpoint" give the corresponding
<clip> attributes.
Within the transition dictionary:
"transition" points to the actual otio.schema.Transition,
"start" and "duration" give the corresponding <clip>
attributes.
"""
otio_transitions = []
otio_items = []
for clip in self._layer_clips_for_track_type(layer, track_type):
clip_type = self._get_attrib(clip, "type-name", str)
start = self._get_attrib(clip, "start", int)
inpoint = self._get_attrib(clip, "inpoint", int)
duration = self._get_attrib(clip, "duration", int)
otio_composable = None
name = self._get_name(clip)
if clip_type == "GESTransitionClip":
otio_composable = self._otio_transition_from_clip(clip)
elif clip_type == "GESUriClip":
otio_composable = self._otio_item_from_uri_clip(clip)
else:
# TODO: support other clip types
# maybe represent a GESTitleClip as a gap, with the text
# in the metadata?
# or as a clip with a MissingReference?
_show_ignore(
"The xges clip {} is of an unsupported {} type"
"".format(name, clip_type))
continue
otio_composable.name = name
self._add_properties_and_metadatas_to_otio(
otio_composable, clip, "clip")
self._add_clip_effects_to_otio_composable(
otio_composable, clip, track_type)
if isinstance(otio_composable, otio.schema.Transition):
otio_transitions.append({
"transition": otio_composable,
"start": start, "duration": duration})
elif isinstance(otio_composable, otio.core.Item):
otio_items.append({
"item": otio_composable, "start": start,
"inpoint": inpoint, "duration": duration})
return otio_items, otio_transitions
def _add_clip_effects_to_otio_composable(
self, otio_composable, clip, track_type):
"""
Add the <effect> elements found under the xges 'clip' of the
given 'track_type' to the 'otio_composable'.
"""
clip_effects = self._clip_effects_for_track_type(
clip, track_type)
if not isinstance(otio_composable, otio.core.Item):
if clip_effects:
_show_ignore(
"The effects {!s} found under the xges clip {} can "
"not be represented".format(
[self._get_attrib(effect, "asset-id", str)
for effect in clip_effects],
self._get_name(clip)))
return
for effect in clip_effects:
effect_type = self._get_attrib(effect, "type-name", str)
if effect_type == "GESEffect":
otio_composable.effects.append(
self._otio_effect_from_effect(effect))
else:
_show_ignore(
"The {} effect under the xges clip {} is of an "
"unsupported {} type".format(
self._get_attrib(effect, "asset-id", str),
self._get_name(clip), effect_type))
def _otio_effect_from_effect(self, effect):
"""Convert the xges 'effect' into an otio.schema.Effect."""
bin_desc = self._get_attrib(effect, "asset-id", str)
# TODO: a smart way to convert the bin description into a standard
# effect name that is recognised by other adapters
# e.g. a bin description can also contain parameter values, such
# as "agingtv scratch-lines=20"
otio_effect = otio.schema.Effect(effect_name=bin_desc)
self._add_to_otio_metadata(
otio_effect, "bin-description", bin_desc)
self._add_properties_and_metadatas_to_otio(otio_effect, effect)
self._add_children_properties_to_otio(otio_effect, effect)
return otio_effect
@staticmethod
def _item_gap(second, first):
"""
Calculate the time gap between the start time of 'second' and the
end time of 'first', each of which are item dictionaries as
returned by _create_otio_composables_from_layer_clips.
If 'first' is None, we return the gap between the start of the
timeline and the start of 'second'.
If 'second' is None, we return 0 to indicate no gap.
"""
if second is None:
return 0
if first is None:
return second["start"]
return second["start"] - first["start"] - first["duration"]
def _add_otio_composables_to_otio_track(
self, otio_track, items, transitions):
"""
Insert 'items' and 'transitions' into 'otio_track' with correct
timings.
'items' and 'transitions' should be a list of dictionaries, as
returned by _create_otio_composables_from_layer_clips.
Specifically, the item dictionaries should contain an un-parented
otio.schema.Item under the "item" key, and GstClockTimes under the
"start", "duration" and "inpoint" keys, corresponding to the times
found under the corresponding xges <clip>.
This method should set the correct source_range for the item
before inserting it into 'otio_track'.
The transitions dictionaries should contain an un-parented
otio.schema.Transition under the "transition" key, and
GstClockTimes under the "start" and "duration" keys, corresponding
to the times found under the corresponding xges <clip>.
Whenever an overlap of non-transition <clip>s is detected, the
transition that matches the overlap will be searched for in
'transitions', removed from the list, and the corresponding otio
transition will be inserted in 'otio_track' with the correct
timings.
"""
# otio tracks do not allow items to overlap
# in contrast an xges layer will let clips overlap, and their
# overlap may have some corresponding transition associated with
# it. Diagrammatically, we want to translate:
# _ _ _ _ _ _ ____________ _ _ _ _ _ _ ____________ _ _ _ _ _ _
# + + + +
# xges-clip-0 | |xges-clip-1| xges-clip-2
# _ _ _ _ _ _+____________+_ _ _ _ _ _+____________+_ _ _ _ _ _
# .------------. .------------.
# :xges-trans-1: :xges-trans-2:
# '------------' '------------'
# -----------> <----------------------------------->
# start duration (on xges-clip-1)
# -----------> <---------->
# start duration (on xges-trans-1)
# ------------------------------------> <---------->
# start duration (on xges-trans-2)
#
# . . . . ..........................................
# . Not : :
# . Avail. : xges-asset for xges-clip-1 :
# . . . . .:.......................................:
# <--------->
# inpoint (on xges-clip-1)
# <---------------------------------------------->
# duration (on xges-asset)
#
# to:
# _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
# + +
# otio-clip-0 | otio-clip-1 | otio-clip-2
# _ _ _ _ _ _ _ _ _+_ _ _ _ _ _ _ _ _ _ _ _ _+_ _ _ _ _ _ _ _ _
# .------------. .------------.
# :otio-trans-1: :otio-trans-2:
# '------------' '------------'
# <---> <----> <----> <--->
# .in_offset .out_offset .in_offset .out_offset
#
# . . . . ..........................................
# . Not : :
# . Avail. : otio-med-ref for otio-clip-1 :
# . . . . .:.......................................:
# <---------------> <----------------------->
# s_range.start_time s_range.duration (on otio-clip-1)
# <------> <------------------------------------->
# a_range.start_time a_range.duration (on otio-med-ref)
#
# where:
# s_range = source_range
# a_range = available_range
#
# so:
# for otio-trans-1:
# .in_offset + .out_offset = xges-trans-1-duration
# for otio-clip-1:
# s_range.start_time = xges-clip-1-inpoint
# + otio-trans-1.in_offset
# s_range.duration = xges-clip-1-duration
# - otio-trans-1.in_offset
# - otio-trans-2.out_offset
#
#
# We also want to insert any otio-gaps when the first xges clip
# does not start at zero, or if there is an implied gap between
# xges clips
items.sort(key=lambda ent: ent["start"])
prev_otio_transition = None
for item, prev_item, next_item in zip(
items, [None] + items, items[1:] + [None]):
otio_start = self._to_rational_time(item["inpoint"])
otio_duration = self._to_rational_time(item["duration"])
otio_transition = None
pre_gap = self._item_gap(item, prev_item)
post_gap = self._item_gap(next_item, item)
if pre_gap < 0:
# overlap: transition should have been
# handled by the previous iteration
otio_start += prev_otio_transition.in_offset
otio_duration -= prev_otio_transition.in_offset
# start is delayed until the otio transition's position
# duration looses what start gains
elif pre_gap > 0:
otio_track.append(self._create_otio_gap(pre_gap))
if post_gap < 0:
# overlap
duration = -post_gap
transition = [
t for t in transitions
if t["start"] == next_item["start"] and
t["duration"] == duration]
if len(transition) == 1:
otio_transition = transition[0]["transition"]
transitions.remove(transition[0])
# remove transitions once they have been extracted
elif len(transition) == 0:
# NOTE: this can happen if auto-transition is false
# for the xges timeline
otio_transition = self._default_otio_transition()
else:
raise XGESReadError(
"Found {:d} {!s} transitions with start={:d} "
"and duration={:d} within a single layer".format(
len(transition), otio_track.kind,
next_item["start"], duration))
half = float(duration) / 2.0
otio_transition.in_offset = self._to_rational_time(half)
otio_transition.out_offset = self._to_rational_time(half)
otio_duration -= otio_transition.out_offset
# trim the end of the clip, which is where the otio
# transition starts
otio_item = item["item"]
otio_item.source_range = otio.opentime.TimeRange(
otio_start, otio_duration)
otio_track.append(otio_item)
if otio_transition:
otio_track.append(otio_transition)
prev_otio_transition = otio_transition
if transitions:
raise XGESReadError(
"xges layer contains {:d} {!s} transitions that could "
"not be associated with any clip overlap".format(
len(transitions), otio_track.kind))
@classmethod
def _get_name(cls, element):
"""
Get the "name" of the xges 'element' found in its properties, or
return a generic name if none is found.
"""
name = cls._get_from_properties(element, "name", "string")
if not name:
name = element.tag
return name
def _otio_transition_from_clip(self, clip):
"""
Convert the xges transition 'clip' into an otio.schema.Transition.
Note that the timing of the object is not set.
"""
return otio.schema.Transition(
transition_type=_TRANSITION_MAP.get(
self._get_attrib(clip, "asset-id", str),
otio.schema.TransitionTypes.Custom))
@staticmethod
def _default_otio_transition():
"""
Create a default otio.schema.Transition.
Note that the timing of the object is not set.
"""
return otio.schema.Transition(
transition_type=otio.schema.TransitionTypes.SMPTE_Dissolve)
def _otio_item_from_uri_clip(self, clip):
"""
Convert the xges uri 'clip' into an otio.schema.Item.
Note that the timing of the object is not set.
If 'clip' is found to reference a sub-project, this will return
an otio.schema.Stack of the sub-project, also converted from the
found <ges> element.
Otherwise, an otio.schema.Clip with an
otio.schema.ExternalReference is returned.
"""
asset_id = self._get_attrib(clip, "asset-id", str)
sub_project_asset = self._asset_by_id(asset_id, "GESTimeline")
if sub_project_asset is not None:
# this clip refers to a sub project
otio_item = otio.schema.Stack()
sub_ges = XGES(self._findonly(sub_project_asset, "./ges"))
sub_ges._fill_otio_stack_from_ges(otio_item)
self._add_properties_and_metadatas_to_otio(
otio_item, sub_project_asset, "sub-project-asset")
# NOTE: we include asset-id in the metadata, so that two
# stacks that refer to a single sub-project will not be
# split into separate assets when converting from
# xges->otio->xges
self._add_to_otio_metadata(otio_item, "asset-id", asset_id)
uri_clip_asset = self._asset_by_id(asset_id, "GESUriClip")
if uri_clip_asset is None:
_show_ignore(
"Did not find the expected GESUriClip asset with "
"the id {}".format(asset_id))
else:
self._add_properties_and_metadatas_to_otio(
otio_item, uri_clip_asset, "uri-clip-asset")
else:
otio_item = otio.schema.Clip(
media_reference=self._otio_reference_from_id(asset_id))
return otio_item
def _create_otio_gap(self, gst_duration):
"""
Create a new otio.schema.Gap with the given GstClockTime
'gst_duration' duration.
"""
source_range = otio.opentime.TimeRange(
self._to_rational_time(0),
self._to_rational_time(gst_duration))
return otio.schema.Gap(source_range=source_range)
def _otio_image_sequence_from_url(self, ref_url):
# TODO: Add support for missing policy
params = {}
fname, ext = os.path.splitext(unquote(os.path.basename(ref_url.path)))
index_format = re.findall(r"%\d+d", fname)
if index_format:
params["frame_zero_padding"] = int(index_format[-1][2:-1])
fname = fname[0:-len(index_format[-1])]
url_params = parse_qs(ref_url.query)
if "framerate" in url_params:
rate = params["rate"] = float(Fraction(url_params["framerate"][-1]))
if "start-index" in url_params and "stop-index" in url_params:
start = int(url_params["start-index"][-1])
stop = int(url_params["stop-index"][-1])
params["available_range"] = otio.opentime.TimeRange(
otio.opentime.RationalTime(int(start), rate),
otio.opentime.RationalTime(int(stop - start), rate),
)
else:
rate = params["rate"] = float(30)
return otio.schema.ImageSequenceReference(
"file://" + os.path.dirname(ref_url.path),
fname, ext, **params)
def _otio_reference_from_id(self, asset_id):
"""