Welcome to mirror list, hosted at ThFree Co, Russian Federation.

task.rs « runtime « src « threadshare « generic - gitlab.freedesktop.org/gstreamer/gst-plugins-rs.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ee2eb0ead135b5a94ca7dc7207180c8cf8daa840 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
// Copyright (C) 2019-2020 François Laignel <fengalin@free.fr>
// Copyright (C) 2020 Sebastian Dröge <sebastian@centricular.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Suite 500,
// Boston, MA 02110-1335, USA.

//! An execution loop to run asynchronous processing.

use futures::channel::mpsc as async_mpsc;
use futures::channel::oneshot;
use futures::future::{self, abortable, AbortHandle, Aborted, BoxFuture};
use futures::prelude::*;
use futures::stream::StreamExt;

use gst::{gst_debug, gst_error, gst_error_msg, gst_fixme, gst_log, gst_trace, gst_warning};

use std::fmt;
use std::ops::Deref;
use std::sync::{Arc, Mutex, MutexGuard};

use super::executor::{block_on_or_add_sub_task, TaskId};
use super::{Context, JoinHandle, RUNTIME_CAT};

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone, Copy)]
pub enum TaskState {
    Flushing,
    Paused,
    PausedFlushing,
    PrepareFailed,
    Prepared,
    Preparing,
    Started,
    Stopped,
    Unprepared,
    Unpreparing,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TaskError {
    ActiveTask,
    InactiveTask,
}

impl fmt::Display for TaskError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            TaskError::ActiveTask => write!(f, "Task is active"),
            TaskError::InactiveTask => write!(f, "Task is not active"),
        }
    }
}

impl std::error::Error for TaskError {}

/// Implementation trait for `Task`s.
///
/// Defines implementations for specific state transitions.
///
/// In the event of a failure, the implementer must call
/// `gst_element_error!`.
pub trait TaskImpl: Send + 'static {
    fn prepare(&mut self) -> BoxFuture<'_, Result<(), gst::ErrorMessage>> {
        future::ok(()).boxed()
    }

    /// Handles an error happening during prepare.
    ///
    /// This handler also catches errors returned by subtasks spawned by `prepare`.
    ///
    /// Implementation might use `gst::Element::post_error_message`.
    fn handle_prepare_error(&mut self, err: gst::ErrorMessage) -> BoxFuture<'_, ()> {
        async move {
            gst_error!(
                RUNTIME_CAT,
                "TaskImpl default handle_prepare_error received {:?}",
                err
            );
        }
        .boxed()
    }

    fn unprepare(&mut self) -> BoxFuture<'_, ()> {
        future::ready(()).boxed()
    }

    fn start(&mut self) -> BoxFuture<'_, ()> {
        future::ready(()).boxed()
    }

    /// Executes an iteration in `TaskState::Started`.
    fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>>;

    fn pause(&mut self) -> BoxFuture<'_, ()> {
        future::ready(()).boxed()
    }

    fn flush_start(&mut self) -> BoxFuture<'_, ()> {
        future::ready(()).boxed()
    }

    fn flush_stop(&mut self) -> BoxFuture<'_, ()> {
        future::ready(()).boxed()
    }

    fn stop(&mut self) -> BoxFuture<'_, ()> {
        future::ready(()).boxed()
    }
}

#[derive(Clone, Copy, Debug)]
enum TransitionKind {
    FlushStart,
    FlushStop,
    Pause,
    Prepare,
    Start,
    Stop,
    Unprepare,
}

struct Transition {
    kind: TransitionKind,
    ack_tx: Option<oneshot::Sender<Transition>>,
}

impl Transition {
    fn new(kind: TransitionKind) -> (Self, oneshot::Receiver<Transition>) {
        let (ack_tx, ack_rx) = oneshot::channel();
        let req = Transition {
            kind,
            ack_tx: Some(ack_tx),
        };

        (req, ack_rx)
    }

    fn send_ack(mut self) {
        if let Some(ack_tx) = self.ack_tx.take() {
            let _ = ack_tx.send(self);
        }
    }
}

impl fmt::Debug for Transition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Transition")
            .field("kind", &self.kind)
            .finish()
    }
}

#[derive(Debug)]
struct TaskInner {
    // The state machine needs an un-throttling Context because otherwise
    // `transition_rx.next()` would throttle at each transition request.
    // Since pipelines serialize state changes, this would lead to long starting / stopping
    // when a pipeline consists in a large number of elements.
    // See also the comment about transition_tx below.
    state_machine_context: Context,
    // The TaskImpl processings are spawned on the Task Context by the state machine.
    context: Option<Context>,
    state: TaskState,
    state_machine_handle: Option<JoinHandle<()>>,
    // The transition channel allows serializing transitions handling,
    // preventing race conditions when transitions are run in //.
    transition_tx: Option<async_mpsc::Sender<Transition>>,
    prepare_abort_handle: Option<AbortHandle>,
    loop_abort_handle: Option<AbortHandle>,
    spawned_task_id: Option<TaskId>,
}

impl Default for TaskInner {
    fn default() -> Self {
        TaskInner {
            state_machine_context: Context::acquire("state_machine", 0).unwrap(),
            context: None,
            state: TaskState::Unprepared,
            state_machine_handle: None,
            transition_tx: None,
            prepare_abort_handle: None,
            loop_abort_handle: None,
            spawned_task_id: None,
        }
    }
}

impl TaskInner {
    fn switch_to_state(&mut self, state: TaskState, transition: Transition) {
        self.state = state;
        transition.send_ack();
    }

    fn skip_transition(&mut self, transition: Transition) {
        transition.send_ack();
    }

    fn push_transition(
        &mut self,
        kind: TransitionKind,
    ) -> Result<oneshot::Receiver<Transition>, TaskError> {
        if self.transition_tx.is_none() {
            return Err(TaskError::InactiveTask);
        }

        let (transition, ack_rx) = Transition::new(kind);

        gst_log!(RUNTIME_CAT, "Requesting {:?}", transition);

        self.transition_tx
            .as_mut()
            .unwrap()
            .try_send(transition)
            .or(Err(TaskError::InactiveTask))?;

        Ok(ack_rx)
    }
}

impl Drop for TaskInner {
    fn drop(&mut self) {
        if self.state != TaskState::Unprepared {
            // Don't panic here: in case another panic occurs, we would get
            // "panicked while panicking" which would prevents developers
            // from getting the initial panic message.
            gst_fixme!(RUNTIME_CAT, "Missing call to `Task::unprepare`");
        }
    }
}

/// An RAII implementation of scoped locked `TaskState`.
pub struct TaskStateGuard<'guard>(MutexGuard<'guard, TaskInner>);

impl Deref for TaskStateGuard<'_> {
    type Target = TaskState;

    fn deref(&self) -> &Self::Target {
        &(self.0).state
    }
}

/// A `Task` operating on a `threadshare` [`Context`].
///
/// [`Context`]: ../executor/struct.Context.html
#[derive(Debug, Clone)]
pub struct Task(Arc<Mutex<TaskInner>>);

impl Default for Task {
    fn default() -> Self {
        Task(Arc::new(Mutex::new(TaskInner::default())))
    }
}

impl Task {
    pub fn state(&self) -> TaskState {
        self.0.lock().unwrap().state
    }

