-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathabc.py
More file actions
1078 lines (900 loc) · 42.4 KB
/
abc.py
File metadata and controls
1078 lines (900 loc) · 42.4 KB
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
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Generator, Sequence
from typing_extensions import Literal, Self, get_args
from .. import filtergraph as fgb
from .exceptions import FiltergraphMismatchError, FiltergraphPadNotFoundError
from .GraphLinks import GraphLinks
from .typing import JOIN_HOW, PAD_INDEX
__all__ = ["FilterGraphObject"]
class FilterGraphObject(ABC):
@staticmethod
def relabel_duplicates(*fgs: tuple[FilterGraphObject]): ...
@property
def links(self) -> GraphLinks | None:
"""filtergraph link definition only if filtergraph"""
return None
def get_num_pads(self, input: bool) -> int:
"""get the number of available pads at input or output
:param input: True to get the input count, False for the output count.
"""
return self.get_num_inputs() if input else self.get_num_outputs()
@abstractmethod
def copy(self) -> Self:
"""(deep) copy filtergraph object"""
@abstractmethod
def get_num_inputs(self) -> int:
"""get the number of input pads of the filter
:return: number of input pads
"""
@abstractmethod
def get_num_outputs(self) -> int:
"""get the number of output pads of the filter
:return: number of output pads
"""
@abstractmethod
def get_num_chains(self) -> int:
"""get the number of chains"""
@abstractmethod
def get_num_filters(self, chain: int | None = None) -> int:
"""get the number of filters of the specfied chain
:param chain: id of the chain, defaults to None to get the total number
of filters across all chains
"""
@abstractmethod
def iter_chains(self) -> Generator[fgb.Chain]:
"""iterate over chains of the filtergraphobject
:yields chain: ``Chain`` object
"""
@abstractmethod
def iter_input_pads(
self,
pad: int | None = None,
filter: int | None = None,
chain: int | None = None,
*,
chainable_first: bool = False,
include_connected: bool | None = False,
unlabeled_only: bool = False,
chainable_only: bool = False,
full_pad_index: bool = False,
) -> Generator[tuple[PAD_INDEX, fgb.Filter, PAD_INDEX | None]]:
"""Iterate over input pads of the filter
:param pad: pad id, defaults to None
:param filter: filter index, defaults to None
:param chain: chain index, defaults to None
:param chainable_first: True to yield the last input first then the rest, defaults to False
:param include_connected: True to include pads connected to input streams, defaults to False
:param unlabeled_only: True to leave out named inputs, defaults to False to return all inputs
:param chainable_only: True to only iterate chainable pads, defaults to False to return all inputs
:param full_pad_index: True to return 3-element index, defaults to False
:yield: filter pad index, link label, filter object, output pad index of connected filter if connected
"""
# used by: join (unlabeled_only, full_pad_index, chainable_only)
# resolve_pad_index (chainable_first, chainable_only)
# Chain.attach (chainable_only)
# Graph.compose (unlabeled_only)
# Graph.iter_input_pads/_iter_pads (exclude_chainable, chainable_first, include_connected, chainable_only)
# Graph.get_num_inputs (exclude_stream_specs, chainable_only)
# Graph.attach/rattach (chainable_only, full_pad_index)
# analyze_complex_filtergraph (full_pad_index, exclude_stream_specs)
#
# iter_input_pads used by:
#
@abstractmethod
def iter_output_pads(
self,
pad: int | None = None,
filter: int | None = None,
chain: int | None = None,
*,
exclude_chainable: bool = False,
chainable_first: bool = False,
include_connected: bool = False,
unlabeled_only: bool = False,
chainable_only: bool = False,
full_pad_index: bool = False,
) -> Generator[tuple[PAD_INDEX, fgb.Filter, PAD_INDEX | None]]:
"""Iterate over output pads of the filter
:param pad: pad id, defaults to None
:param filter: filter index, defaults to None
:param chain: chain index, defaults to None
:param exclude_chainable: True to leave out the last output pads, defaults to False (all avail pads)
:param chainable_first: True to yield the last output first then the rest, defaults to False
:param include_connected: True to include pads connected to output streams, defaults to False
:param unlabeled_only: True to leave out named outputs, defaults to False to return all outputs
:param chainable_only: True to only iterate chainable pads, defaults to False to return all outputs
:param full_pad_index: True to return 3-element index, defaults to False
:yield: filter pad index, link label, filter object, output pad index of connected filter if connected
"""
# Label management methods (default operation for non-Graph objects)
def iter_input_labels(
self, exclude_stream_specs: bool = False, only_stream_specs: bool = False
) -> Generator[tuple[str, PAD_INDEX]]:
"""iterate over the dangling labeled input pads of the filtergraph object
:param exclude_stream_specs: True to not include input streams
:param only_stream_specs: True to only include input streams
:yield: a tuple of 3-tuple pad index and the pad index of the connected output pad if connected
"""
yield from ()
def iter_output_labels(self) -> Generator[tuple[str, PAD_INDEX]]:
"""iterate over the dangling labeled output pads of the filtergraph object
:yield: a tuple of 3-tuple pad index and the pad index of the connected input pad if connected
"""
yield from ()
def get_label(
self,
input: bool = True,
index: PAD_INDEX | None = None,
inpad: PAD_INDEX | None = None,
outpad: PAD_INDEX | None = None,
) -> str | None:
"""get the label string of the specified filter input or output pad
:param input: True to get label of input pad, False to get label of output pad, defaults to True
:param index: 3-element tuple to specify the (chain, filter, pad) indices, defaults to None
:param inpad: alternate argument to specify an input pad index, defaults to None
:param outpad: alternate argument to specify an output pad index, defaults to None
:return: the label of the specified pad or ``None`` if no label is assigned.
If the pad index is invalid, the method raises ``FiltergraphInvalidIndex``.
"""
if index is not None:
return self._get_label(input, index)
if inpad is not None:
return self._get_label(True, inpad)
if outpad is not None:
return self._get_label(False, outpad)
raise ValueError(
"One and only one of index, inpad, or outpad must be specified."
)
def _get_label(self, input: bool, index: PAD_INDEX):
return None
@abstractmethod
def normalize_pad_index(
self, input: bool, index: PAD_INDEX
) -> tuple[int, int, int]:
"""normalize pad index.
Returns three-element pad index with non-negative indices.
:param input: True to check the input pad index, False the output.
:param index: pad index to be normalized
:return: normalized pad index
"""
def get_input_pad(
self, index_or_label: PAD_INDEX | str
) -> tuple[PAD_INDEX, str | None]:
"""resolve (unconnected) input pad from pad index or label
:param index: pad index or link label
:return: filter input pad index and its link label (None if not assigned)
Raises error if specified label does not resolve uniquely to an input pad
"""
index = self.resolve_pad_index(index_or_label, is_input=True)
return index, self._get_label(True, index)
def get_output_pad(
self, index_or_label: PAD_INDEX | str
) -> tuple[PAD_INDEX, str | None]:
"""resolve (unconnected) output filter pad from pad index or labels
:param index: pad index or link label
:type index: tuple(int,int,int) or str
:return: filter output pad index and its link labels
:rtype: tuple(int,int,int), list(str)
Raises error if specified index does not resolve uniquely to an output pad
"""
index = self.resolve_pad_index(index_or_label, is_input=False)
return index, self._get_label(False, index)
@abstractmethod
def add_label(
self,
label: str,
inpad: PAD_INDEX | Sequence[PAD_INDEX] = None,
outpad: PAD_INDEX = None,
force: bool = None,
) -> fgb.Graph:
"""label a filter pad
:param label: name of the new label. Square brackets are optional.
:param inpad: input filter pad index or a sequence of pads, defaults to None
:param outpad: output filter pad index, defaults to None
:param force: True to delete existing labels, defaults to None
:return: actual label name
Only one of inpad and outpad argument must be given.
If given label already exists, no new label will be created.
If inpad indices are given, the label must be an input stream specifier.
If label has a trailing number, the number will be dropped and replaced with an
internally assigned label number.
"""
def has_label(
self, label: str, only_if: Literal["input", "output", "internal"] | None = None
) -> bool:
"""True if a linklabel is defined
:param label: name of the link label
:param only_if: also check for the type of the label
:return: True if exists
"""
return False # reimplemented by Graph
def remove_label(self, label: str, inpad: PAD_INDEX | None = None):
"""remove an input/output label
:param label: linkn label
:param inpad: specify input pad if multiple pads receives the same input
stream, defaults to `None` to delete all input pads.
"""
### main graph manipulation routines
def stack(
self,
*others: tuple[fgb.abc.FilterGraphObject | str],
auto_link: bool | int = False,
sws_flags_policy: Literal["first", "last"] | int | None = None,
inplace: bool = False,
) -> fgb.Graph | None:
"""stack filtergraph objects
:param others: other filtergraphs to be stacked under in the order
appeared
:param auto_link: ``True`` to connect matched I/O labels, defaults to
``None``
:param sws_flags_policy: Defines how to set ``sws_flags``:
* ``'first'``: to use the first ``sws_flags`` found among the
filtergraphs (searched ``self`` first then ``others``)
* ``'last'``: use this filtergraph's ``sws_flags`` (or none used if
not set).
* ``int``: specify which filtergraph's ``sws_flags`` to use. ``0``
refers to this object, ``1`` refers to ``others[0]``, etc.
* ``None``: if more than one have the ``sws_flags`` set, raises
``FFmpegioError`` exception. Otherwise, it uses the only one found
or none if none not found.
:param inplace: Must be ``False`` as the result is always a ``Graph``.
If ``True``, a ``ValueError` exception will be raised.
:return: new filtergraph object
Remarks
-------
- extend() and import links
- If `auto-link=False`, common labels may be renamed.
- For more explicit linking rather than the auto-linking, use `connect()` instead.
"""
if inplace:
raise ValueError("Filter object cannot perform stack() with inplace=True")
return fgb.as_filtergraph(self).stack(*others, auto_link, sws_flags_policy)
@abstractmethod
def connect(
self,
right: fgb.abc.FilterGraphObject | str,
from_left: PAD_INDEX | str | list[PAD_INDEX | str],
to_right: PAD_INDEX | str | list[PAD_INDEX | str],
*,
from_right: PAD_INDEX | str | list[PAD_INDEX | str] | None = None,
to_left: PAD_INDEX | str | list[PAD_INDEX | str] | None = None,
chain_siso: bool = True,
sws_flags_policy: Literal["first", "last"] | int | None = None,
inplace: bool = False,
) -> fgb.Graph | fgb.Chain | None:
"""append another filtergraph object and make downstream connections
:param right: receiving filtergraph object
:param from_left: output pad ids or labels of `left` fg
:param to_right: input pad ids or labels of the `right` fg
:param from_right: output pad ids or labels of the `right` fg
:param to_left: input pad ids or labels of this `left` fg
:param chain_siso: ``True`` (default) to chain the connections instead
of stacking. ``False`` to append all the chains of ``right`` graphs.
:param sws_flags_policy: Defines how to set ``sws_flags``:
* ``'first'``: to use the first ``sws_flags`` found among the
filtergraphs (searched ``self`` first then ``others``)
* ``'last'``: use this filtergraph's ``sws_flags`` (or none used if
not set).
* ``int``: specify which filtergraph's ``sws_flags`` to use. ``0``
refers to this object, ``1`` refers to ``others[0]``, etc.
* ``None``: if more than one have the ``sws_flags`` set, raises
``FFmpegioError`` exception. Otherwise, it uses the only one found
or none if none not found.
:param inplace: ``True`` to store the output filtergraph in place.
If ``'inplace=True`` but the output is not of the same class type,
a ``ValueError` exception will be raised.
:return: new filtergraph object or ``None`` if ``inplace=True``
* link labels may be auto-renamed if there is a conflict
"""
@abstractmethod
def rconnect(
self,
left: fgb.abc.FilterGraphObject | str,
from_left: PAD_INDEX | str | list[PAD_INDEX | str],
to_right: PAD_INDEX | str | list[PAD_INDEX | str],
*,
from_right: PAD_INDEX | str | list[PAD_INDEX | str] | None = None,
to_left: PAD_INDEX | str | list[PAD_INDEX | str] | None = None,
chain_siso: bool = True,
sws_flags_policy: Literal["first", "last"] | int | None = None,
inplace: bool = False,
) -> fgb.Graph | fgb.Chain | None:
"""append another filtergraph object and make upstream connections
:param left: transmitting filtergraph object
:param right: receiving filtergraph object
:param from_left: output pad ids or labels of `left` fg
:param to_right: input pad ids or labels of the `right` fg
:param from_right: output pad ids or labels of the `right` fg
:param to_left: input pad ids or labels of this `left` fg
:param chain_siso: ``True`` (default) to chain the connections instead
of stacking. ``False`` to append all the chains of ``right`` graphs.
:param replace_sws_flags: Defines how to set ``sws_flags``:
* ``True``: to use the first ``sws_flags`` found among the
filtergraphs, chosen in the order of appearance
* ``False``: use this filtergraph's ``sws_flags`` (or none used if
not set).
* ``int``: specify which filtergraph's ``sws_flags`` to use. ``0``
refers to this object, ``1`` refers to ``others[0]``, etc.
* ``None``: if more than one have the ``sws_flags`` set, raises
``FFmpegioError`` exception. Otherwise, it uses the only one found
or none if none not found.
:param inplace: ``True`` to store the output filtergraph in place.
If ``'inplace=True`` but the output is not of the same class type,
a ``ValueError` exception will be raised.
:return: new filtergraph object or ``None`` if ``inplace=True``
* link labels may be auto-renamed if there is a conflict
"""
def join(
self,
right: fgb.abc.FilterGraphObject | str,
how: JOIN_HOW | None = None,
n_links: int | Literal["all"] | None = None,
*,
strict: bool = False,
unlabeled_only: bool = False,
chain_siso: bool = True,
sws_flags_policy: Literal["first", "last"] | int | None = None,
inplace: bool = False,
) -> fgb.Graph | fgb.Chain:
"""filtergraph auto-connector
:param right: receiving filtergraph object
:param how: method on how to mate input and output, defaults to ``"per_chain"``.
- ``'chainable'``: joins only chainable input pads and output pads.
- ``'per_chain'``: joins one pair of first available input pad and output pad of each
mating chains. Source and sink chains are ignored.
- ``'all'``: joins all input pads and output pads
- ``'auto'``: tries ``'per_chain'`` first, if fails, then tries ``'all'``.
:param n_links: number of left output pads to be connected to the right input pads, default: 0
(all matching links). If ``how=='per_chain'``, ``n_links`` connections are made
per chain.
:param strict: True to raise exception if numbers of available pads do not match, default: False
:param unlabeled_only: True to ignore labeled unconnected pads, defaults to False
:param chain_siso: True to chain the single-input single-output connection, default: True
:param sws_flags_policy: Defines how to set ``sws_flags``:
* ``'first'``: to use the first ``sws_flags`` found among the
filtergraphs (searched ``self`` first then ``others``)
* ``'last'``: use this filtergraph's ``sws_flags`` (or none used if
not set).
* ``int``: specify which filtergraph's ``sws_flags`` to use. ``0``
refers to this object, ``1`` refers to ``others[0]``, etc.
* ``None``: if more than one have the ``sws_flags`` set, raises
``FFmpegioError`` exception. Otherwise, it uses the only one found
or none if none not found.
:return: Graph with the appended filter chains or None if inplace=True.
"""
right = fgb.as_filtergraph_object(right)
# if one of the filtergraphs is empty, return the other (or a copy thereof)
if right.get_num_filters() == 0:
return None if inplace else self.copy()
if self.get_num_filters() == 0:
if inplace:
self.__init__(right)
return
else:
return right.copy()
from_left, to_right = self._join_analyze(
self,
right,
how,
n_links,
strict,
unlabeled_only,
)
return self.connect(
right,
from_left=from_left,
to_right=to_right,
chain_siso=chain_siso,
sws_flags_policy=sws_flags_policy,
inplace=inplace,
)
def rjoin(
self,
left: fgb.abc.FilterGraphObject | str,
*,
how: JOIN_HOW | None = None,
n_links: int | Literal["all"] | None = None,
strict: bool = False,
unlabeled_only: bool = False,
chain_siso: bool = True,
sws_flags_policy: Literal["first", "last"] | int | None = None,
inplace: bool = False,
) -> fgb.Graph | fgb.Chain:
"""filtergraph auto-connector
:param left: feeding filtergraph object
:param how: method on how to mate input and output, defaults to ``"per_chain"``.
- ``'chainable'``: joins only chainable input pads and output pads.
- ``'per_chain'``: joins one pair of first available input pad and output pad of each
mating chains. Source and sink chains are ignored.
- ``'all'``: joins all input pads and output pads
- ``'auto'``: tries ``'per_chain'`` first, if fails, then tries ``'all'``.
:param n_links: number of left output pads to be connected to the right input pads, default: 0
(all matching links). If ``how=='per_chain'``, ``n_links`` connections are made
per chain.
:param strict: True to raise exception if numbers of available pads do not match, default: False
:param unlabeled_only: True to ignore labeled unconnected pads, defaults to False
:param chain_siso: ``True`` to chain the single-input single-output
connection, default: True
:param sws_flags_policy: Defines how to set ``sws_flags``:
* ``'first'``: to use the first ``sws_flags`` found among the
filtergraphs (searched ``self`` first then ``others``)
* ``'last'``: use this filtergraph's ``sws_flags`` (or none used if
not set).
* ``int``: specify which filtergraph's ``sws_flags`` to use. ``0``
refers to this object, ``1`` refers to ``others[0]``, etc.
* ``None``: if more than one have the ``sws_flags`` set, raises
``FFmpegioError`` exception. Otherwise, it uses the only one found
or none if none not found.
:return: Graph with the appended filter chains or None if inplace=True.
"""
left = fgb.as_filtergraph_object(left)
# if one of the filtergraphs is empty, return the other (or a copy thereof)
if left.get_num_filters() == 0:
return None if inplace else self.copy()
if self.get_num_filters() == 0:
if inplace:
self.__init__(left)
return
else:
return left.copy()
from_left, to_right = self._join_analyze(
left, self, how, n_links, strict, unlabeled_only
)
return self.rconnect(
left,
from_left=from_left,
to_right=to_right,
chain_siso=chain_siso,
sws_flags_policy=sws_flags_policy,
inplace=inplace,
)
@staticmethod
def _join_analyze(
left: FilterGraphObject,
right: FilterGraphObject,
how: JOIN_HOW | None,
n_links: int | Literal["all"] | None,
strict: bool,
unlabeled_only: bool,
):
if how is None:
how = "auto"
if n_links is None:
n_links = "all"
if how not in get_args(JOIN_HOW):
raise ValueError(f"{how=} is not a valid option")
# handle joining empty graph
nright = right.get_num_chains()
nleft = left.get_num_chains()
iter_kws = {"unlabeled_only": unlabeled_only, "full_pad_index": True}
if how == "chainable":
iter_kws["chainable_only"] = True
if n_links == "all" or n_links < 0:
n_links = 0
from_left = []
to_right = []
if how in ("per_chain", "auto") and nright == nleft:
try:
from_left = [
next(left.iter_output_pads(chain=c, **iter_kws))[0]
for c in range(nleft)
]
to_right = [
next(right.iter_input_pads(chain=c, **iter_kws))[0]
for c in range(nleft)
]
except StopIteration:
if how == "auto":
how = "all"
else:
raise
if how in ("all", "chainable") or nright != nleft:
left_pads = [out[0] for out in left.iter_output_pads(**iter_kws)]
right_pads = [out[0] for out in right.iter_input_pads(**iter_kws)]
nleft, nright = len(left_pads), len(right_pads)
if strict and nleft != nright:
raise FiltergraphMismatchError(
"`[stict=True] number of unconnected pads must match."
)
n_max = min(nleft, nright)
n_links = n_max if n_links <= 0 else min(n_links, n_max)
from_left = left_pads[:n_links]
to_right = right_pads[:n_links]
return from_left, to_right
@abstractmethod
def attach(
self,
right: fgb.abc.FilterGraphObject | str | list[str],
left_on: PAD_INDEX | str | list[PAD_INDEX | str | None] | None = None,
right_on: PAD_INDEX | str | list[PAD_INDEX | str | None] | None = None,
*,
chainable_only: bool | Literal["left", "right", "auto"] = "auto",
chain_siso: bool = True,
inplace: bool = False,
) -> fgb.Chain | fgb.Graph:
"""attach filter, chain, graph, or labels to available output pads
:param right: output filtergraph or labels. If ``str``, the expression
is first attempted to be converted to a filtergraph object. If the
attempt fails, it is treated as a label.
:param left_on: pad_index, specify the output pad to connect ``right``
to, defaults to auto-detect (first available)
:param right_on: pad index, specifies the input pad of ``right`` to
connect to the ``left_on`` pad, defaults to auto-detect (first
available)
:param chainable_only: ``True`` to limit auto-detecting ``left_on`` and
``righ_on`` pads to be only those that can extend the existing
chains. To force this condition only on one side, use ``'left'`` or
``'right'``. If ``"auto"`` (default) depends on this filtergraph
object type: ``Filter`` and ``Chain`` defaults to ``True`` while
``Graph`` defaults to ``False``
:param chain_siso: ``True`` (default) to chain the new connection,
``False`` to stack attached filtergraph.
:param inplace: ``True`` to store the output filtergraph in place.
If ``'inplace=True`` but the output is not of the same class type,
a ``ValueError` exception will be raised.
:return: new filtergraph object or ``None`` if ``inplace=True``
"""
@abstractmethod
def rattach(
self,
left: fgb.abc.FilterGraphObject | str | list[str],
left_on: PAD_INDEX | str | list[PAD_INDEX | str | None] | None = None,
right_on: PAD_INDEX | str | list[PAD_INDEX | str | None] | None = None,
*,
chainable_only: bool | Literal["left", "right", "auto"] = "auto",
chain_siso: bool = True,
inplace: bool = False,
) -> fgb.Chain | fgb.Graph:
"""attach filter, chain, graph, or labels to available input pads
:param left: input filtergraph or labels. If ``str``, the expression
is first attempted to be converted to a filtergraph object. If the
attempt fails, it is treated as a label.
:param left_on: pad_index, specify the output pad of ``left``,
defaults to auto-detect (first available)
:param right_on: pad index, specifies which input pad to connect
``left`` to, defaults to auto-detect (first available)
:param chainable_only: ``True`` to limit auto-detecting ``left_on`` and
``righ_on`` pads to be only those that can extend the existing
chains. To force this condition only on one side, use ``'left'`` or
``'right'``. If ``"auto"`` (default) depends on this filtergraph
object type: ``Filter`` and ``Chain`` defaults to ``True`` while
``Graph`` defaults to ``False``
:param chain_siso: ``True`` (default) to chain the new connection,
``False`` to stack attached filtergraph.
:param inplace: ``True`` to store the output filtergraph in place.
If ``'inplace=True`` but the output is not of the same class type,
a ``ValueError` exception will be raised.
:return: new filtergraph object or ``None`` if ``inplace=True``
"""
### main graph manipulation routines
@abstractmethod
def __getitem__(self, key): ...
@abstractmethod
def compose(
self,
show_unconnected_inputs: bool = True,
show_unconnected_outputs: bool = True,
):
"""compose filtergraph
:param show_unconnected_inputs: display [UNC#] on all unconnected input pads, defaults to True
:param show_unconnected_outputs: display [UNC#] on all unconnected output pads, defaults to True
"""
# def __eq__(self, value: FilterGraphObject | str) -> bool:
def __eq__(self, value: object) -> bool:
try:
value = fgb.convert.as_filtergraph_object_like(value, self)
except Exception:
return False
return super().__eq__(value)
# def __ne__(self, value: FilterGraphObject | str) -> bool:
def __ne__(self, value: object) -> bool:
try:
value = fgb.convert.as_filtergraph_object_like(value, self)
except Exception:
return True
return super().__ne__(value)
def __str__(self) -> str:
return self.compose(False, False)
@abstractmethod
def __repr__(self) -> str: ...
# Filtergraph math operators
def __add__(self, other: FilterGraphObject | str) -> fgb.Chain | fgb.Graph:
return self.join(other)
def __radd__(self, other: FilterGraphObject | str) -> fgb.Chain | fgb.Graph:
return fgb.as_filtergraph_object(other).join(self)
def __mul__(self, __n: int) -> fgb.Graph:
"""duplicate-n-stack"""
if not isinstance(__n, int):
return NotImplemented
return fgb.stack(*((self,) * __n))
def __rmul__(self, __n: int) -> fgb.Graph:
"""duplicate-n-stack"""
if not isinstance(__n, int):
return NotImplemented
return fgb.stack(*((self,) * __n))
def __or__(self, other: FilterGraphObject | str) -> fgb.Graph:
"""stack"""
return self.stack(other)
def __ror__(self, other: FilterGraphObject | str) -> fgb.Graph:
"""stack"""
return fgb.stack(other, self)
def __rshift__(
self,
other: (
FilterGraphObject
| str
| tuple[FilterGraphObject, PAD_INDEX | str]
| tuple[FilterGraphObject, PAD_INDEX | str | None, PAD_INDEX | str]
),
) -> fgb.Graph:
"""make one-to-one attachment
self >> other|label
self >> (index, other|label)
self >> (index, other_index, other)
If pad is unspecified (i.e., ``index`` is ``None`` or the last
element of ``index`` is ``None``), chain connection is sought first
unless multiple other connection points are given.
"""
left_on = right_on = None
if isinstance(other, tuple):
n = len(other)
if n == 0 or n > 3:
return NotImplemented
right = other[-1]
if n > 1:
left_on = other[0]
right_on = other[1] if n > 2 else None
else:
right = other
return self.attach(right, left_on, right_on, inplace=False)
def __rrshift__(
self,
other: (
FilterGraphObject
| str
| tuple[PAD_INDEX | str, FilterGraphObject]
| tuple[PAD_INDEX | str, PAD_INDEX | str, FilterGraphObject]
),
) -> fgb.Graph:
"""make one-to-one connections
other|label >> self
(other|label, index) >> self
(other, other_index, index) >> self
[other0, other1, ...] >> self
If pad is unspecified (i.e., ``index`` is ``None`` or the last
element of ``index`` is ``None``), chain connection is sought first
unless multiple other connection points are given.
"""
left_on = right_on = None
if isinstance(other, tuple):
n = len(other)
if n == 0 or n > 3:
return NotImplemented
left = other[0]
if n > 1:
right_on = other[-1]
left_on = other[1] if n > 2 else None
else:
left = other
return self.rattach(left, left_on, right_on, inplace=False)
def resolve_pad_index(
self,
index_or_label: PAD_INDEX | str | None,
*,
is_input: bool = True,
chain_id_omittable: bool = False,
filter_id_omittable: bool = False,
pad_id_omittable: bool = False,
resolve_omitted: bool = True,
chain_fill_value: int | None = None,
filter_fill_value: int | None = None,
pad_fill_value: int | None = None,
chainable_first: bool = False,
chainable_only: bool = False,
) -> PAD_INDEX:
"""Resolve unconnected label or pad index to full 3-element pad index
:param index_or_label: pad index set or pad label or ``None`` to auto-select
:param is_input: True to resolve an input pad, else an output pad, defaults to True
:param chain_id_omittable: True to allow ``None`` chain index, defaults to False
:param filter_id_omittable: True to allow ``None`` filter index, defaults to False
:param pad_id_omittable: True to allow ``None`` pad index, defaults to False
:param resolve_omitted: True to fill each omitted value with the prescribed fill value.
:param chain_fill_value: if ``chain_id_omittable=True`` and chain index is either not
given or ``None``, this value will be returned, defaults to None,
which returns the first available pad.
:param filter_fill_value:if ``filter_id_omittable=True`` and filter index is either not
given or ``None``, this value will be returned, defaults to None,
which returns the first available pad.
:param pad_fill_value: if ``pad_id_omittable=True`` and either ``index`` is None or
pad index is ``None``, this value will be returned, defaults to None,
which returns the first available pad.
:param chainable_first: if True, chainable pad is selected first, defaults to False
:param chainable_only: True to only iterate chainable pads, defaults to False to return all pads
One and only one of ``index`` and ``label`` must be specified. If the given index
or label is invalid, it raises FiltergraphPadNotFoundError.
"""
# base implementation - guarantees to return 3-element tuple index WITHOUT converting None fill_values
# label, if allowed, must be resolved in the subclass
if isinstance(index_or_label, str):
raise FiltergraphPadNotFoundError(
f"{index_or_label=} is not defined on the filtergraph."
)
# put missing or pad-only input to a 3-element tuple format
index = (
(None, None, None)
if index_or_label is None
else (
(None, None, index_or_label)
if isinstance(index_or_label, int)
else (
index_or_label
if len(index_or_label) == 3
else (*((None,) * (3 - len(index_or_label))), *index_or_label)
)
)
)
allow_partial_index = (
chain_id_omittable or filter_id_omittable or pad_id_omittable
)
index_types = (int, type(None)) if allow_partial_index else int
pad_type = "input" if is_input else "output" # for error messages
if not (all(isinstance(i, index_types) for i in index)):
raise FiltergraphPadNotFoundError(
f"{index_or_label=} is an invalid {pad_type} pad index."
)
def get_value(id_type, id_value, omittable, fill_value):
if id_value is None and not omittable:
raise FiltergraphPadNotFoundError(f"{id_type} id must be specified.")
return fill_value if id_value is None else id_value
index = tuple(
get_value(id_type, id, omittable, fill_value)
for id_type, id, omittable, fill_value in zip(
("chain", "filter", "pad"),
index,
(chain_id_omittable, filter_id_omittable, pad_id_omittable),
(chain_fill_value, filter_fill_value, pad_fill_value),
)
)
if allow_partial_index and any(i is None for i in index):
if resolve_omitted:
iter_pads = self.iter_input_pads if is_input else self.iter_output_pads
try:
index = next(
iter_pads(
chain=index[0],
filter=index[1],
pad=index[2],
chainable_first=chainable_first,
chainable_only=chainable_only,
)
)[0]
except StopIteration as e:
raise FiltergraphPadNotFoundError(
f"{index_or_label=} could not be resolve to an unused {pad_type} pad index."
) from e
n = len(index)
if n < 3:
index = (*(0,) * (3 - n), *index)
elif not self._check_partial_pad_index(index, is_input=is_input):
raise FiltergraphPadNotFoundError(
f"{index_or_label=} cannot be resolve to a valid {pad_type} pad index."
)
return index
# validate
if (
self._input_pad_is_available if is_input else self._output_pad_is_available
)(index):
return index
raise FiltergraphPadNotFoundError(
f"{index_or_label=} is either already connected or invalid {pad_type} pad."
)
@abstractmethod
def _input_pad_is_available(self, index: tuple[int, int, int]) -> bool:
"""index must be 3-element tuple"""
@abstractmethod
def _output_pad_is_available(self, index: tuple[int, int, int]) -> bool:
"""index must be 3-element tuple"""
@abstractmethod
def _check_partial_pad_index(
self, index: tuple[int | None, int | None, int | None], is_input: bool
) -> bool:
"""True if defined values of the partial pad index are valid"""
@abstractmethod
def _input_pad_is_chainable(self, index: tuple[int, int, int]) -> bool:
"""True if specified input pad is chainable"""
@abstractmethod
def _output_pad_is_chainable(self, index: tuple[int, int, int]) -> bool:
"""True if specified output pad is chainable"""
def _attach(
self,
right: list[fgb.Filter | fgb.Chain | str],
left_on: list[PAD_INDEX],
right_on: list[PAD_INDEX | None],
) -> fgb.Chain | fgb.Graph:
"""helper function attach other filtergraph to this graph
:param right: list of filter/chain objects or pad label strings
:param left_on: list of output pad indices, matching the size of right
:param right_on: list of input pad indices if object or None if label
:param right_first: True to preserve the chain indices of the right filtergraph object, defaults
to False to preserve the chain order of the self object
:return: resulting filtergraph
"""
fg = (
fgb.as_filtergraph(self)
if any(idx is None for idx in right_on)
else fgb.atleast_filterchain(self)
)
for r, l_idx, r_idx in zip(right, left_on, right_on, strict=True):
if r_idx is None: # label
fg.add_label(r, outpad=l_idx)
else:
out = fg._connect(r, [(l_idx, r_idx)], [], chain_siso=True)