    pub fn lock_state(&self) -> TaskStateGuard<'_> {
        TaskStateGuard(self.0.lock().unwrap())
    }

    pub fn context(&self) -> Option<Context> {
        self.0.lock().unwrap().context.as_ref().cloned()
    }

    pub fn prepare(&self, task_impl: impl TaskImpl, context: Context) -> Result<(), TaskError> {
        let mut inner = self.0.lock().unwrap();

        match inner.state {
            TaskState::Unprepared => (),
            TaskState::Prepared => {
                gst_debug!(RUNTIME_CAT, "Task already prepared");
                return Err(TaskError::ActiveTask);
            }
            TaskState::Preparing => {
                gst_warning!(RUNTIME_CAT, "Task already preparing");
                return Err(TaskError::ActiveTask);
            }
            TaskState::Unpreparing => {
                gst_warning!(RUNTIME_CAT, "Task unpreparing");
                return Err(TaskError::InactiveTask);
            }
            state => {
                gst_warning!(
                    RUNTIME_CAT,
                    "Attempt to prepare a task in state {:?}",
                    state
                );
                return Err(TaskError::ActiveTask);
            }
        }

        assert!(inner.state_machine_handle.is_none());

        inner.state = TaskState::Preparing;

        gst_log!(RUNTIME_CAT, "Starting task state machine");

        // FIXME allow configuration of the channel buffer size,
        // this determines the contention on the Task.
        let (transition_tx, transition_rx) = async_mpsc::channel(4);
        let state_machine = StateMachine::new(Box::new(task_impl), transition_rx);
        let (transition, _) = Transition::new(TransitionKind::Prepare);
        inner.state_machine_handle = Some(inner.state_machine_context.spawn(state_machine.run(
            Arc::clone(&self.0),
            context.clone(),
            transition,
        )));

        inner.transition_tx = Some(transition_tx);
        inner.context = Some(context);

        gst_log!(RUNTIME_CAT, "Task state machine started");

        Ok(())
    }

    pub fn unprepare(&self) -> Result<(), TaskError> {
        let mut inner = self.0.lock().unwrap();

        match inner.state {
            TaskState::Stopped
            | TaskState::Prepared
            | TaskState::PrepareFailed
            | TaskState::Preparing => (),
            TaskState::Unprepared => {
                gst_debug!(RUNTIME_CAT, "Task already unprepared");
                return Err(TaskError::InactiveTask);
            }
            TaskState::Unpreparing => {
                gst_debug!(RUNTIME_CAT, "Task already unpreparing");
                return Err(TaskError::InactiveTask);
            }
            state => {
                gst_warning!(
                    RUNTIME_CAT,
                    "Attempt to unprepare a task in state  {:?}",
                    state
                );
                return Err(TaskError::ActiveTask);
            }
        }

        gst_debug!(RUNTIME_CAT, "Unpreparing task");

        inner.state = TaskState::Unpreparing;

        if let Some(loop_abort_handle) = inner.loop_abort_handle.take() {
            loop_abort_handle.abort();
        }

        let _ = inner.push_transition(TransitionKind::Unprepare).unwrap();
        let transition_tx = inner.transition_tx.take().unwrap();

        let state_machine_handle = inner.state_machine_handle.take();
        let context = inner.context.take().unwrap();

        if let Some(prepare_abort_handle) = inner.prepare_abort_handle.take() {
            prepare_abort_handle.abort();
        }

        drop(inner);

        if let Some(state_machine_handle) = state_machine_handle {
            // We can block on the state_machine_handle since `unprepare` is never called
            // from the state machine Context, but from a spawned Task Context subtask.
            gst_log!(
                RUNTIME_CAT,
                "Synchronously waiting for the state machine {:?}",
                state_machine_handle,
            );
            let _ = block_on_or_add_sub_task(state_machine_handle);
        }

        drop(transition_tx);
        drop(context);

        gst_debug!(RUNTIME_CAT, "Task unprepared");

        Ok(())
    }

    /// `Starts` the `Task`.
    ///
    /// The execution occurs on the `Task` context.
    pub fn start(&self) {
        let mut inner = self.0.lock().unwrap();

        let ack_rx = match inner.push_transition(TransitionKind::Start) {
            Ok(ack_rx) => ack_rx,
            Err(err) => {
                gst_warning!(RUNTIME_CAT, "Error attempting to Start task: {:?}", err);
                return;
            }
        };

        if let TaskState::Started = inner.state {
            // Don't await ack_rx because TaskImpl::iterate might be pending
            return;
        }

        Self::await_ack(inner, ack_rx, TransitionKind::Start);
    }

    /// Requests the `Task` loop to pause.
    ///
    /// If an iteration is in progress, it will run to completion,
    /// then no more iteration will be executed before `start` is called again.
    /// Therefore, it is not guaranteed that `Paused` is reached when `pause` returns.
    pub fn pause(&self) {
        let mut inner = self.0.lock().unwrap();

        if let Err(err) = inner.push_transition(TransitionKind::Pause) {
            gst_warning!(RUNTIME_CAT, "Error attempting to Pause task: {:?}", err);
        }
    }

    pub fn flush_start(&self) {
        let mut inner = self.0.lock().unwrap();

        if let Some(loop_abort_handle) = inner.loop_abort_handle.take() {
            loop_abort_handle.abort();
        }

        Self::push_and_await_transition(inner, TransitionKind::FlushStart);
    }

    pub fn flush_stop(&self) {
        let mut inner = self.0.lock().unwrap();

        if let Some(loop_abort_handle) = inner.loop_abort_handle.take() {
            loop_abort_handle.abort();
        }

        Self::push_and_await_transition(inner, TransitionKind::FlushStop);
    }

    /// Stops the `Started` `Task` and wait for it to finish.
    pub fn stop(&self) {
        let mut inner = self.0.lock().unwrap();

        if let Some(loop_abort_handle) = inner.loop_abort_handle.take() {
            loop_abort_handle.abort();
        }

        Self::push_and_await_transition(inner, TransitionKind::Stop);
    }

    fn push_and_await_transition(
        mut inner: MutexGuard<TaskInner>,
        transition_kind: TransitionKind,
    ) {
        match inner.push_transition(transition_kind) {
            Ok(ack_rx) => Self::await_ack(inner, ack_rx, transition_kind),
            Err(err) => {
                gst_warning!(
                    RUNTIME_CAT,
                    "Error attempting to {:?} task: {:?}",
                    transition_kind,
                    err
                );
            }
        }
    }

    fn await_ack(
        inner: MutexGuard<TaskInner>,
        ack_rx: oneshot::Receiver<Transition>,
        transition_kind: TransitionKind,
    ) {
        // Since transition handling is serialized by the state machine and
        // we hold a lock on TaskInner, we can verify if current spawned loop / tansition hook
        // task_id matches the task_id of current subtask, if any.
        if let Some(spawned_task_id) = inner.spawned_task_id {
            if let Some((cur_context, cur_task_id)) = Context::current_task() {
                if cur_task_id == spawned_task_id && &cur_context == inner.context.as_ref().unwrap()
                {
                    // Don't block as this would deadlock
                    gst_log!(
                        RUNTIME_CAT,
                        "Transitionning to {:?} from loop or transition hook, not waiting",
                        transition_kind,
                    );
                    return;
                }
            }
        }

        drop(inner);

        block_on_or_add_sub_task(async move {
            gst_trace!(RUNTIME_CAT, "Awaiting ack for {:?}", transition_kind);
            if let Ok(transition) = ack_rx.await {
                gst_log!(RUNTIME_CAT, "Received ack for {:?}", transition);
            } else {
                gst_log!(
                    RUNTIME_CAT,
                    "Transition to {:?} was dropped",
                    transition_kind
                );
            }
        });
    }
}

struct StateMachine {
    task_impl: Box<dyn TaskImpl>,
    transition_rx: async_mpsc::Receiver<Transition>,
    pending_transition: Option<Transition>,
}

// Make sure the Context doesn't throttle otherwise we end up  with long delays
// executing transition in a pipeline with many elements. This is because pipeline
// serializes the transitions and the Context's scheduler gets a chance to reach its
// throttling state between 2 elements.

macro_rules! spawn_hook {
    ($hook:ident, $self:ident, $task_inner:expr, $context:expr) => {{
        let hook_fut = async move {
            $self.task_impl.$hook().await;
            $self
        };

        let join_handle = {
            let mut task_inner = $task_inner.lock().unwrap();
            let join_handle = $context.awake_and_spawn(hook_fut);
            task_inner.spawned_task_id = Some(join_handle.task_id());

            join_handle
        };

        join_handle.map(|res| res.unwrap())
    }};
}

impl StateMachine {
    // Use dynamic dispatch for TaskImpl as it reduces memory usage compared to monomorphization
    // without inducing any significant performance penalties.
    fn new(task_impl: Box<dyn TaskImpl>, transition_rx: async_mpsc::Receiver<Transition>) -> Self {
        StateMachine {
            task_impl,
            transition_rx,
            pending_transition: None,
        }
    }

    async fn run(
        mut self,
        task_inner: Arc<Mutex<TaskInner>>,
        context: Context,
        transition: Transition,
    ) {
        gst_trace!(RUNTIME_CAT, "Preparing task");

        self = StateMachine::spawn_prepare(self, &task_inner, &context, transition).await;

        loop {
            let transition = match self.pending_transition.take() {
                Some(pending_transition) => pending_transition,
                None => self
                    .transition_rx
                    .next()
                    .await
                    .expect("transition_rx dropped"),
            };

            gst_trace!(RUNTIME_CAT, "State machine popped {:?}", transition);

            match transition.kind {
                TransitionKind::Start => {
                    {
                        let mut task_inner = task_inner.lock().unwrap();
                        match task_inner.state {
                            TaskState::Stopped | TaskState::Paused | TaskState::Prepared => (),
                            TaskState::PausedFlushing => {
                                task_inner.switch_to_state(TaskState::Flushing, transition);
                                gst_trace!(RUNTIME_CAT, "Switched from PausedFlushing to Flushing");
                                continue;
                            }
                            state => {
                                task_inner.skip_transition(transition);
                                gst_trace!(RUNTIME_CAT, "Skipped Pause in state {:?}", state);
                                continue;
                            }
                        }
                    }

                    self = StateMachine::spawn_loop(self, &task_inner, &context, transition).await;
                    // next/pending transition handled in next iteration
                }
                TransitionKind::Pause => {
                    let target_state = {
                        let mut task_inner = task_inner.lock().unwrap();
                        match task_inner.state {
                            TaskState::Started | TaskState::Stopped | TaskState::Prepared => {
                                TaskState::Paused
                            }
                            TaskState::Flushing => TaskState::PausedFlushing,
                            state => {
                                task_inner.skip_transition(transition);
                                gst_trace!(RUNTIME_CAT, "Skipped Pause in state {:?}", state);
                                continue;
                            }
                        }
                    };

                    self = spawn_hook!(pause, self, &task_inner, &context).await;
                    task_inner
                        .lock()
                        .unwrap()
                        .switch_to_state(target_state, transition);
                }
                TransitionKind::Stop => {
                    {
                        let mut task_inner = task_inner.lock().unwrap();
                        match task_inner.state {
                            TaskState::Started
                            | TaskState::Paused
                            | TaskState::PausedFlushing
                            | TaskState::Flushing => (),
                            state => {
                                task_inner.skip_transition(transition);
                                gst_trace!(RUNTIME_CAT, "Skipped Stop in state {:?}", state);
                                continue;
                            }
                        }
                    }

                    self = spawn_hook!(stop, self, &task_inner, &context).await;
                    task_inner
                        .lock()
                        .unwrap()
                        .switch_to_state(TaskState::Stopped, transition);
                    gst_trace!(RUNTIME_CAT, "Task loop stopped");
                }
                TransitionKind::FlushStart => {
                    let target_state = {
                        let mut task_inner = task_inner.lock().unwrap();
                        match task_inner.state {
                            TaskState::Started => TaskState::Flushing,
                            TaskState::Paused => TaskState::PausedFlushing,
                            state => {
                                task_inner.skip_transition(transition);
                                gst_trace!(RUNTIME_CAT, "Skipped FlushStart in state {:?}", state);
                                continue;
                            }
                        }
                    };

                    self = spawn_hook!(flush_start, self, &task_inner, &context).await;
                    task_inner
                        .lock()
                        .unwrap()
                        .switch_to_state(target_state, transition);
                    gst_trace!(RUNTIME_CAT, "Task flush started");
                }
                TransitionKind::FlushStop => {
                    let state = task_inner.lock().unwrap().state;
                    match state {
                        TaskState::Flushing => (),
                        TaskState::PausedFlushing => {
                            self = spawn_hook!(flush_stop, self, &task_inner, &context).await;
                            task_inner
                                .lock()
                                .unwrap()
                                .switch_to_state(TaskState::Paused, transition);
                            gst_trace!(RUNTIME_CAT, "Switched from PausedFlushing to Paused");
                            continue;
                        }
                        state => {
                            task_inner.lock().unwrap().skip_transition(transition);
                            gst_trace!(RUNTIME_CAT, "Skipped FlushStop in state {:?}", state);
                            continue;
                        }
                    }

                    self = spawn_hook!(flush_stop, self, &task_inner, &context).await;
                    self = StateMachine::spawn_loop(self, &task_inner, &context, transition).await;
                    // next/pending transition handled in next iteration
                }
                TransitionKind::Unprepare => {
                    StateMachine::spawn_unprepare(self, context).await;
                    task_inner
                        .lock()
                        .unwrap()
                        .switch_to_state(TaskState::Unprepared, transition);

                    break;
                }
                _ => unreachable!("State machine handler {:?}", transition),
            }
        }

        gst_trace!(RUNTIME_CAT, "Task state machine terminated");
    }

    async fn prepare(&mut self) -> Result<(), gst::ErrorMessage> {
        self.task_impl.prepare().await?;

        gst_trace!(RUNTIME_CAT, "Draining subtasks");
        while Context::current_has_sub_tasks() {
            Context::drain_sub_tasks().await.map_err(|err| {
                gst_error_msg!(
                    gst::ResourceError::OpenRead,
                    ["Failed to drain substasks while preparing: {:?}", err]
                )
            })?;
        }

        Ok(())
    }

    async fn run_loop(&mut self, task_inner: Arc<Mutex<TaskInner>>) -> Result<(), gst::FlowError> {
        gst_trace!(RUNTIME_CAT, "Task loop started");

        loop {
            // Check if there is any pending transition
            while let Ok(Some(transition)) = self.transition_rx.try_next() {
                gst_trace!(RUNTIME_CAT, "Task loop popped {:?}", transition);

                match transition.kind {
                    TransitionKind::Start => {
                        task_inner.lock().unwrap().skip_transition(transition);
                        gst_trace!(RUNTIME_CAT, "Skipped Start in state Started");
                    }
                    _ => {
                        gst_trace!(
                            RUNTIME_CAT,
                            "Task loop handing {:?} to state machine",
                            transition,
                        );
                        self.pending_transition = Some(transition);
                        return Ok(());
                    }
                }
            }

            // Run the iteration
            self.task_impl.iterate().await.map_err(|err| {
                gst_log!(RUNTIME_CAT, "Task loop iterate impl returned {:?}", err);
                err
            })?;
        }
    }

    async fn spawn_prepare(
        mut self,
        task_inner: &Arc<Mutex<TaskInner>>,
        context: &Context,
        transition: Transition,
    ) -> Self {
        let task_inner_clone = Arc::clone(&task_inner);
        let prepare_fut = async move {
            let (abortable_prepare, abort_handle) = abortable(self.prepare());
            task_inner_clone.lock().unwrap().prepare_abort_handle = Some(abort_handle);

            let res = abortable_prepare.await.unwrap_or_else(|_| {
                Err(gst_error_msg!(
                    gst::ResourceError::OpenRead,
                    ["Task preparation aborted"]
                ))
            });

            match res {
                Ok(()) => {
                    task_inner_clone
                        .lock()
                        .unwrap()
                        .switch_to_state(TaskState::Prepared, transition);
                    gst_log!(RUNTIME_CAT, "Task prepared");
                }
                Err(err) => {
                    {
                        let mut task_inner = task_inner_clone.lock().unwrap();
                        task_inner.skip_transition(transition);
                        task_inner.state = TaskState::PrepareFailed;
                    }

                    gst_error!(RUNTIME_CAT, "Task preparation failed: {:?}", err);
                    self.task_impl.handle_prepare_error(err).await;

                    gst_log!(
                        RUNTIME_CAT,
                        "Waiting for Unprepare due to task preparation failure"
                    );
                    loop {
                        let transition = self
                            .transition_rx
                            .next()
                            .await
                            .expect("transition_rx dropped");

                        if let TransitionKind::Unprepare = transition.kind {
                            self.pending_transition = Some(transition);
                            break;
                        } else {
                            gst_log!(
                                RUNTIME_CAT,
                                "Skipping {:?} since task preparation failed",
                                transition,
                            );

                            task_inner_clone.lock().unwrap().skip_transition(transition);
                        }
                    }
                }
            }

            self
        };

        let join_handle = {
            let mut task_inner = task_inner.lock().unwrap();
            let join_handle = context.awake_and_spawn(prepare_fut);
            task_inner.spawned_task_id = Some(join_handle.task_id());

            join_handle
        };

        join_handle.await.unwrap()
    }

    async fn spawn_loop(
        mut self,
        task_inner: &Arc<Mutex<TaskInner>>,
        context: &Context,
        transition: Transition,
    ) -> Self {
        let task_inner_clone = Arc::clone(&task_inner);
        let loop_fut = async move {
            gst_trace!(RUNTIME_CAT, "Starting task loop");
            self.task_impl.start().await;

            let abortable_task_loop = {
                let (abortable_task_loop, loop_abort_handle) =
                    abortable(self.run_loop(Arc::clone(&task_inner_clone)));

                let mut task_inner = task_inner_clone.lock().unwrap();
                task_inner.loop_abort_handle = Some(loop_abort_handle);
                task_inner.switch_to_state(TaskState::Started, transition);

                abortable_task_loop
            };

            match abortable_task_loop.await {
                Ok(Ok(())) => (),
                Ok(Err(gst::FlowError::Flushing)) => {
                    gst_trace!(RUNTIME_CAT, "Starting task flush");
                    self.task_impl.flush_start().await;
                    task_inner_clone.lock().unwrap().state = TaskState::Flushing;
                    gst_trace!(RUNTIME_CAT, "Started task flush");
                }
                Ok(Err(err)) => {
                    // Note: this includes EOS
                    gst_trace!(RUNTIME_CAT, "Stopping task due to {:?}", err);
                    self.task_impl.stop().await;
                    task_inner_clone.lock().unwrap().state = TaskState::Stopped;
                    gst_trace!(RUNTIME_CAT, "Stopped task due to {:?}", err);
                }
                Err(Aborted) => gst_trace!(RUNTIME_CAT, "Task loop aborted"),
            }

            // next/pending transition handled in state machine loop

            self
        };

        let join_handle = {
            let mut task_inner = task_inner.lock().unwrap();
            let join_handle = context.awake_and_spawn(loop_fut);
            task_inner.spawned_task_id = Some(join_handle.task_id());

            join_handle
        };

        join_handle.await.unwrap()
    }

    async fn spawn_unprepare(mut self, context: Context) {
        // Unprepare is not joined by an ack_rx but by joining the state machine
        // handle, so we don't need to keep track of the spwaned_task_id
        context
            .awake_and_spawn(async move {
                self.task_impl.unprepare().await;
            })
            .await
            .unwrap()
    }
}

#[cfg(test)]
mod tests {
    use futures::channel::{mpsc, oneshot};
    use std::time::Duration;

    use crate::runtime::Context;

    use super::*;

    #[tokio::test]
    async fn iterate() {
        gst::init().unwrap();

        struct TaskTest {
            prepared_sender: mpsc::Sender<()>,
            started_sender: mpsc::Sender<()>,
            iterate_sender: mpsc::Sender<()>,
            complete_iterate_receiver: mpsc::Receiver<Result<(), gst::FlowError>>,
            paused_sender: mpsc::Sender<()>,
            stopped_sender: mpsc::Sender<()>,
            flush_start_sender: mpsc::Sender<()>,
            unprepared_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskTest {
            fn prepare(&mut self) -> BoxFuture<'_, Result<(), gst::ErrorMessage>> {
                async move {
                    gst_debug!(RUNTIME_CAT, "task_iterate: prepared");
                    self.prepared_sender.send(()).await.unwrap();
                    Ok(())
                }
                .boxed()
            }

            fn start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "task_iterate: started");
                    self.started_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                async move {
                    gst_debug!(RUNTIME_CAT, "task_iterate: entering iterate");
                    self.iterate_sender.send(()).await.unwrap();

                    gst_debug!(
                        RUNTIME_CAT,
                        "task_iterate: awaiting complete_iterate_receiver"
                    );

                    let res = self.complete_iterate_receiver.next().await.unwrap();
                    if res.is_ok() {
                        gst_debug!(RUNTIME_CAT, "task_iterate: received true => keep looping");
                    } else {
                        gst_debug!(
                            RUNTIME_CAT,
                            "task_iterate: received false => cancelling loop"
                        );
                    }

                    res
                }
                .boxed()
            }

            fn pause(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "task_iterate: paused");
                    self.paused_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn stop(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "task_iterate: stopped");
                    self.stopped_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn flush_start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "task_iterate: stopped");
                    self.flush_start_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn unprepare(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "task_iterate: unprepared");
                    self.unprepared_sender.send(()).await.unwrap();
                }
                .boxed()
            }
        }

        let context = Context::acquire("task_iterate", 2).unwrap();

        let task = Task::default();

        assert_eq!(task.state(), TaskState::Unprepared);

        gst_debug!(RUNTIME_CAT, "task_iterate: preparing");

        let (prepared_sender, mut prepared_receiver) = mpsc::channel(1);
        let (started_sender, mut started_receiver) = mpsc::channel(1);
        let (iterate_sender, mut iterate_receiver) = mpsc::channel(1);
        let (mut complete_iterate_sender, complete_iterate_receiver) = mpsc::channel(1);
        let (paused_sender, mut paused_receiver) = mpsc::channel(1);
        let (stopped_sender, mut stopped_receiver) = mpsc::channel(1);
        let (flush_start_sender, mut flush_start_receiver) = mpsc::channel(1);
        let (unprepared_sender, mut unprepared_receiver) = mpsc::channel(1);
        task.prepare(
            TaskTest {
                prepared_sender,
                started_sender,
                iterate_sender,
                complete_iterate_receiver,
                paused_sender,
                stopped_sender,
                flush_start_sender,
                unprepared_sender,
            },
            context,
        )
        .unwrap();

        gst_debug!(RUNTIME_CAT, "task_iterate: starting (initial)");
        task.start();

        assert_eq!(task.state(), TaskState::Started);
        // At this point, prepared must be completed
        prepared_receiver.next().await.unwrap();
        // ... and start executed
        started_receiver.next().await.unwrap();

        assert_eq!(task.state(), TaskState::Started);

        // unlock task loop and keep looping
        iterate_receiver.next().await.unwrap();
        complete_iterate_sender.send(Ok(())).await.unwrap();

        gst_debug!(RUNTIME_CAT, "task_iterate: starting (redundant)");
        // start will return immediately
        task.start();
        assert_eq!(task.state(), TaskState::Started);

        gst_debug!(RUNTIME_CAT, "task_iterate: pause (initial)");
        task.pause();

        // Pause transition is asynchronous
        while TaskState::Paused != task.state() {
            tokio::time::delay_for(Duration::from_millis(2)).await;

            if let Ok(Some(())) = iterate_receiver.try_next() {
                // unlock iteration
                complete_iterate_sender.send(Ok(())).await.unwrap();
            }
        }

        gst_debug!(RUNTIME_CAT, "task_iterate: awaiting pause hook ack");
        paused_receiver.next().await.unwrap();

        gst_debug!(RUNTIME_CAT, "task_iterate: starting (after pause)");
        task.start();

        assert_eq!(task.state(), TaskState::Started);
        // Paused -> Started
        let _ = started_receiver.next().await;

        gst_debug!(RUNTIME_CAT, "task_iterate: stopping (initial)");
        task.stop();

        assert_eq!(task.state(), TaskState::Stopped);
        let _ = stopped_receiver.next().await;

        // purge remaining iteration received before stop if any
        let _ = iterate_receiver.try_next();

        gst_debug!(RUNTIME_CAT, "task_iterate: starting (after stop)");
        task.start();
        let _ = started_receiver.next().await;

        gst_debug!(RUNTIME_CAT, "task_iterate: req. iterate to return Eos");
        iterate_receiver.next().await.unwrap();
        complete_iterate_sender
            .send(Err(gst::FlowError::Eos))
            .await
            .unwrap();

        gst_debug!(RUNTIME_CAT, "task_iterate: awaiting stop hook ack");
        stopped_receiver.next().await.unwrap();

        // Wait for state machine to reach Stopped
        while TaskState::Stopped != task.state() {
            tokio::time::delay_for(Duration::from_millis(2)).await;
        }

        gst_debug!(RUNTIME_CAT, "task_iterate: starting (after stop)");
        task.start();
        let _ = started_receiver.next().await;

        gst_debug!(RUNTIME_CAT, "task_iterate: req. iterate to return Error");
        iterate_receiver.next().await.unwrap();
        complete_iterate_sender
            .send(Err(gst::FlowError::Error))
            .await
            .unwrap();

        gst_debug!(RUNTIME_CAT, "task_iterate: awaiting stop hook ack");
        stopped_receiver.next().await.unwrap();

        // Wait for state machine to reach Stopped
        while TaskState::Stopped != task.state() {
            tokio::time::delay_for(Duration::from_millis(2)).await;
        }

        gst_debug!(RUNTIME_CAT, "task_iterate: starting (after Error)");
        task.start();

        assert_eq!(task.state(), TaskState::Started);
        gst_debug!(RUNTIME_CAT, "task_iterate: awaiting start hook ack");
        let _ = started_receiver.next().await;

        gst_debug!(RUNTIME_CAT, "task_iterate: req. iterate to return Flushing");
        iterate_receiver.next().await.unwrap();
        complete_iterate_sender
            .send(Err(gst::FlowError::Flushing))
            .await
            .unwrap();

        gst_debug!(RUNTIME_CAT, "task_iterate: awaiting flush_start hook ack");
        flush_start_receiver.next().await.unwrap();

        // Wait for state machine to reach Flushing
        while TaskState::Flushing != task.state() {
            tokio::time::delay_for(Duration::from_millis(2)).await;
        }

        gst_debug!(RUNTIME_CAT, "task_iterate: stopping (final)");
        task.stop();

        assert_eq!(task.state(), TaskState::Stopped);
        let _ = stopped_receiver.next().await;

        task.unprepare().unwrap();

        assert_eq!(task.state(), TaskState::Unprepared);
        let _ = unprepared_receiver.next().await;
    }

    #[tokio::test]
    async fn prepare_error() {
        gst::init().unwrap();

        struct TaskPrepareTest {
            prepare_error_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskPrepareTest {
            fn prepare(&mut self) -> BoxFuture<'_, Result<(), gst::ErrorMessage>> {
                async move {
                    gst_debug!(RUNTIME_CAT, "prepare_error: prepare returning an error");
                    Err(gst_error_msg!(
                        gst::ResourceError::OpenRead,
                        ["prepare_error: intentional prepare error"]
                    ))
                }
                .boxed()
            }

            fn handle_prepare_error(&mut self, _err: gst::ErrorMessage) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "prepare_error: handling prepare error");
                    self.prepare_error_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                future::ok(()).boxed()
            }
        }

        let context = Context::acquire("prepare_error", 2).unwrap();

        let task = Task::default();

        assert_eq!(task.state(), TaskState::Unprepared);

        let (prepare_error_sender, mut prepare_error_receiver) = mpsc::channel(1);
        task.prepare(
            TaskPrepareTest {
                prepare_error_sender,
            },
            context,
        )
        .unwrap();

        gst_debug!(
            RUNTIME_CAT,
            "prepare_error: await prepare error notification"
        );
        prepare_error_receiver.next().await.unwrap();

        task.unprepare().unwrap();
    }

    #[tokio::test]
    async fn prepare_start_ok() {
        // Hold the preparation function so that it completes after the start request is engaged

        gst::init().unwrap();

        struct TaskPrepareTest {
            prepare_receiver: mpsc::Receiver<()>,
        }

        impl TaskImpl for TaskPrepareTest {
            fn prepare(&mut self) -> BoxFuture<'_, Result<(), gst::ErrorMessage>> {
                async move {
                    gst_debug!(
                        RUNTIME_CAT,
                        "prepare_start_ok: preparation awaiting trigger"
                    );
                    self.prepare_receiver.next().await.unwrap();
                    gst_debug!(RUNTIME_CAT, "prepare_start_ok: preparation complete Ok");

                    Ok(())
                }
                .boxed()
            }

            fn handle_prepare_error(&mut self, _err: gst::ErrorMessage) -> BoxFuture<'_, ()> {
                unreachable!("prepare_start_ok: handle_prepare_error");
            }

            fn start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "prepare_start_ok: started");
                }
                .boxed()
            }

            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                future::pending::<Result<(), gst::FlowError>>().boxed()
            }
        }

        let context = Context::acquire("prepare_start_ok", 2).unwrap();

        let task = Task::default();

        let (mut prepare_sender, prepare_receiver) = mpsc::channel(1);
        task.prepare(TaskPrepareTest { prepare_receiver }, context.clone())
            .unwrap();

        let start_ctx = Context::acquire("prepare_start_ok_requester", 0).unwrap();
        let task_clone = task.clone();
        let (ready_sender, ready_receiver) = oneshot::channel();
        let start_handle = start_ctx.spawn(async move {
            assert_eq!(task_clone.state(), TaskState::Preparing);
            gst_debug!(RUNTIME_CAT, "prepare_start_ok: starting");
            ready_sender.send(()).unwrap();
            task_clone.start();
            Context::drain_sub_tasks().await.unwrap();

            assert_eq!(task_clone.state(), TaskState::Started);

            task_clone.stop();
            Context::drain_sub_tasks().await.unwrap();

            task_clone.unprepare().unwrap();
            Context::drain_sub_tasks().await.unwrap();
        });

        gst_debug!(RUNTIME_CAT, "prepare_start_ok: awaiting for start_ctx");
        ready_receiver.await.unwrap();

        gst_debug!(RUNTIME_CAT, "prepare_start_ok: triggering preparation");
        prepare_sender.send(()).await.unwrap();

        start_handle.await.unwrap();
    }

    #[tokio::test]
    async fn prepare_start_error() {
        // Hold the preparation function so that it completes after the start request is engaged

        gst::init().unwrap();

        struct TaskPrepareTest {
            prepare_receiver: mpsc::Receiver<()>,
            prepare_error_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskPrepareTest {
            fn prepare(&mut self) -> BoxFuture<'_, Result<(), gst::ErrorMessage>> {
                async move {
                    gst_debug!(
                        RUNTIME_CAT,
                        "prepare_start_error: preparation awaiting trigger"
                    );
                    self.prepare_receiver.next().await.unwrap();
                    gst_debug!(RUNTIME_CAT, "prepare_start_error: preparation complete Err");

                    Err(gst_error_msg!(
                        gst::ResourceError::OpenRead,
                        ["prepare_start_error: intentional prepare error"]
                    ))
                }
                .boxed()
            }

            fn handle_prepare_error(&mut self, _err: gst::ErrorMessage) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "prepare_start_error: handling prepare error");
                    self.prepare_error_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn start(&mut self) -> BoxFuture<'_, ()> {
                unreachable!("prepare_start_error: start");
            }

            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                unreachable!("prepare_start_error: iterate");
            }
        }

        let context = Context::acquire("prepare_start_error", 2).unwrap();

        let task = Task::default();

        let (mut prepare_sender, prepare_receiver) = mpsc::channel(1);
        let (prepare_error_sender, mut prepare_error_receiver) = mpsc::channel(1);
        task.prepare(
            TaskPrepareTest {
                prepare_receiver,
                prepare_error_sender,
            },
            context,
        )
        .unwrap();

        let start_ctx = Context::acquire("prepare_start_error_requester", 0).unwrap();
        let task_clone = task.clone();
        let (ready_sender, ready_receiver) = oneshot::channel();
        let start_handle = start_ctx.spawn(async move {
            assert_eq!(task_clone.state(), TaskState::Preparing);
            gst_debug!(RUNTIME_CAT, "prepare_start_error: starting (Err)");
            ready_sender.send(()).unwrap();
            task_clone.start();
            Context::drain_sub_tasks().await.unwrap();

            assert_eq!(task_clone.state(), TaskState::PrepareFailed);
            task_clone.unprepare().unwrap();
            Context::drain_sub_tasks().await.unwrap();
        });

        gst_debug!(RUNTIME_CAT, "prepare_start_error: awaiting for start_ctx");
        ready_receiver.await.unwrap();

        gst_debug!(
            RUNTIME_CAT,
            "prepare_start_error: triggering preparation (failure)"
        );
        prepare_sender.send(()).await.unwrap();

        gst_debug!(
            RUNTIME_CAT,
            "prepare_start_error: await prepare error notification"
        );
        prepare_error_receiver.next().await.unwrap();

        start_handle.await.unwrap();
    }

    #[tokio::test]
    async fn pause_start() {
        gst::init().unwrap();

        struct TaskPauseStartTest {
            iterate_sender: mpsc::Sender<()>,
            complete_receiver: mpsc::Receiver<()>,
            paused_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskPauseStartTest {
            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                async move {
                    gst_debug!(RUNTIME_CAT, "pause_start: entering iteration");
                    self.iterate_sender.send(()).await.unwrap();

                    gst_debug!(RUNTIME_CAT, "pause_start: iteration awaiting completion");
                    self.complete_receiver.next().await.unwrap();
                    gst_debug!(RUNTIME_CAT, "pause_start: iteration complete");

                    Ok(())
                }
                .boxed()
            }

            fn pause(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "pause_start: paused");
                    self.paused_sender.send(()).await.unwrap();
                }
                .boxed()
            }
        }

        let context = Context::acquire("pause_start", 2).unwrap();

        let task = Task::default();

        let (iterate_sender, mut iterate_receiver) = mpsc::channel(1);
        let (mut complete_sender, complete_receiver) = mpsc::channel(0);
        let (paused_sender, mut paused_receiver) = mpsc::channel(1);
        task.prepare(
            TaskPauseStartTest {
                iterate_sender,
                complete_receiver,
                paused_sender,
            },
            context,
        )
        .unwrap();

        gst_debug!(RUNTIME_CAT, "pause_start: starting");
        task.start();
        assert_eq!(task.state(), TaskState::Started);

        gst_debug!(RUNTIME_CAT, "pause_start: awaiting 1st iteration");
        iterate_receiver.next().await.unwrap();

        gst_debug!(RUNTIME_CAT, "pause_start: pausing (1)");
        task.pause();

        gst_debug!(RUNTIME_CAT, "pause_start: sending 1st iteration completion");
        complete_sender.try_send(()).unwrap();

        // Pause transition is asynchronous
        while TaskState::Paused != task.state() {
            tokio::time::delay_for(Duration::from_millis(5)).await;
        }

        gst_debug!(RUNTIME_CAT, "pause_start: awaiting paused");
        let _ = paused_receiver.next().await;

        // Loop held on due to Pause
        iterate_receiver.try_next().unwrap_err();

        task.start();
        assert_eq!(task.state(), TaskState::Started);

        gst_debug!(RUNTIME_CAT, "pause_start: awaiting 2d iteration");
        iterate_receiver.next().await.unwrap();

        gst_debug!(RUNTIME_CAT, "pause_start: sending 2d iteration completion");
        complete_sender.try_send(()).unwrap();

        task.stop();
        task.unprepare().unwrap();
    }

    #[tokio::test]
    async fn successive_pause_start() {
        // Purpose: check pause cancellation.
        gst::init().unwrap();

        struct TaskPauseStartTest {
            iterate_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskPauseStartTest {
            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                async move {
                    gst_debug!(RUNTIME_CAT, "successive_pause_start: iteration");
                    self.iterate_sender.send(()).await.unwrap();

                    Ok(())
                }
                .boxed()
            }
        }

        let context = Context::acquire("successive_pause_start", 2).unwrap();

        let task = Task::default();

        let (iterate_sender, mut iterate_receiver) = mpsc::channel(1);
        task.prepare(TaskPauseStartTest { iterate_sender }, context)
            .unwrap();

        gst_debug!(RUNTIME_CAT, "successive_pause_start: starting");
        task.start();

        gst_debug!(RUNTIME_CAT, "successive_pause_start: awaiting iteration 1");
        iterate_receiver.next().await.unwrap();

        gst_debug!(RUNTIME_CAT, "successive_pause_start: pause and start");
        task.pause();
        task.start();

        assert_eq!(task.state(), TaskState::Started);

        gst_debug!(RUNTIME_CAT, "successive_pause_start: awaiting iteration 2");
        iterate_receiver.next().await.unwrap();

        gst_debug!(RUNTIME_CAT, "successive_pause_start: stopping");
        task.stop();
        task.unprepare().unwrap();
    }

    #[tokio::test]
    async fn flush_regular_sync() {
        gst::init().unwrap();

        struct TaskFlushTest {
            flush_start_sender: mpsc::Sender<()>,
            flush_stop_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskFlushTest {
            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                future::pending::<Result<(), gst::FlowError>>().boxed()
            }

            fn flush_start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "flush_regular_sync: started flushing");
                    self.flush_start_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn flush_stop(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "flush_regular_sync: stopped flushing");
                    self.flush_stop_sender.send(()).await.unwrap();
                }
                .boxed()
            }
        }

        let context = Context::acquire("flush_regular_sync", 2).unwrap();

        let task = Task::default();

        let (flush_start_sender, mut flush_start_receiver) = mpsc::channel(1);
        let (flush_stop_sender, mut flush_stop_receiver) = mpsc::channel(1);
        task.prepare(
            TaskFlushTest {
                flush_start_sender,
                flush_stop_sender,
            },
            context,
        )
        .unwrap();

        gst_debug!(RUNTIME_CAT, "flush_regular_sync: start");
        task.start();

        gst_debug!(RUNTIME_CAT, "flush_regular_sync: starting flush");
        task.flush_start();
        assert_eq!(task.state(), TaskState::Flushing);

        flush_start_receiver.next().await.unwrap();

        gst_debug!(RUNTIME_CAT, "flush_regular_sync: stopping flush");
        task.flush_stop();
        assert_eq!(task.state(), TaskState::Started);

        flush_stop_receiver.next().await.unwrap();

        task.pause();
        task.stop();
        task.unprepare().unwrap();
    }

    #[tokio::test]
    async fn flush_regular_different_context() {
        // Purpose: make sure a flush sequence triggered from a Context doesn't block.
        gst::init().unwrap();

        struct TaskFlushTest {
            flush_start_sender: mpsc::Sender<()>,
            flush_stop_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskFlushTest {
            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                future::pending::<Result<(), gst::FlowError>>().boxed()
            }

            fn flush_start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(
                        RUNTIME_CAT,
                        "flush_regular_different_context: started flushing"
                    );
                    self.flush_start_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn flush_stop(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(
                        RUNTIME_CAT,
                        "flush_regular_different_context: stopped flushing"
                    );
                    self.flush_stop_sender.send(()).await.unwrap();
                }
                .boxed()
            }
        }

        let context = Context::acquire("flush_regular_different_context", 2).unwrap();

        let task = Task::default();

        let (flush_start_sender, mut flush_start_receiver) = mpsc::channel(1);
        let (flush_stop_sender, mut flush_stop_receiver) = mpsc::channel(1);
        task.prepare(
            TaskFlushTest {
                flush_start_sender,
                flush_stop_sender,
            },
            context,
        )
        .unwrap();

        gst_debug!(RUNTIME_CAT, "flush_regular_different_context: start");
        task.start();

        let oob_context = Context::acquire("flush_regular_different_context_oob", 2).unwrap();

        let task_clone = task.clone();
        let flush_handle = oob_context.spawn(async move {
            task_clone.flush_start();
            Context::drain_sub_tasks().await.unwrap();
            assert_eq!(task_clone.state(), TaskState::Flushing);
            flush_start_receiver.next().await.unwrap();

            task_clone.flush_stop();
            Context::drain_sub_tasks().await.unwrap();
            assert_eq!(task_clone.state(), TaskState::Started);
        });

        flush_handle.await.unwrap();
        flush_stop_receiver.next().await.unwrap();

        task.stop();
        task.unprepare().unwrap();
    }

    #[tokio::test]
    async fn flush_regular_same_context() {
        // Purpose: make sure a flush sequence triggered from the same Context doesn't block.
        gst::init().unwrap();

        struct TaskFlushTest {
            flush_start_sender: mpsc::Sender<()>,
            flush_stop_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskFlushTest {
            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                future::pending::<Result<(), gst::FlowError>>().boxed()
            }

            fn flush_start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "flush_regular_same_context: started flushing");
                    self.flush_start_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn flush_stop(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "flush_regular_same_context: stopped flushing");
                    self.flush_stop_sender.send(()).await.unwrap();
                }
                .boxed()
            }
        }

        let context = Context::acquire("flush_regular_same_context", 2).unwrap();

        let task = Task::default();

        let (flush_start_sender, mut flush_start_receiver) = mpsc::channel(1);
        let (flush_stop_sender, mut flush_stop_receiver) = mpsc::channel(1);
        task.prepare(
            TaskFlushTest {
                flush_start_sender,
                flush_stop_sender,
            },
            context,
        )
        .unwrap();

        task.start();

        let task_clone = task.clone();
        let flush_handle = task.context().as_ref().unwrap().spawn(async move {
            task_clone.flush_start();
            Context::drain_sub_tasks().await.unwrap();
            assert_eq!(task_clone.state(), TaskState::Flushing);
            flush_start_receiver.next().await.unwrap();

            task_clone.flush_stop();
            Context::drain_sub_tasks().await.unwrap();
            assert_eq!(task_clone.state(), TaskState::Started);
        });

        flush_handle.await.unwrap();
        flush_stop_receiver.next().await.unwrap();

        task.stop();
        task.unprepare().unwrap();
    }

    #[tokio::test]
    async fn flush_from_loop() {
        // Purpose: make sure a flush_start transition triggered from an iteration doesn't block.
        gst::init().unwrap();

        struct TaskFlushTest {
            task: Task,
            flush_start_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskFlushTest {
            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                async move {
                    gst_debug!(RUNTIME_CAT, "flush_from_loop: flush_start from iteration");
                    self.task.flush_start();
                    Context::drain_sub_tasks().await
                }
                .boxed()
            }

            fn flush_start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "flush_from_loop: started flushing");
                    self.flush_start_sender.send(()).await.unwrap();
                }
                .boxed()
            }
        }

        let context = Context::acquire("flush_from_loop", 2).unwrap();

        let task = Task::default();

        let (flush_start_sender, mut flush_start_receiver) = mpsc::channel(1);
        task.prepare(
            TaskFlushTest {
                task: task.clone(),
                flush_start_sender,
            },
            context,
        )
        .unwrap();

        task.start();

        gst_debug!(
            RUNTIME_CAT,
            "flush_from_loop: awaiting flush_start notification"
        );
        flush_start_receiver.next().await.unwrap();

        task.stop();
        task.unprepare().unwrap();
    }

    #[tokio::test]
    async fn start_from_loop() {
        // Purpose: make sure a start transition triggered from an iteration doesn't block.
        // E.g. an auto pause cancellation after a delay.
        gst::init().unwrap();

        struct TaskStartTest {
            task: Task,
            iterate_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskStartTest {
            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                async move {
                    gst_debug!(RUNTIME_CAT, "start_from_loop: entering iteration");
                    self.iterate_sender.send(()).await.unwrap();

                    tokio::time::delay_for(Duration::from_millis(50)).await;

                    gst_debug!(RUNTIME_CAT, "start_from_loop: start from iteration");
                    self.task.start();
                    Context::drain_sub_tasks().await
                }
                .boxed()
            }
        }

        let context = Context::acquire("start_from_loop", 2).unwrap();

        let task = Task::default();

        let (iterate_sender, mut iterate_receiver) = mpsc::channel(1);
        task.prepare(
            TaskStartTest {
                task: task.clone(),
                iterate_sender,
            },
            context,
        )
        .unwrap();

        task.start();
        iterate_receiver.next().await.unwrap();
        task.pause();

        gst_debug!(RUNTIME_CAT, "start_from_loop: awaiting start notification");
        iterate_receiver.next().await.unwrap();

        task.stop();
        task.unprepare().unwrap();
    }

    #[tokio::test]
    async fn transition_from_hook() {
        // Purpose: make sure a transition triggered from a transition hook doesn't block.
        gst::init().unwrap();

        struct TaskFlushTest {
            task: Task,
            flush_stop_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskFlushTest {
            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                future::pending::<Result<(), gst::FlowError>>().boxed()
            }

            fn flush_start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(
                        RUNTIME_CAT,
                        "transition_from_hook: flush_start triggering flush_stop"
                    );
                    self.task.flush_stop();
                    Context::drain_sub_tasks().await.unwrap();
                }
                .boxed()
            }

            fn flush_stop(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "transition_from_hook: stopped flushing");
                    self.flush_stop_sender.send(()).await.unwrap();
                }
                .boxed()
            }
        }

        let context = Context::acquire("transition_from_hook", 2).unwrap();

        let task = Task::default();

        let (flush_stop_sender, mut flush_stop_receiver) = mpsc::channel(1);
        task.prepare(
            TaskFlushTest {
                task: task.clone(),
                flush_stop_sender,
            },
            context,
        )
        .unwrap();

        task.start();
        task.flush_start();

        gst_debug!(
            RUNTIME_CAT,
            "transition_from_hook: awaiting flush_stop notification"
        );
        flush_stop_receiver.next().await.unwrap();

        task.stop();
        task.unprepare().unwrap();
    }

    #[tokio::test]
    async fn pause_flush_start() {
        gst::init().unwrap();

        struct TaskFlushTest {
            started_sender: mpsc::Sender<()>,
            flush_start_sender: mpsc::Sender<()>,
            flush_stop_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskFlushTest {
            fn start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "pause_flush_start: started");
                    self.started_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                future::pending::<Result<(), gst::FlowError>>().boxed()
            }

            fn flush_start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "pause_flush_start: started flushing");
                    self.flush_start_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn flush_stop(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "pause_flush_start: stopped flushing");
                    self.flush_stop_sender.send(()).await.unwrap();
                }
                .boxed()
            }
        }

        let context = Context::acquire("pause_flush_start", 2).unwrap();

        let task = Task::default();

        let (started_sender, mut started_receiver) = mpsc::channel(1);
        let (flush_start_sender, mut flush_start_receiver) = mpsc::channel(1);
        let (flush_stop_sender, mut flush_stop_receiver) = mpsc::channel(1);
        task.prepare(
            TaskFlushTest {
                started_sender,
                flush_start_sender,
                flush_stop_sender,
            },
            context,
        )
        .unwrap();

        // Pause, FlushStart, FlushStop, Start

        gst_debug!(RUNTIME_CAT, "pause_flush_start: pausing");
        task.pause();

        gst_debug!(RUNTIME_CAT, "pause_flush_start: starting flush");
        task.flush_start();
        assert_eq!(task.state(), TaskState::PausedFlushing);
        flush_start_receiver.next().await;

        gst_debug!(RUNTIME_CAT, "pause_flush_start: stopping flush");
        task.flush_stop();
        assert_eq!(task.state(), TaskState::Paused);
        flush_stop_receiver.next().await;

        // start hook not executed
        started_receiver.try_next().unwrap_err();

        gst_debug!(RUNTIME_CAT, "pause_flush_start: starting after flushing");
        task.start();
        assert_eq!(task.state(), TaskState::Started);
        started_receiver.next().await;

        task.stop();
        task.unprepare().unwrap();
    }

    #[tokio::test]
    async fn pause_flushing_start() {
        gst::init().unwrap();

        struct TaskFlushTest {
            started_sender: mpsc::Sender<()>,
            flush_start_sender: mpsc::Sender<()>,
            flush_stop_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskFlushTest {
            fn start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "pause_flushing_start: started");
                    self.started_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                future::pending::<Result<(), gst::FlowError>>().boxed()
            }

            fn flush_start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "pause_flushing_start: started flushing");
                    self.flush_start_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn flush_stop(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "pause_flushing_start: stopped flushing");
                    self.flush_stop_sender.send(()).await.unwrap();
                }
                .boxed()
            }
        }

        let context = Context::acquire("pause_flushing_start", 2).unwrap();

        let task = Task::default();

        let (started_sender, mut started_receiver) = mpsc::channel(1);
        let (flush_start_sender, mut flush_start_receiver) = mpsc::channel(1);
        let (flush_stop_sender, mut flush_stop_receiver) = mpsc::channel(1);
        task.prepare(
            TaskFlushTest {
                started_sender,
                flush_start_sender,
                flush_stop_sender,
            },
            context,
        )
        .unwrap();

        // Pause, FlushStart, Start, FlushStop

        gst_debug!(RUNTIME_CAT, "pause_flushing_start: pausing");
        task.pause();

        gst_debug!(RUNTIME_CAT, "pause_flushing_start: starting flush");
        task.flush_start();
        assert_eq!(task.state(), TaskState::PausedFlushing);
        flush_start_receiver.next().await;

        gst_debug!(RUNTIME_CAT, "pause_flushing_start: starting while flushing");
        task.start();
        assert_eq!(task.state(), TaskState::Flushing);

        // start hook not executed
        started_receiver.try_next().unwrap_err();

        gst_debug!(RUNTIME_CAT, "pause_flushing_start: stopping flush");
        task.flush_stop();
        assert_eq!(task.state(), TaskState::Started);
        flush_stop_receiver.next().await;
        started_receiver.next().await;

        task.stop();
        task.unprepare().unwrap();
    }

    #[tokio::test]
    async fn flush_concurrent_start() {
        // Purpose: check the racy case of start being triggered in // after flush_start
        // e.g.: a FlushStart event received on a Pad and the element starting after a Pause
        gst::init().unwrap();

        struct TaskStartTest {
            flush_start_sender: mpsc::Sender<()>,
            flush_stop_sender: mpsc::Sender<()>,
        }

        impl TaskImpl for TaskStartTest {
            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                future::pending::<Result<(), gst::FlowError>>().boxed()
            }

            fn flush_start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "flush_concurrent_start: started flushing");
                    self.flush_start_sender.send(()).await.unwrap();
                }
                .boxed()
            }

            fn flush_stop(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    gst_debug!(RUNTIME_CAT, "flush_concurrent_start: stopped flushing");
                    self.flush_stop_sender.send(()).await.unwrap();
                }
                .boxed()
            }
        }

        let context = Context::acquire("flush_concurrent_start", 2).unwrap();

        let task = Task::default();

        let (flush_start_sender, mut flush_start_receiver) = mpsc::channel(1);
        let (flush_stop_sender, mut flush_stop_receiver) = mpsc::channel(1);
        task.prepare(
            TaskStartTest {
                flush_start_sender,
                flush_stop_sender,
            },
            context,
        )
        .unwrap();

        let oob_context = Context::acquire("flush_concurrent_start_oob", 2).unwrap();
        let task_clone = task.clone();

        task.start();
        task.pause();

        // Launch flush_start // start
        let (ready_sender, ready_receiver) = oneshot::channel();
        gst_debug!(RUNTIME_CAT, "flush_concurrent_start: spawning flush_start");
        let flush_start_handle = oob_context.spawn(async move {
            gst_debug!(RUNTIME_CAT, "flush_concurrent_start: // flush_start");
            ready_sender.send(()).unwrap();
            task_clone.flush_start();
            Context::drain_sub_tasks().await.unwrap();
            flush_start_receiver.next().await.unwrap();
        });

        gst_debug!(
            RUNTIME_CAT,
            "flush_concurrent_start: awaiting for oob_context"
        );
        ready_receiver.await.unwrap();

        gst_debug!(RUNTIME_CAT, "flush_concurrent_start: // start");
        task.start();

        flush_start_handle.await.unwrap();

        gst_debug!(RUNTIME_CAT, "flush_concurrent_start: requesting flush_stop");
        task.flush_stop();

        assert_eq!(task.state(), TaskState::Started);
        flush_stop_receiver.next().await;

        task.stop();
        task.unprepare().unwrap();
    }

    #[tokio::test]
    async fn start_timer() {
        // Purpose: make sure a Timer initialized in a transition is
        // available when iterating in the loop.
        gst::init().unwrap();

        struct TaskTimerTest {
            timer: Option<tokio::time::Delay>,
            timer_elapsed_sender: Option<oneshot::Sender<()>>,
        }

        impl TaskImpl for TaskTimerTest {
            fn start(&mut self) -> BoxFuture<'_, ()> {
                async move {
                    self.timer = Some(tokio::time::delay_for(Duration::from_millis(50)));
                    gst_debug!(RUNTIME_CAT, "start_timer: started");
                }
                .boxed()
            }

            fn iterate(&mut self) -> BoxFuture<'_, Result<(), gst::FlowError>> {
                async move {
                    gst_debug!(RUNTIME_CAT, "start_timer: awaiting timer");
                    self.timer.take().unwrap().await;
                    gst_debug!(RUNTIME_CAT, "start_timer: timer elapsed");

                    if let Some(timer_elapsed_sender) = self.timer_elapsed_sender.take() {
                        timer_elapsed_sender.send(()).unwrap();
                    }

                    Err(gst::FlowError::Eos)
                }
                .boxed()
            }
        }

        let context = Context::acquire("start_timer", 2).unwrap();

        let task = Task::default();

        let (timer_elapsed_sender, timer_elapsed_receiver) = oneshot::channel();
        task.prepare(
            TaskTimerTest {
                timer: None,
                timer_elapsed_sender: Some(timer_elapsed_sender),
            },
            context,
        )
        .unwrap();

        gst_debug!(RUNTIME_CAT, "start_timer: start");
        task.start();

        timer_elapsed_receiver.await.unwrap();
        gst_debug!(RUNTIME_CAT, "start_timer: timer elapsed received");

        task.stop();
        task.unprepare().unwrap();
    }
}