summaryrefslogtreecommitdiff
path: root/subprojects/gst-plugins-base/gst/playback/gsturidecodebin3.c
blob: 8f7181c493fb61a48e7db14f37c06ace34cf1367 (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
/* GStreamer
 * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.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 St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

/**
 * SECTION:element-uridecodebin3
 * @title: uridecodebin3
 *
 * Decodes data from a URI into raw media. It selects a source element that can
 * handle the given #GstURIDecodeBin3:uri scheme and connects it to a decodebin3.
 */

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

#include <string.h>

#include <gst/gst.h>
#include <glib/gi18n-lib.h>
#include <gst/pbutils/missing-plugins.h>

#include "gstplay-enum.h"
#include "gstrawcaps.h"
#include "gstplaybackelements.h"
#include "gstplaybackutils.h"

#define GST_TYPE_URI_DECODE_BIN3 \
  (gst_uri_decode_bin3_get_type())
#define GST_URI_DECODE_BIN3(obj) \
  (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_URI_DECODE_BIN3,GstURIDecodeBin3))
#define GST_URI_DECODE_BIN3_CLASS(klass) \
  (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_URI_DECODE_BIN3,GstURIDecodeBin3Class))
#define GST_IS_URI_DECODE_BIN3(obj) \
  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_URI_DECODE_BIN3))
#define GST_IS_URI_DECODE_BIN3_CLASS(klass) \
  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_URI_DECODE_BIN3))
#define GST_URI_DECODE_BIN3_CAST(obj) ((GstURIDecodeBin3 *) (obj))

typedef struct _GstSourceGroup GstSourceGroup;
typedef struct _GstURIDecodeBin3 GstURIDecodeBin3;
typedef struct _GstURIDecodeBin3Class GstURIDecodeBin3Class;

typedef struct _GstPlayItem GstPlayItem;
typedef struct _GstSourceItem GstSourceItem;
typedef struct _GstSourceHandler GstSourceHandler;
typedef struct _GstSourcePad GstSourcePad;
typedef struct _OutputPad OutputPad;

/* A structure describing a play item, which travels through the elements
 * over time.
 *
 * All source items in this play item will be played together. Corresponds to an
 * end-user "play item" (ex: one item from a playlist, even though it might be
 * using a main content and subtitle content).
 */
struct _GstPlayItem
{
  GstURIDecodeBin3 *uridecodebin;

  /* Main URI */
  GstSourceItem *main_item;

  /* Auxiliary URI */
  /* FIXME : Replace by a list later */
  GstSourceItem *sub_item;

  /* The group_id used to identify this play item via STREAM_START events
   * This is the group_id which will be used externally (i.e. rewritten
   * to outgoing STREAM_START events and in emitted signals).
   * The urisourcebin-specific group_id is located in GstSourceItem */
  guint group_id;

  /* The two following variables are required for gapless, since there could be
   * a play item which is started which is different from the one currently
   * being outputted */

  /* active: TRUE if the backing urisourcebin were created */
  gboolean active;

  /* Whether about-to-finish was already posted for this play item */
  gboolean posted_about_to_finish;

  /* Whether about-to-finish should be posted once this play item becomes the
   * current input item */
  gboolean pending_about_to_finish;
};

/* The actual "source" component of a "play item"
 *
 * This is defined by having a URI, is backed by a `GstSourceHandler`.
 */
struct _GstSourceItem
{
  /* The GstPlayItem to which this GstSourceItem belongs to */
  GstPlayItem *play_item;

  gchar *uri;

  /* The urisourcebin controlling this uri
   * Can be NULL */
  GstSourceHandler *handler;
};

/* Structure wrapping everything related to a urisourcebin */
struct _GstSourceHandler
{
  GstURIDecodeBin3 *uridecodebin;
  GstPlayItem *play_item;

  GstElement *urisourcebin;

  /* Signal handlers */
  gulong pad_added_id;
  gulong pad_removed_id;
  gulong source_setup_id;
  gulong about_to_finish_id;

  /* TRUE if the controlled urisourcebin was added to uridecodebin */
  gboolean active;

  /* TRUE if the urisourcebin handles main item */
  gboolean is_main_source;

  /* buffering message stored for after switching */
  GstMessage *pending_buffering_msg;

  /* TRUE if urisourcebin handles stream-selection */
  gboolean upstream_selected;

  /* Number of expected sourcepads. Default 1, else it's the number of streams
   * specified by GST_MESSAGE_SELECTED_STREAMS from the source */
  guint expected_pads;

  /* List of GstSourcePad */
  GList *sourcepads;
};

/* Structure wrapping everything related to a urisourcebin pad */
struct _GstSourcePad
{
  GstSourceHandler *handler;

  GstPad *src_pad;

  /* GstStream (if present) */
  GstStream *stream;

  /* Decodebin3 pad to which src_pad is linked to */
  GstPad *db3_sink_pad;

  /* TRUE if db3_sink_pad is a request pad */
  gboolean db3_pad_is_request;

  /* TRUE if EOS went through the source pad. Marked as TRUE if decodebin3
   * notified `about-to-finish` for pull mode */
  gboolean saw_eos;

  /* Downstream blocking probe id. Only set/valid if we need to block this
   * pad */
  gulong block_probe_id;

  /* Downstream event probe id */
  gulong event_probe_id;
};

/* Controls an output source pad */
struct _OutputPad
{
  GstURIDecodeBin3 *uridecodebin;

  GstPad *target_pad;
  GstPad *ghost_pad;

  /* Downstream event probe id */
  gulong probe_id;

  /* The last seen (i.e. current) group_id
   * Can be (guint)-1 if no group_id was seen yet */
  guint current_group_id;
};

#define PLAY_ITEMS_GET_LOCK(d) (&(GST_URI_DECODE_BIN3_CAST(d)->play_items_lock))
#define PLAY_ITEMS_LOCK(d) G_STMT_START { \
    GST_TRACE("Locking play_items from thread %p", g_thread_self()); \
    g_mutex_lock (PLAY_ITEMS_GET_LOCK (d)); \
    GST_TRACE("Locked play_items from thread %p", g_thread_self()); \
 } G_STMT_END

#define PLAY_ITEMS_UNLOCK(d) G_STMT_START { \
    GST_TRACE("Unlocking play_items from thread %p", g_thread_self()); \
    g_mutex_unlock (PLAY_ITEMS_GET_LOCK (d)); \
 } G_STMT_END

/**
 * GstURIDecodeBin3
 *
 * uridecodebin3 element struct
 */
struct _GstURIDecodeBin3
{
  GstBin parent_instance;

  /* Properties */
  GstElement *source;
  guint64 connection_speed;     /* In bits/sec (0 = unknown) */
  GstCaps *caps;
  guint64 buffer_duration;      /* When buffering, buffer duration (ns) */
  guint buffer_size;            /* When buffering, buffer size (bytes) */
  gboolean download;
  gboolean use_buffering;
  guint64 ring_buffer_max_size;
  gboolean instant_uri;         /* Whether URI changes should be applied immediately or not */

  /* Mutex to protect play_items/input_item/output_item */
  GMutex play_items_lock;

  /* Notify that the input_item sources have all drained */
  GCond input_source_drained;

  /* List of GstPlayItem ordered by time of creation (first is oldest, new ones
   * are appended) */
  GList *play_items;

  /* Play item currently feeding decodebin3. */
  GstPlayItem *input_item;

  /* Play item currently outputted by decodebin3 */
  GstPlayItem *output_item;

  /* A global decodebin3 that's used to actually do decoding */
  GstElement *decodebin;

  /* db3 signals */
  gulong db_pad_added_id;
  gulong db_pad_removed_id;
  gulong db_select_stream_id;
  gulong db_about_to_finish_id;

  /* 1 if shutting down */
  gint shutdown;

  GList *output_pads;           /* List of OutputPad */
};

static GstStateChangeReturn activate_play_item (GstPlayItem * item);

static gint
gst_uridecodebin3_select_stream (GstURIDecodeBin3 * dbin,
    GstStreamCollection * collection, GstStream * stream)
{
  GST_LOG_OBJECT (dbin, "default select-stream, returning -1");

  return -1;
}

struct _GstURIDecodeBin3Class
{
  GstBinClass parent_class;

    gint (*select_stream) (GstURIDecodeBin3 * dbin,
      GstStreamCollection * collection, GstStream * stream);
};

GST_DEBUG_CATEGORY_STATIC (gst_uri_decode_bin3_debug);
#define GST_CAT_DEFAULT gst_uri_decode_bin3_debug

/* signals */
enum
{
  SIGNAL_SELECT_STREAM,
  SIGNAL_SOURCE_SETUP,
  SIGNAL_ABOUT_TO_FINISH,
  LAST_SIGNAL
};

/* properties */
#define DEFAULT_PROP_URI            NULL
#define DEFAULT_PROP_SUBURI            NULL
#define DEFAULT_CONNECTION_SPEED    0
#define DEFAULT_CAPS                (gst_static_caps_get (&default_raw_caps))
#define DEFAULT_BUFFER_DURATION     -1
#define DEFAULT_BUFFER_SIZE         -1
#define DEFAULT_DOWNLOAD            FALSE
#define DEFAULT_USE_BUFFERING       FALSE
#define DEFAULT_RING_BUFFER_MAX_SIZE 0
#define DEFAULT_INSTANT_URI         FALSE

enum
{
  PROP_0,
  PROP_URI,
  PROP_CURRENT_URI,
  PROP_SUBURI,
  PROP_CURRENT_SUBURI,
  PROP_SOURCE,
  PROP_CONNECTION_SPEED,
  PROP_BUFFER_SIZE,
  PROP_BUFFER_DURATION,
  PROP_DOWNLOAD,
  PROP_USE_BUFFERING,
  PROP_RING_BUFFER_MAX_SIZE,
  PROP_CAPS,
  PROP_INSTANT_URI
};

static guint gst_uri_decode_bin3_signals[LAST_SIGNAL] = { 0 };

static GstStaticCaps default_raw_caps = GST_STATIC_CAPS (DEFAULT_RAW_CAPS);

static GstStaticPadTemplate video_src_template =
GST_STATIC_PAD_TEMPLATE ("video_%u",
    GST_PAD_SRC,
    GST_PAD_SOMETIMES,
    GST_STATIC_CAPS_ANY);

static GstStaticPadTemplate audio_src_template =
GST_STATIC_PAD_TEMPLATE ("audio_%u",
    GST_PAD_SRC,
    GST_PAD_SOMETIMES,
    GST_STATIC_CAPS_ANY);

static GstStaticPadTemplate text_src_template =
GST_STATIC_PAD_TEMPLATE ("text_%u",
    GST_PAD_SRC,
    GST_PAD_SOMETIMES,
    GST_STATIC_CAPS_ANY);

static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src_%u",
    GST_PAD_SRC,
    GST_PAD_SOMETIMES,
    GST_STATIC_CAPS_ANY);

GType gst_uri_decode_bin3_get_type (void);
#define gst_uri_decode_bin3_parent_class parent_class
G_DEFINE_TYPE (GstURIDecodeBin3, gst_uri_decode_bin3, GST_TYPE_BIN);

#define _do_init \
    GST_DEBUG_CATEGORY_INIT (gst_uri_decode_bin3_debug, "uridecodebin3", 0, "URI decoder element 3"); \
    playback_element_init (plugin);
GST_ELEMENT_REGISTER_DEFINE_WITH_CODE (uridecodebin3, "uridecodebin3",
    GST_RANK_NONE, GST_TYPE_URI_DECODE_BIN3, _do_init);

#define REMOVE_SIGNAL(obj,id)            \
if (id) {                                \
  g_signal_handler_disconnect (obj, id); \
  id = 0;                                \
}

static void gst_uri_decode_bin3_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec);
static void gst_uri_decode_bin3_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec);
static void gst_uri_decode_bin3_dispose (GObject * obj);
static GstSourceHandler *new_source_handler (GstURIDecodeBin3 * uridecodebin,
    GstPlayItem * item, gboolean is_main);
static void free_source_handler (GstURIDecodeBin3 * uridecodebin,
    GstSourceHandler * item);
static void free_source_item (GstURIDecodeBin3 * uridecodebin,
    GstSourceItem * item);

static GstPlayItem *new_play_item (GstURIDecodeBin3 * dec);
static void free_play_item (GstURIDecodeBin3 * dec, GstPlayItem * item);
static gboolean play_item_is_eos (GstPlayItem * item);
static void play_item_set_eos (GstPlayItem * item);
static gboolean play_item_has_all_pads (GstPlayItem * item);

static void gst_uri_decode_bin3_set_uri (GstURIDecodeBin3 * dec,
    const gchar * uri);
static void gst_uri_decode_bin3_set_suburi (GstURIDecodeBin3 * dec,
    const gchar * uri);

static GstStateChangeReturn gst_uri_decode_bin3_change_state (GstElement *
    element, GstStateChange transition);
static gboolean gst_uri_decodebin3_send_event (GstElement * element,
    GstEvent * event);
static void gst_uri_decode_bin3_handle_message (GstBin * bin, GstMessage * msg);

static gboolean
_gst_int_accumulator (GSignalInvocationHint * ihint,
    GValue * return_accu, const GValue * handler_return, gpointer dummy)
{
  gint res = g_value_get_int (handler_return);

  g_value_set_int (return_accu, res);

  if (res == -1)
    return TRUE;

  return FALSE;
}


static void
gst_uri_decode_bin3_class_init (GstURIDecodeBin3Class * klass)
{
  GObjectClass *gobject_class;
  GstElementClass *gstelement_class;
  GstBinClass *gstbin_class;

  gobject_class = G_OBJECT_CLASS (klass);
  gstelement_class = GST_ELEMENT_CLASS (klass);
  gstbin_class = GST_BIN_CLASS (klass);

  gobject_class->set_property = gst_uri_decode_bin3_set_property;
  gobject_class->get_property = gst_uri_decode_bin3_get_property;
  gobject_class->dispose = gst_uri_decode_bin3_dispose;

  g_object_class_install_property (gobject_class, PROP_URI,
      g_param_spec_string ("uri", "URI", "URI to decode",
          DEFAULT_PROP_URI, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  g_object_class_install_property (gobject_class, PROP_CURRENT_URI,
      g_param_spec_string ("current-uri", "Current URI",
          "The currently playing URI", NULL,
          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));

  g_object_class_install_property (gobject_class, PROP_SUBURI,
      g_param_spec_string ("suburi", ".sub-URI", "Optional URI of a subtitle",
          NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  g_object_class_install_property (gobject_class, PROP_CURRENT_SUBURI,
      g_param_spec_string ("current-suburi", "Current .sub-URI",
          "The currently playing URI of a subtitle",
          NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));

  g_object_class_install_property (gobject_class, PROP_SOURCE,
      g_param_spec_object ("source", "Source", "Source object used",
          GST_TYPE_ELEMENT, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));

  g_object_class_install_property (gobject_class, PROP_CONNECTION_SPEED,
      g_param_spec_uint64 ("connection-speed", "Connection Speed",
          "Network connection speed in kbps (0 = unknown)",
          0, G_MAXUINT64 / 1000, DEFAULT_CONNECTION_SPEED,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  g_object_class_install_property (gobject_class, PROP_BUFFER_SIZE,
      g_param_spec_int ("buffer-size", "Buffer size (bytes)",
          "Buffer size when buffering streams (-1 default value)",
          -1, G_MAXINT, DEFAULT_BUFFER_SIZE,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  g_object_class_install_property (gobject_class, PROP_BUFFER_DURATION,
      g_param_spec_int64 ("buffer-duration", "Buffer duration (ns)",
          "Buffer duration when buffering streams (-1 default value)",
          -1, G_MAXINT64, DEFAULT_BUFFER_DURATION,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstURIDecodeBin3::download:
   *
   * For certain media type, enable download buffering.
   */
  g_object_class_install_property (gobject_class, PROP_DOWNLOAD,
      g_param_spec_boolean ("download", "Download",
          "Attempt download buffering when buffering network streams",
          DEFAULT_DOWNLOAD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  /**
   * GstURIDecodeBin3::use-buffering:
   *
   * Emit BUFFERING messages based on low-/high-percent thresholds of the
   * demuxed or parsed data.
   * When download buffering is activated and used for the current media
   * type, this property does nothing. Otherwise perform buffering on the
   * demuxed or parsed media.
   */
  g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
      g_param_spec_boolean ("use-buffering", "Use Buffering",
          "Perform buffering on demuxed/parsed media",
          DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstURIDecodeBin3::ring-buffer-max-size
   *
   * The maximum size of the ring buffer in kilobytes. If set to 0, the ring
   * buffer is disabled. Default is 0.
   */
  g_object_class_install_property (gobject_class, PROP_RING_BUFFER_MAX_SIZE,
      g_param_spec_uint64 ("ring-buffer-max-size",
          "Max. ring buffer size (bytes)",
          "Max. amount of data in the ring buffer (bytes, 0 = ring buffer disabled)",
          0, G_MAXUINT, DEFAULT_RING_BUFFER_MAX_SIZE,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  g_object_class_install_property (gobject_class, PROP_CAPS,
      g_param_spec_boxed ("caps", "Caps",
          "The caps on which to stop decoding. (NULL = default)",
          GST_TYPE_CAPS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstURIDecodeBin3:instant-uri:
   *
   * Changes to uri are applied immediately (instead of on EOS or when the
   * element is set back to PLAYING).
   *
   * Since: 1.22
   */
  g_object_class_install_property (gobject_class, PROP_INSTANT_URI,
      g_param_spec_boolean ("instant-uri", "Instantaneous URI change",
          "When enabled, URI changes are applied immediately",
          DEFAULT_INSTANT_URI, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstURIDecodebin3::select-stream
   * @decodebin: a #GstURIDecodebin3
   * @collection: a #GstStreamCollection
   * @stream: a #GstStream
   *
   * This signal is emitted whenever @decodebin needs to decide whether
   * to expose a @stream of a given @collection.
   *
   * Note that the prefered way to select streams is to listen to
   * GST_MESSAGE_STREAM_COLLECTION on the bus and send a
   * GST_EVENT_SELECT_STREAMS with the streams the user wants.
   *
   * Returns: 1 if the stream should be selected, 0 if it shouldn't be selected.
   * A value of -1 (default) lets @decodebin decide what to do with the stream.
   * */
  gst_uri_decode_bin3_signals[SIGNAL_SELECT_STREAM] =
      g_signal_new ("select-stream", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstURIDecodeBin3Class, select_stream),
      _gst_int_accumulator, NULL, NULL, G_TYPE_INT, 2,
      GST_TYPE_STREAM_COLLECTION, GST_TYPE_STREAM);

  /**
   * GstURIDecodeBin3::source-setup:
   * @bin: the uridecodebin.
   * @source: source element
   *
   * This signal is emitted after a source element has been created, so
   * it can be configured by setting additional properties (e.g. set a
   * proxy server for an http source, or set the device and read speed for
   * an audio cd source).
   */
  gst_uri_decode_bin3_signals[SIGNAL_SOURCE_SETUP] =
      g_signal_new ("source-setup", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
  /**
   * GstURIDecodeBin3::about-to-finish:
   *
   * This signal is emitted when the data for the selected URI is
   * entirely buffered and it is safe to specify another URI.
   */
  gst_uri_decode_bin3_signals[SIGNAL_ABOUT_TO_FINISH] =
      g_signal_new ("about-to-finish", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 0, G_TYPE_NONE);


  gst_element_class_add_static_pad_template (gstelement_class,
      &video_src_template);
  gst_element_class_add_static_pad_template (gstelement_class,
      &audio_src_template);
  gst_element_class_add_static_pad_template (gstelement_class,
      &text_src_template);
  gst_element_class_add_static_pad_template (gstelement_class, &src_template);
  gst_element_class_set_static_metadata (gstelement_class,
      "URI Decoder", "Generic/Bin/Decoder",
      "Autoplug and decode an URI to raw media",
      "Edward Hervey <edward@centricular.com>, Jan Schmidt <jan@centricular.com>");

  gstelement_class->change_state = gst_uri_decode_bin3_change_state;
  gstelement_class->send_event =
      GST_DEBUG_FUNCPTR (gst_uri_decodebin3_send_event);

  gstbin_class->handle_message = gst_uri_decode_bin3_handle_message;

  klass->select_stream = gst_uridecodebin3_select_stream;
}

static void
check_output_group_id (GstURIDecodeBin3 * dec)
{
  GList *iter;
  guint common_group_id = GST_GROUP_ID_INVALID;

  PLAY_ITEMS_LOCK (dec);

  for (iter = dec->output_pads; iter; iter = iter->next) {
    OutputPad *pad = iter->data;

    if (common_group_id == GST_GROUP_ID_INVALID)
      common_group_id = pad->current_group_id;
    else if (common_group_id != pad->current_group_id) {
      GST_DEBUG_OBJECT (dec, "transitioning output play item");
      PLAY_ITEMS_UNLOCK (dec);
      return;
    }
  }

  if (dec->output_item->group_id == common_group_id) {
    GST_DEBUG_OBJECT (dec, "Output play item %d fully active", common_group_id);
  } else if (dec->output_item->group_id == GST_GROUP_ID_INVALID) {
    /* This can happen for pull-based situations */
    GST_DEBUG_OBJECT (dec, "Assigning group id %u to current output play item",
        common_group_id);
    dec->output_item->group_id = common_group_id;
  } else if (common_group_id != GST_GROUP_ID_INVALID &&
      dec->output_item->group_id != common_group_id) {
    GstPlayItem *previous_item = dec->output_item;
    GST_DEBUG_OBJECT (dec, "Output play item %d fully active", common_group_id);
    if (g_list_length (dec->play_items) > 1) {
      dec->play_items = g_list_remove (dec->play_items, previous_item);
      dec->output_item = dec->play_items->data;
      dec->output_item->group_id = common_group_id;
      free_play_item (dec, previous_item);
    }
  }

  PLAY_ITEMS_UNLOCK (dec);
}

static GstPadProbeReturn
db_src_probe (GstPad * pad, GstPadProbeInfo * info, OutputPad * output)
{
  GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
  GstURIDecodeBin3 *uridecodebin = output->uridecodebin;

  GST_DEBUG_OBJECT (pad, "event %" GST_PTR_FORMAT, event);

  /* EOS : Mark pad as EOS */

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_EOS:
    {
      /* If there is a next input, drop the EOS event */
      if (uridecodebin->input_item != uridecodebin->output_item ||
          uridecodebin->input_item !=
          g_list_last (uridecodebin->play_items)->data) {
        GST_DEBUG_OBJECT (uridecodebin,
            "Dropping EOS event because in gapless mode");
        return GST_PAD_PROBE_DROP;
      }
      break;
    }
    case GST_EVENT_STREAM_START:
    {
      /* STREAM_START : Store group_id and check if currently active
       *  PlayEntry changed */
      if (gst_event_parse_group_id (event, &output->current_group_id)) {
        GST_DEBUG_OBJECT (pad, "current group id %" G_GUINT32_FORMAT,
            output->current_group_id);
        /* Check if we switched over to a new output */
        check_output_group_id (uridecodebin);
      }

      break;
    }
    default:
      break;
  }


  return GST_PAD_PROBE_OK;
}

static OutputPad *
add_output_pad (GstURIDecodeBin3 * dec, GstPad * target_pad)
{
  OutputPad *output;
  gchar *pad_name;
  GstEvent *stream_start;

  output = g_slice_new0 (OutputPad);

  GST_LOG_OBJECT (dec, "Created output %p", output);

  output->uridecodebin = dec;
  output->target_pad = target_pad;
  output->current_group_id = GST_GROUP_ID_INVALID;
  pad_name = gst_pad_get_name (target_pad);
  output->ghost_pad = gst_ghost_pad_new (pad_name, target_pad);
  g_free (pad_name);

  gst_pad_set_active (output->ghost_pad, TRUE);

  stream_start = gst_pad_get_sticky_event (target_pad,
      GST_EVENT_STREAM_START, 0);
  if (stream_start) {
    gst_pad_store_sticky_event (output->ghost_pad, stream_start);
    gst_event_unref (stream_start);
  } else {
    GST_WARNING_OBJECT (target_pad,
        "Exposing pad without stored stream-start event");
  }

  gst_element_add_pad (GST_ELEMENT (dec), output->ghost_pad);

  output->probe_id =
      gst_pad_add_probe (output->target_pad,
      GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, (GstPadProbeCallback) db_src_probe,
      output, NULL);

  /* FIXME: LOCK TO PROTECT PAD LIST */
  dec->output_pads = g_list_append (dec->output_pads, output);

  return output;
}

static void
db_pad_added_cb (GstElement * element, GstPad * pad, GstURIDecodeBin3 * dec)
{
  GST_DEBUG_OBJECT (dec, "Wrapping new pad %s:%s", GST_DEBUG_PAD_NAME (pad));

  if (GST_PAD_IS_SRC (pad))
    add_output_pad (dec, pad);
}

static void
db_pad_removed_cb (GstElement * element, GstPad * pad, GstURIDecodeBin3 * dec)
{
  GList *tmp;
  OutputPad *output = NULL;

  if (!GST_PAD_IS_SRC (pad))
    return;

  GST_DEBUG_OBJECT (dec, "pad %s:%s", GST_DEBUG_PAD_NAME (pad));
  /* FIXME: LOCK for list access */

  for (tmp = dec->output_pads; tmp; tmp = tmp->next) {
    OutputPad *cand = (OutputPad *) tmp->data;

    if (cand->target_pad == pad) {
      output = cand;
      dec->output_pads = g_list_delete_link (dec->output_pads, tmp);
      break;
    }
  }

  if (output) {
    GST_LOG_OBJECT (element, "Removing output %p", output);
    /* Remove source ghost pad */
    gst_ghost_pad_set_target ((GstGhostPad *) output->ghost_pad, NULL);
    gst_element_remove_pad ((GstElement *) dec, output->ghost_pad);

    /* Remove event probe */
    gst_pad_remove_probe (output->target_pad, output->probe_id);

    g_slice_free (OutputPad, output);

    check_output_group_id (dec);
  }
}

static gint
db_select_stream_cb (GstElement * decodebin,
    GstStreamCollection * collection, GstStream * stream,
    GstURIDecodeBin3 * uridecodebin)
{
  gint response = -1;

  g_signal_emit (uridecodebin,
      gst_uri_decode_bin3_signals[SIGNAL_SELECT_STREAM], 0, collection, stream,
      &response);
  return response;
}

static gboolean
check_pad_mode (GstElement * src, GstPad * pad, gpointer udata)
{
  GstPadMode curmode = GST_PAD_MODE (pad);
  GstPadMode *retmode = (GstPadMode *) udata;

  /* We don't care if pads aren't activated */
  if (curmode == GST_PAD_MODE_NONE)
    return TRUE;

  if (*retmode == GST_PAD_MODE_NONE) {
    *retmode = curmode;
  } else if (*retmode != curmode) {
    GST_ERROR_OBJECT (src, "source has different scheduling mode ?");
  }

  return TRUE;
}

static gboolean
play_item_is_pull_based (GstPlayItem * item)
{
  GstElement *src;
  GstPadMode mode = GST_PAD_MODE_NONE;

  g_assert (item->main_item && item->main_item->handler
      && item->main_item->handler->urisourcebin);

  src = item->main_item->handler->urisourcebin;
  gst_element_foreach_src_pad (src, check_pad_mode, &mode);

  return (mode == GST_PAD_MODE_PULL);
}

static void
emit_and_handle_about_to_finish (GstURIDecodeBin3 * uridecodebin,
    GstPlayItem * item)
{
  GST_DEBUG_OBJECT (uridecodebin, "output %d , posted_about_to_finish:%d",
      item->group_id, item->posted_about_to_finish);

  if (item->posted_about_to_finish) {
    GST_DEBUG_OBJECT (uridecodebin,
        "already handling about-to-finish for this play item");
    return;
  }

  if (item != uridecodebin->input_item) {
    GST_DEBUG_OBJECT (uridecodebin, "Postponing about-to-finish propagation");
    item->pending_about_to_finish = TRUE;
    return;
  }

  /* If the input entry is pull-based, mark all the source pads as EOS */
  if (play_item_is_pull_based (item)) {
    GST_DEBUG_OBJECT (uridecodebin, "Marking play item as EOS");
    play_item_set_eos (item);
  }

  item->posted_about_to_finish = TRUE;
  GST_DEBUG_OBJECT (uridecodebin, "Posting about-to-finish");
  g_signal_emit (uridecodebin,
      gst_uri_decode_bin3_signals[SIGNAL_ABOUT_TO_FINISH], 0, NULL);

  /* Note : Activation of the (potential) next entry is handled in
   * gst_uri_decode_bin3_set_uri */
}

static void
db_about_to_finish_cb (GstElement * decodebin, GstURIDecodeBin3 * uridecodebin)
{
  GST_LOG_OBJECT (uridecodebin, "about to finish from %s",
      GST_OBJECT_NAME (decodebin));

  emit_and_handle_about_to_finish (uridecodebin, uridecodebin->output_item);
}

static void
gst_uri_decode_bin3_init (GstURIDecodeBin3 * dec)
{
  GstPlayItem *item;

  dec->connection_speed = DEFAULT_CONNECTION_SPEED;
  dec->caps = DEFAULT_CAPS;
  dec->buffer_duration = DEFAULT_BUFFER_DURATION;
  dec->buffer_size = DEFAULT_BUFFER_SIZE;
  dec->download = DEFAULT_DOWNLOAD;
  dec->use_buffering = DEFAULT_USE_BUFFERING;
  dec->ring_buffer_max_size = DEFAULT_RING_BUFFER_MAX_SIZE;

  g_mutex_init (&dec->play_items_lock);
  g_cond_init (&dec->input_source_drained);

  dec->decodebin = gst_element_factory_make ("decodebin3", NULL);
  gst_bin_add (GST_BIN_CAST (dec), dec->decodebin);
  dec->db_pad_added_id =
      g_signal_connect (dec->decodebin, "pad-added",
      G_CALLBACK (db_pad_added_cb), dec);
  dec->db_pad_removed_id =
      g_signal_connect (dec->decodebin, "pad-removed",
      G_CALLBACK (db_pad_removed_cb), dec);
  dec->db_select_stream_id =
      g_signal_connect (dec->decodebin, "select-stream",
      G_CALLBACK (db_select_stream_cb), dec);
  dec->db_about_to_finish_id =
      g_signal_connect (dec->decodebin, "about-to-finish",
      G_CALLBACK (db_about_to_finish_cb), dec);

  GST_OBJECT_FLAG_SET (dec, GST_ELEMENT_FLAG_SOURCE);
  gst_bin_set_suppressed_flags (GST_BIN (dec),
      GST_ELEMENT_FLAG_SOURCE | GST_ELEMENT_FLAG_SINK);

  item = new_play_item (dec);
  dec->play_items = g_list_append (dec->play_items, item);
  /* The initial play item is automatically the input and output one */
  dec->input_item = dec->output_item = item;
}

static void
gst_uri_decode_bin3_dispose (GObject * obj)
{
  GstURIDecodeBin3 *dec = GST_URI_DECODE_BIN3 (obj);
  GList *iter;

  GST_DEBUG_OBJECT (obj, "Disposing");

  /* Free all play items */
  for (iter = dec->play_items; iter; iter = iter->next) {
    GstPlayItem *item = iter->data;
    free_play_item (dec, item);
  }
  g_list_free (dec->play_items);
  dec->play_items = NULL;

  g_mutex_clear (&dec->play_items_lock);

  G_OBJECT_CLASS (parent_class)->dispose (obj);
}

static GstStateChangeReturn
activate_source_item (GstSourceItem * item)
{
  GstSourceHandler *handler = item->handler;

  if (handler == NULL) {
    GST_WARNING ("Can't activate item without a handler");
    return GST_STATE_CHANGE_FAILURE;
  }

  g_object_set (handler->urisourcebin, "uri", item->uri, NULL);
  if (!handler->active) {
    gst_bin_add ((GstBin *) handler->uridecodebin, handler->urisourcebin);
    handler->active = TRUE;
  }

  if (!gst_element_sync_state_with_parent (handler->urisourcebin))
    return GST_STATE_CHANGE_FAILURE;

  return GST_STATE_CHANGE_SUCCESS;
}

static void
link_src_pad_to_db3 (GstURIDecodeBin3 * uridecodebin, GstSourcePad * spad)
{
  GstSourceHandler *handler = spad->handler;
  GstPad *sinkpad = NULL;

  /* Try to link to main sink pad only if it's from a main handler */
  if (handler->is_main_source) {
    sinkpad = gst_element_get_static_pad (uridecodebin->decodebin, "sink");
    if (gst_pad_is_linked (sinkpad)) {
      gst_object_unref (sinkpad);
      sinkpad = NULL;
    }
  }

  if (sinkpad == NULL) {
    sinkpad =
        gst_element_request_pad_simple (uridecodebin->decodebin, "sink_%u");
    spad->db3_pad_is_request = TRUE;
  }

  if (sinkpad) {
    GstPadLinkReturn res;
    GST_DEBUG_OBJECT (uridecodebin,
        "Linking %" GST_PTR_FORMAT " to %" GST_PTR_FORMAT, spad->src_pad,
        sinkpad);
    res = gst_pad_link (spad->src_pad, sinkpad);
    gst_object_unref (sinkpad);
    if (GST_PAD_LINK_FAILED (res)) {
      GST_ERROR_OBJECT (uridecodebin,
          "failed to link pad %s:%s to decodebin, reason %s (%d)",
          GST_DEBUG_PAD_NAME (spad->src_pad), gst_pad_link_get_name (res), res);
      return;
    }
  } else {
    GST_ERROR_OBJECT (uridecodebin, "Could not get a sinkpad from decodebin3");
    return;
  }

  spad->db3_sink_pad = sinkpad;

  /* Activate sub_item after the main source activation was finished */
  if (handler->is_main_source && handler->play_item->sub_item
      && !handler->play_item->sub_item->handler) {
    GstStateChangeReturn ret;
    handler->play_item->sub_item->handler =
        new_source_handler (uridecodebin, handler->play_item, FALSE);
    ret = activate_source_item (handler->play_item->sub_item);
    if (ret == GST_STATE_CHANGE_FAILURE) {
      free_source_handler (uridecodebin, handler->play_item->sub_item->handler);
      handler->play_item->sub_item->handler = NULL;
      goto sub_item_activation_failed;
    }
  }

  return;

sub_item_activation_failed:
  {
    GST_ERROR_OBJECT (uridecodebin,
        "failed to activate subtitle playback item");
    return;
  }
}

static GList *
get_all_play_item_source_pads (GstPlayItem * item)
{
  GList *ret = NULL;

  if (item->main_item && item->main_item->handler) {
    ret = g_list_copy (item->main_item->handler->sourcepads);
  }

  if (item->sub_item && item->sub_item->handler) {
    ret =
        g_list_concat (ret, g_list_copy (item->sub_item->handler->sourcepads));
  }

  return ret;
}

static GstSourcePad *
find_matching_source_pad (GList * candidates, GstSourcePad * target)
{
  GList *iter;
  GstStream *stream = target->stream;

  GST_DEBUG_OBJECT (target->src_pad, "Find match for stream %" GST_PTR_FORMAT,
      stream);

  for (iter = candidates; iter; iter = iter->next) {
    GstSourcePad *cand = iter->data;

    if (!cand->db3_sink_pad)
      continue;

    /* Target doesn't have a specific GstStream, return the first result */
    if (!stream)
      return cand;

    if (gst_stream_get_stream_type (cand->stream) ==
        gst_stream_get_stream_type (stream))
      return cand;
  }

  return NULL;
}

/* PLAY_ITEMS_LOCK held
 *
 * Switch the input play item to the next one
 */
static void
switch_and_activate_input_locked (GstURIDecodeBin3 * uridecodebin,
    GstPlayItem * new_item)
{
  GList *new_pads = get_all_play_item_source_pads (new_item);
  GList *old_pads = get_all_play_item_source_pads (uridecodebin->input_item);
  GList *to_activate = NULL;
  GList *iternew, *iterold;

  /* Deactivate old urisourcebins first ? Problem is they might remove the pads */

  /* Go over new item source pads and figure out a candidate replacement in  */
  /* Figure out source pad matches */
  for (iternew = new_pads; iternew; iternew = iternew->next) {
    GstSourcePad *new_spad = iternew->data;
    GstSourcePad *old_spad = find_matching_source_pad (old_pads, new_spad);

    if (old_spad) {
      GST_DEBUG_OBJECT (uridecodebin, "Relinking %s:%s from %s:%s to %s:%s",
          GST_DEBUG_PAD_NAME (old_spad->db3_sink_pad),
          GST_DEBUG_PAD_NAME (old_spad->src_pad),
          GST_DEBUG_PAD_NAME (new_spad->src_pad));
      gst_pad_unlink (old_spad->src_pad, old_spad->db3_sink_pad);
      new_spad->db3_sink_pad = old_spad->db3_sink_pad;
      new_spad->db3_pad_is_request = old_spad->db3_pad_is_request;
      old_spad->db3_sink_pad = NULL;

      gst_pad_link (new_spad->src_pad, new_spad->db3_sink_pad);
      old_pads = g_list_remove (old_pads, old_spad);
    } else {
      GST_DEBUG_OBJECT (new_spad->src_pad, "Needs a new pad");
      to_activate = g_list_append (to_activate, new_spad);
    }
  }

  /* Remove unmatched old source pads */
  for (iterold = old_pads; iterold; iterold = iterold->next) {
    GstSourcePad *old_spad = iterold->data;
    if (old_spad->db3_sink_pad && old_spad->db3_pad_is_request) {
      GST_DEBUG_OBJECT (uridecodebin, "Releasing no longer used db3 pad");
      gst_element_release_request_pad (uridecodebin->decodebin,
          old_spad->db3_sink_pad);
      old_spad->db3_sink_pad = NULL;
    }
  }

  /* Link new source pads */
  for (iternew = to_activate; iternew; iternew = iternew->next) {
    GstSourcePad *new_spad = iternew->data;
    link_src_pad_to_db3 (uridecodebin, new_spad);
  }

  /* Unblock all new item source pads */
  for (iternew = new_pads; iternew; iternew = iternew->next) {
    GstSourcePad *new_spad = iternew->data;
    if (new_spad->block_probe_id) {
      gst_pad_remove_probe (new_spad->src_pad, new_spad->block_probe_id);
      new_spad->block_probe_id = 0;
    }
  }
  g_list_free (new_pads);
  g_list_free (old_pads);

  /* Deactivate old input item (by removing the source components). The final
   * removal of this play item will be done once decodebin3 starts output the
   * content of the new play item. */
  if (uridecodebin->input_item->main_item) {
    free_source_item (uridecodebin, uridecodebin->input_item->main_item);
    uridecodebin->input_item->main_item = NULL;
  }
  if (uridecodebin->input_item->sub_item) {
    free_source_item (uridecodebin, uridecodebin->input_item->sub_item);
    uridecodebin->input_item->sub_item = NULL;
  }

  /* and set new one as input item */
  uridecodebin->input_item = new_item;

  /* If the new source is already drained, propagate about-to-finish */
  if (new_item->pending_about_to_finish) {
    emit_and_handle_about_to_finish (uridecodebin, new_item);
  }

  /* Finally propagate pending buffering message */
  if (new_item->main_item->handler->pending_buffering_msg) {
    GstMessage *msg = new_item->main_item->handler->pending_buffering_msg;
    new_item->main_item->handler->pending_buffering_msg = NULL;
    GST_DEBUG_OBJECT (uridecodebin,
        "Posting pending buffering message %" GST_PTR_FORMAT, msg);
    PLAY_ITEMS_UNLOCK (uridecodebin);
    GST_BIN_CLASS (parent_class)->handle_message ((GstBin *) uridecodebin, msg);
    PLAY_ITEMS_LOCK (uridecodebin);
  }
}

static GstPadProbeReturn
uri_src_probe (GstPad * pad, GstPadProbeInfo * info, GstSourcePad * srcpad)
{
  GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
  GstSourceHandler *handler = srcpad->handler;
  GstPadProbeReturn ret = GST_PAD_PROBE_OK;

  GST_DEBUG_OBJECT (pad, "event %" GST_PTR_FORMAT, event);

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_EOS:
    {
      GstPad *peer;
      /* Propagate the EOS *before* triggering any potential switch */
      peer = gst_pad_get_peer (pad);
      if (peer) {
        gst_pad_send_event (peer, event);
        gst_object_unref (peer);
      } else {
        /* No peer, just drop it (since we're returning HANDLED below) */
        gst_event_unref (event);
      }

      PLAY_ITEMS_LOCK (handler->uridecodebin);
      /* EOS : Mark pad as EOS */
      srcpad->saw_eos = TRUE;
      /* Check if the input play item is fully EOS. If yes and there is a
       * pending play item, switch to it */
      if (handler->play_item == handler->uridecodebin->input_item &&
          play_item_is_eos (handler->play_item)) {
        g_cond_broadcast (&handler->uridecodebin->input_source_drained);
      }
      PLAY_ITEMS_UNLOCK (handler->uridecodebin);
      ret = GST_PAD_PROBE_HANDLED;
      break;
    }
    case GST_EVENT_STREAM_START:
    {
      GstStream *stream = NULL;
      guint group_id = GST_GROUP_ID_INVALID;

      srcpad->saw_eos = FALSE;
      gst_event_parse_group_id (event, &group_id);
      /* Unify group id */
      if (handler->play_item->group_id == GST_GROUP_ID_INVALID) {
        GST_DEBUG_OBJECT (pad,
            "Setting play item to group_id %" G_GUINT32_FORMAT, group_id);
        handler->play_item->group_id = group_id;
      } else if (handler->play_item->group_id != group_id) {
        GST_DEBUG_OBJECT (pad, "Updating event group-id to %" G_GUINT32_FORMAT,
            handler->play_item->group_id);
        event = gst_event_make_writable (event);
        GST_PAD_PROBE_INFO_DATA (info) = event;
        gst_event_set_group_id (event, handler->play_item->group_id);
      }
      gst_event_parse_stream (event, &stream);
      if (stream) {
        GST_DEBUG_OBJECT (srcpad->src_pad, "Got GstStream %" GST_PTR_FORMAT,
            stream);
        if (srcpad->stream)
          gst_object_unref (srcpad->stream);
        srcpad->stream = stream;
      }
      break;
    }
    case GST_EVENT_SEGMENT:
    {
      srcpad->saw_eos = FALSE;
      break;
    }
    default:
      break;
  }

  return ret;
}

static GstPadProbeReturn
uri_src_block_probe (GstPad * pad, GstPadProbeInfo * info,
    GstSourcePad * srcpad)
{
  GstPadProbeReturn ret = GST_PAD_PROBE_OK;
  GstSourceHandler *handler = srcpad->handler;
  GST_DEBUG_OBJECT (pad, "blocked");

  /* We only block on buffers, buffer list and gap events. Everything else is
   * dropped (sticky events will be propagated later) */
  if (GST_IS_EVENT (GST_PAD_PROBE_INFO_DATA (info)) &&
      GST_EVENT_TYPE (GST_PAD_PROBE_INFO_EVENT (info)) != GST_EVENT_GAP) {
    GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
    if (GST_EVENT_TYPE (event) == GST_EVENT_STREAM_START) {
      GstStream *stream = NULL;
      GstQuery *q = gst_query_new_selectable ();
      gst_event_parse_stream (event, &stream);
      if (stream) {
        GST_DEBUG_OBJECT (srcpad->src_pad, "Got GstStream %" GST_PTR_FORMAT,
            stream);
        if (srcpad->stream)
          gst_object_unref (srcpad->stream);
        srcpad->stream = stream;
      }
      if (gst_pad_query (pad, q)) {
        PLAY_ITEMS_LOCK (handler->uridecodebin);
        gst_query_parse_selectable (q, &handler->upstream_selected);
        GST_DEBUG_OBJECT (srcpad->src_pad, "Upstream is selectable : %d",
            handler->upstream_selected);
        PLAY_ITEMS_UNLOCK (handler->uridecodebin);
      }
      gst_query_unref (q);
    } else if (GST_EVENT_TYPE (event) == GST_EVENT_STREAM_COLLECTION) {
      GstStreamCollection *collection = NULL;
      PLAY_ITEMS_LOCK (handler->uridecodebin);
      if (!handler->upstream_selected) {
        gst_event_parse_stream_collection (event, &collection);
        if (collection) {
          GST_DEBUG_OBJECT (srcpad->src_pad, "Seen collection with %d streams",
              gst_stream_collection_get_size (collection));
          if (handler->expected_pads == 1) {
            handler->expected_pads =
                gst_stream_collection_get_size (collection);
          }
          gst_object_unref (collection);
        }
      }
      PLAY_ITEMS_UNLOCK (handler->uridecodebin);
    }

    GST_LOG_OBJECT (pad, "Skiping %" GST_PTR_FORMAT, event);
    /* We don't want to be repeatedly called for the same event when unlinked,
     * so we mark the event as handled */
    gst_mini_object_unref (GST_PAD_PROBE_INFO_DATA (info));
    return GST_PAD_PROBE_HANDLED;
  }

  PLAY_ITEMS_LOCK (handler->uridecodebin);
  if (play_item_is_eos (handler->uridecodebin->input_item)) {
    GST_DEBUG_OBJECT (handler->uridecodebin,
        "We can switch over to the next input item");
    switch_and_activate_input_locked (handler->uridecodebin,
        handler->play_item);
    ret = GST_PAD_PROBE_REMOVE;
  } else if (play_item_has_all_pads (handler->play_item)) {
    /* We have all expected pads for this play item but the current input
     * play item isn't done yet, wait for it */
    GST_DEBUG_OBJECT (pad, "Waiting for input source to be drained");
    g_cond_wait (&handler->uridecodebin->input_source_drained,
        &handler->uridecodebin->play_items_lock);
    if (g_atomic_int_get (&handler->uridecodebin->shutdown))
      goto shutdown;
    if (play_item_is_eos (handler->uridecodebin->input_item)) {
      GST_DEBUG_OBJECT (handler->uridecodebin,
          "We can switch over to the next input item");
      switch_and_activate_input_locked (handler->uridecodebin,
          handler->play_item);
    }
    ret = GST_PAD_PROBE_REMOVE;
  }

  PLAY_ITEMS_UNLOCK (handler->uridecodebin);

  return ret;

  /* ERRORS */
shutdown:
  {
    GST_LOG_OBJECT (pad, "Shutting down");
    /* We are shutting down, we both want to remove this probe and propagate a
     * GST_FLOW_FLUSHING upstream (to cause tasks to stop) */
    if (srcpad->block_probe_id)
      gst_pad_remove_probe (pad, srcpad->block_probe_id);
    srcpad->block_probe_id = 0;
    PLAY_ITEMS_UNLOCK (handler->uridecodebin);
    GST_PAD_PROBE_INFO_FLOW_RETURN (info) = GST_FLOW_FLUSHING;
    gst_mini_object_unref (GST_PAD_PROBE_INFO_DATA (info));
    return GST_PAD_PROBE_HANDLED;
  }
}

static void
src_pad_added_cb (GstElement * element, GstPad * pad,
    GstSourceHandler * handler)
{
  GstSourcePad *spad = g_slice_new0 (GstSourcePad);
  GstURIDecodeBin3 *uridecodebin;

  uridecodebin = handler->uridecodebin;

  PLAY_ITEMS_LOCK (uridecodebin);

  GST_DEBUG_OBJECT (uridecodebin,
      "New pad %" GST_PTR_FORMAT " from source %" GST_PTR_FORMAT, pad, element);

  /* Register the new pad information with the source handler */
  spad->handler = handler;
  spad->src_pad = pad;
  spad->event_probe_id =
      gst_pad_add_probe (pad,
      GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, (GstPadProbeCallback) uri_src_probe,
      spad, NULL);

  handler->sourcepads = g_list_append (handler->sourcepads, spad);

  /* Can the pad be linked straight away to db3 ?
   * This can happen if:
   * * It is the initial play item
   * * It is part of the current input item
   */
  if (handler->play_item == uridecodebin->input_item) {
    GST_DEBUG_OBJECT (uridecodebin,
        "Pad is part of current input item, linking");

    link_src_pad_to_db3 (uridecodebin, spad);
    PLAY_ITEMS_UNLOCK (uridecodebin);
    return;
  }

  /* This pad is not from the current input item. We add a blocking probe to
   * wait until we block on the new urisourcebin streaming thread and can
   * switch */
  GST_DEBUG_OBJECT (uridecodebin, "Blocking input pad");
  spad->block_probe_id =
      gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM,
      (GstPadProbeCallback) uri_src_block_probe, spad, NULL);
  PLAY_ITEMS_UNLOCK (uridecodebin);
}

static GstSourcePad *
handler_get_source_pad (GstSourceHandler * handler, GstPad * srcpad)
{
  GList *iter;

  for (iter = handler->sourcepads; iter; iter = iter->next) {
    GstSourcePad *spad = iter->data;
    if (spad->src_pad == srcpad)
      return spad;
  }

  return NULL;
}

static void
src_pad_removed_cb (GstElement * element, GstPad * pad,
    GstSourceHandler * handler)
{
  GstURIDecodeBin3 *uridecodebin = handler->uridecodebin;
  GstSourcePad *spad = handler_get_source_pad (handler, pad);

  if (!spad)
    return;

  GST_DEBUG_OBJECT (uridecodebin,
      "Source %" GST_PTR_FORMAT " removed pad %" GST_PTR_FORMAT " peer %"
      GST_PTR_FORMAT, element, pad, spad->db3_sink_pad);

  if (spad->db3_sink_pad && spad->db3_pad_is_request)
    gst_element_release_request_pad (uridecodebin->decodebin,
        spad->db3_sink_pad);

  if (spad->stream)
    gst_object_unref (spad->stream);

  handler->sourcepads = g_list_remove (handler->sourcepads, spad);
  g_slice_free (GstSourcePad, spad);
}

static void
src_source_setup_cb (GstElement * element, GstElement * source,
    GstSourceHandler * handler)
{
  g_signal_emit (handler->uridecodebin,
      gst_uri_decode_bin3_signals[SIGNAL_SOURCE_SETUP], 0, source, NULL);
}

static void
src_about_to_finish_cb (GstElement * element, GstSourceHandler * handler)
{
  GST_LOG_OBJECT (handler->uridecodebin, "about to finish from %s",
      GST_OBJECT_NAME (element));

  emit_and_handle_about_to_finish (handler->uridecodebin, handler->play_item);
}

static GstSourceHandler *
new_source_handler (GstURIDecodeBin3 * uridecodebin, GstPlayItem * item,
    gboolean is_main)
{
  GstSourceHandler *handler;

  handler = g_slice_new0 (GstSourceHandler);

  handler->uridecodebin = uridecodebin;
  handler->play_item = item;
  handler->is_main_source = is_main;
  handler->urisourcebin = gst_element_factory_make ("urisourcebin", NULL);
  /* Set pending properties */
  g_object_set (handler->urisourcebin,
      "connection-speed", uridecodebin->connection_speed / 1000,
      "download", uridecodebin->download,
      "use-buffering", uridecodebin->use_buffering,
      "buffer-duration", uridecodebin->buffer_duration,
      "buffer-size", uridecodebin->buffer_size,
      "ring-buffer-max-size", uridecodebin->ring_buffer_max_size,
      "parse-streams", TRUE, NULL);

  handler->pad_added_id =
      g_signal_connect (handler->urisourcebin, "pad-added",
      (GCallback) src_pad_added_cb, handler);
  handler->pad_removed_id =
      g_signal_connect (handler->urisourcebin, "pad-removed",
      (GCallback) src_pad_removed_cb, handler);
  handler->source_setup_id =
      g_signal_connect (handler->urisourcebin, "source-setup",
      (GCallback) src_source_setup_cb, handler);
  handler->about_to_finish_id =
      g_signal_connect (handler->urisourcebin, "about-to-finish",
      (GCallback) src_about_to_finish_cb, handler);

  handler->expected_pads = 1;

  return handler;
}

static gboolean
source_handler_is_eos (GstSourceHandler * handler)
{
  GList *iter;

  for (iter = handler->sourcepads; iter; iter = iter->next) {
    GstSourcePad *spad = iter->data;

    if (!spad->saw_eos)
      return FALSE;
  }

  return TRUE;
}

static void
source_handler_set_eos (GstSourceHandler * handler)
{
  GList *iter;

  for (iter = handler->sourcepads; iter; iter = iter->next) {
    GstSourcePad *spad = iter->data;

    spad->saw_eos = TRUE;
  }
}

static void
gst_uri_decode_bin3_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  GstURIDecodeBin3 *dec = GST_URI_DECODE_BIN3 (object);

  switch (prop_id) {
    case PROP_URI:
      gst_uri_decode_bin3_set_uri (dec, g_value_get_string (value));
      break;
    case PROP_SUBURI:
      gst_uri_decode_bin3_set_suburi (dec, g_value_get_string (value));
      break;
    case PROP_CONNECTION_SPEED:
      GST_OBJECT_LOCK (dec);
      dec->connection_speed = g_value_get_uint64 (value) * 1000;
      GST_OBJECT_UNLOCK (dec);
      break;
    case PROP_BUFFER_SIZE:
      dec->buffer_size = g_value_get_int (value);
      break;
    case PROP_BUFFER_DURATION:
      dec->buffer_duration = g_value_get_int64 (value);
      break;
    case PROP_DOWNLOAD:
      dec->download = g_value_get_boolean (value);
      break;
    case PROP_USE_BUFFERING:
      dec->use_buffering = g_value_get_boolean (value);
      break;
    case PROP_RING_BUFFER_MAX_SIZE:
      dec->ring_buffer_max_size = g_value_get_uint64 (value);
      break;
    case PROP_CAPS:
      GST_OBJECT_LOCK (dec);
      if (dec->caps)
        gst_caps_unref (dec->caps);
      dec->caps = g_value_dup_boxed (value);
      GST_OBJECT_UNLOCK (dec);
      break;
    case PROP_INSTANT_URI:
      GST_OBJECT_LOCK (dec);
      dec->instant_uri = g_value_get_boolean (value);
      GST_OBJECT_UNLOCK (dec);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_uri_decode_bin3_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
  GstURIDecodeBin3 *dec = GST_URI_DECODE_BIN3 (object);

  switch (prop_id) {
    case PROP_URI:
    {
      GstPlayItem *item = dec->play_items->data;
      /* Return from the head */
      if (item->main_item)
        g_value_set_string (value, item->main_item->uri);
      else
        g_value_set_string (value, NULL);
      break;
    }
    case PROP_CURRENT_URI:
    {
      if (dec->output_item && dec->output_item->main_item) {
        g_value_set_string (value, dec->output_item->main_item->uri);
      } else {
        g_value_set_string (value, NULL);
      }
      break;
    }
    case PROP_SUBURI:
    {
      GstPlayItem *item = dec->play_items->data;
      /* Return from the head */
      if (item->sub_item)
        g_value_set_string (value, item->sub_item->uri);
      else
        g_value_set_string (value, NULL);
      break;
    }
    case PROP_CURRENT_SUBURI:
    {
      if (dec->output_item && dec->output_item->sub_item) {
        g_value_set_string (value, dec->output_item->sub_item->uri);
      } else {
        g_value_set_string (value, NULL);
      }
      break;
    }
    case PROP_SOURCE:
    {
      GST_OBJECT_LOCK (dec);
      g_value_set_object (value, dec->source);
      GST_OBJECT_UNLOCK (dec);
      break;
    }
    case PROP_CONNECTION_SPEED:
      GST_OBJECT_LOCK (dec);
      g_value_set_uint64 (value, dec->connection_speed / 1000);
      GST_OBJECT_UNLOCK (dec);
      break;
    case PROP_BUFFER_SIZE:
      GST_OBJECT_LOCK (dec);
      g_value_set_int (value, dec->buffer_size);
      GST_OBJECT_UNLOCK (dec);
      break;
    case PROP_BUFFER_DURATION:
      GST_OBJECT_LOCK (dec);
      g_value_set_int64 (value, dec->buffer_duration);
      GST_OBJECT_UNLOCK (dec);
      break;
    case PROP_DOWNLOAD:
      g_value_set_boolean (value, dec->download);
      break;
    case PROP_USE_BUFFERING:
      g_value_set_boolean (value, dec->use_buffering);
      break;
    case PROP_RING_BUFFER_MAX_SIZE:
      g_value_set_uint64 (value, dec->ring_buffer_max_size);
      break;
    case PROP_CAPS:
      GST_OBJECT_LOCK (dec);
      g_value_set_boxed (value, dec->caps);
      GST_OBJECT_UNLOCK (dec);
      break;
    case PROP_INSTANT_URI:
      GST_OBJECT_LOCK (dec);
      g_value_set_boolean (value, dec->instant_uri);
      GST_OBJECT_UNLOCK (dec);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
free_source_handler (GstURIDecodeBin3 * uridecodebin,
    GstSourceHandler * handler)
{
  GST_LOG_OBJECT (uridecodebin, "source handler %p", handler);
  if (handler->active) {
    GList *iter;
    GST_STATE_LOCK (uridecodebin);
    GST_LOG_OBJECT (uridecodebin, "Removing %" GST_PTR_FORMAT,
        handler->urisourcebin);
    for (iter = handler->sourcepads; iter; iter = iter->next) {
      GstSourcePad *spad = iter->data;
      if (spad->block_probe_id)
        gst_pad_remove_probe (spad->src_pad, spad->block_probe_id);
    }
    gst_element_set_state (handler->urisourcebin, GST_STATE_NULL);
    gst_bin_remove ((GstBin *) uridecodebin, handler->urisourcebin);
    GST_STATE_UNLOCK (uridecodebin);
    g_list_free (handler->sourcepads);
  }
  if (handler->pending_buffering_msg)
    gst_message_unref (handler->pending_buffering_msg);
  g_slice_free (GstSourceHandler, handler);
}

static GstSourceItem *
new_source_item (GstURIDecodeBin3 * dec, GstPlayItem * item, gchar * uri)
{
  GstSourceItem *sourceitem = g_slice_new0 (GstSourceItem);

  sourceitem->play_item = item;
  sourceitem->uri = uri;

  return sourceitem;
}

static void
free_source_item (GstURIDecodeBin3 * uridecodebin, GstSourceItem * item)
{
  GST_LOG_OBJECT (uridecodebin, "source item %p", item);
  if (item->handler)
    free_source_handler (uridecodebin, item->handler);
  g_free (item->uri);
  g_slice_free (GstSourceItem, item);
}

static void
source_item_set_uri (GstSourceItem * item, const gchar * uri)
{
  if (item->uri)
    g_free (item->uri);
  item->uri = g_strdup (uri);
  if (item->handler) {
    g_object_set (item->handler->urisourcebin, "uri", uri, NULL);
  }
}

static GstPlayItem *
new_play_item (GstURIDecodeBin3 * dec)
{
  GstPlayItem *item = g_slice_new0 (GstPlayItem);

  item->uridecodebin = dec;
  item->group_id = GST_GROUP_ID_INVALID;

  return item;
}

static void
free_play_item (GstURIDecodeBin3 * dec, GstPlayItem * item)
{
  GST_LOG_OBJECT (dec, "play item %p", item);
  if (item->main_item)
    free_source_item (dec, item->main_item);
  if (item->sub_item)
    free_source_item (dec, item->sub_item);

  g_slice_free (GstPlayItem, item);
}

static void
play_item_set_uri (GstPlayItem * item, const gchar * uri)
{
  if (!uri)
    return;

  if (!item->main_item) {
    item->main_item =
        new_source_item (item->uridecodebin, item, g_strdup (uri));
  } else {
    source_item_set_uri (item->main_item, uri);
  }
}

static void
play_item_set_suburi (GstPlayItem * item, const gchar * uri)
{
  if (!uri) {
    if (item->sub_item) {
      free_source_item (item->uridecodebin, item->sub_item);
      item->sub_item = NULL;
    }
    return;
  }

  if (!item->sub_item) {
    item->sub_item = new_source_item (item->uridecodebin, item, g_strdup (uri));
  } else {
    source_item_set_uri (item->sub_item, uri);
  }
}

static gboolean
play_item_is_eos (GstPlayItem * item)
{
  if (item->main_item && item->main_item->handler) {
    if (!source_handler_is_eos (item->main_item->handler))
      return FALSE;
  }
  if (item->sub_item && item->sub_item->handler) {
    if (!source_handler_is_eos (item->sub_item->handler))
      return FALSE;
  }

  return TRUE;
}

/* Mark all sourcepads of a play item as EOS. Used in pull-mode */
static void
play_item_set_eos (GstPlayItem * item)
{
  if (item->main_item && item->main_item->handler)
    source_handler_set_eos (item->main_item->handler);

  if (item->sub_item && item->sub_item->handler)
    source_handler_set_eos (item->sub_item->handler);
}

static gboolean
play_item_has_all_pads (GstPlayItem * item)
{
  GstSourceHandler *handler;

  if (item->main_item && item->main_item->handler) {
    handler = item->main_item->handler;
    if (handler->expected_pads != g_list_length (handler->sourcepads))
      return FALSE;
  }

  if (item->sub_item && item->sub_item->handler) {
    handler = item->sub_item->handler;
    if (handler->expected_pads != g_list_length (handler->sourcepads))
      return FALSE;
  }

  return TRUE;
}

/* Returns the next inactive play item. If none available, it will create one
 * and add it to the list of play items */
static GstPlayItem *
next_inactive_play_item (GstURIDecodeBin3 * dec)
{
  GstPlayItem *res;
  GList *iter;

  for (iter = dec->play_items; iter; iter = iter->next) {
    res = iter->data;
    if (!res->active)
      return res;
  }

  GST_DEBUG_OBJECT (dec, "No inactive play items, creating a new one");
  res = new_play_item (dec);
  dec->play_items = g_list_append (dec->play_items, res);

  return res;
}

static GstPadProbeReturn
uri_src_ignore_block_probe (GstPad * pad, GstPadProbeInfo * info,
    GstSourcePad * srcpad)
{
  GST_DEBUG_OBJECT (pad, "blocked");
  return GST_PAD_PROBE_OK;
}

static void
gst_uri_decode_bin3_set_uri (GstURIDecodeBin3 * dec, const gchar * uri)
{
  GstPlayItem *item;
  gboolean start_item = FALSE;

  GST_DEBUG_OBJECT (dec, "uri: %s", uri);

  item = next_inactive_play_item (dec);
  play_item_set_uri (item, uri);

  if (dec->instant_uri && item != dec->input_item) {
    GList *old_pads = get_all_play_item_source_pads (dec->input_item);
    GList *iter;

    /* Switch immediately if not the current input item */
    GST_DEBUG_OBJECT (dec, "Switching immediately");

    /* FLUSH START all input pads */
    for (iter = old_pads; iter; iter = iter->next) {
      GstSourcePad *spad = iter->data;
      if (spad->db3_sink_pad) {
        /* Mark all input pads as EOS */
        gst_pad_send_event (spad->db3_sink_pad, gst_event_new_flush_start ());
      }
      /* Block all input source pads */
      spad->block_probe_id =
          gst_pad_add_probe (spad->src_pad, GST_PAD_PROBE_TYPE_IDLE,
          (GstPadProbeCallback) uri_src_ignore_block_probe, spad, NULL);
      spad->saw_eos = TRUE;
    }
    for (iter = old_pads; iter; iter = iter->next) {
      /* FLUSH_STOP all current input pads */
      GstSourcePad *spad = iter->data;
      if (spad->db3_sink_pad) {
        gst_pad_send_event (spad->db3_sink_pad,
            gst_event_new_flush_stop (TRUE));
      }
    }
    start_item = TRUE;
  } else if (dec->input_item->posted_about_to_finish) {
    GList *iter = g_list_find (dec->play_items, dec->input_item);
    /* If the current item is finishing and the new item is the one just after,
     *  we need to activate it */
    if (iter && iter->next && iter->next->data == item) {
      GST_DEBUG_OBJECT (dec, "Starting new entry (gapless mode)");
      start_item = TRUE;
    }
  }

  if (start_item) {
    /* Start new item */
    activate_play_item (item);
  }
}

static void
gst_uri_decode_bin3_set_suburi (GstURIDecodeBin3 * dec, const gchar * uri)
{
  GstPlayItem *item;
  GST_DEBUG_OBJECT (dec, "suburi: %s", uri);

  /* FIXME : Handle instant-uri-change. Should we just apply it automatically to
   * the current input item ? */

  item = next_inactive_play_item (dec);
  play_item_set_suburi (item, uri);
}

/* Sync source handlers for the given play item. Might require creating/removing some
 * and/or configure the handlers accordingly */
static GstStateChangeReturn
assign_handlers_to_item (GstURIDecodeBin3 * dec, GstPlayItem * item)
{
  GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;

  if (item->main_item == NULL)
    return GST_STATE_CHANGE_FAILURE;

  /* Create missing handlers */
  if (item->main_item->handler == NULL) {
    item->main_item->handler = new_source_handler (dec, item, TRUE);
    ret = activate_source_item (item->main_item);
    if (ret == GST_STATE_CHANGE_FAILURE) {
      free_source_handler (dec, item->main_item->handler);
      item->main_item->handler = NULL;
    }
  }

  return ret;
}

/* Called to activate the next play item */
static GstStateChangeReturn
activate_play_item (GstPlayItem * item)
{
  GstStateChangeReturn ret;

  GST_DEBUG_OBJECT (item->uridecodebin, "Activating play item");

  ret = assign_handlers_to_item (item->uridecodebin, item);
  if (ret != GST_STATE_CHANGE_FAILURE) {
    item->active = TRUE;
  }

  return ret;
}

/* Remove all but the last play item */
static void
purge_play_items (GstURIDecodeBin3 * dec)
{
  GST_DEBUG_OBJECT (dec, "Purging play items");

  PLAY_ITEMS_LOCK (dec);
  g_cond_broadcast (&dec->input_source_drained);
  while (dec->play_items && dec->play_items->next) {
    GstPlayItem *item = dec->play_items->data;
    dec->play_items = g_list_remove (dec->play_items, item);
    free_play_item (dec, item);
  }

  dec->output_item = dec->input_item = dec->play_items->data;
  dec->output_item->posted_about_to_finish = FALSE;
  PLAY_ITEMS_UNLOCK (dec);
}

static GstStateChangeReturn
gst_uri_decode_bin3_change_state (GstElement * element,
    GstStateChange transition)
{
  GstStateChangeReturn ret;
  GstURIDecodeBin3 *uridecodebin = (GstURIDecodeBin3 *) element;

  switch (transition) {
    case GST_STATE_CHANGE_NULL_TO_READY:
      g_object_set (uridecodebin->decodebin, "caps", uridecodebin->caps, NULL);
      break;
    case GST_STATE_CHANGE_READY_TO_PAUSED:
      g_atomic_int_set (&uridecodebin->shutdown, 0);
      ret = activate_play_item (uridecodebin->input_item);
      if (ret == GST_STATE_CHANGE_FAILURE)
        goto failure;
      break;
    case GST_STATE_CHANGE_PAUSED_TO_READY:
      PLAY_ITEMS_LOCK (uridecodebin);
      g_atomic_int_set (&uridecodebin->shutdown, 1);
      g_cond_broadcast (&uridecodebin->input_source_drained);
      PLAY_ITEMS_UNLOCK (uridecodebin);
      break;
    default:
      break;
  }

  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
  if (ret == GST_STATE_CHANGE_FAILURE)
    goto failure;

  switch (transition) {
    case GST_STATE_CHANGE_PAUSED_TO_READY:
      /* Remove all play items *but* the last one, which becomes the current entry */
      purge_play_items (uridecodebin);
      uridecodebin->input_item->active = FALSE;
      break;
    default:
      break;
  }

  return ret;

  /* ERRORS */
failure:
  {
    if (transition == GST_STATE_CHANGE_READY_TO_PAUSED)
      purge_play_items (uridecodebin);
    return ret;
  }
}

static GstSourceHandler *
find_source_handler_for_element (GstURIDecodeBin3 * uridecodebin,
    GstObject * element)
{
  GList *iter;

  for (iter = uridecodebin->play_items; iter; iter = iter->next) {
    GstPlayItem *item = iter->data;

    if (item->main_item && item->main_item->handler) {
      GstSourceHandler *handler = item->main_item->handler;

      if (gst_object_has_as_ancestor (element,
              (GstObject *) handler->urisourcebin))
        return handler;
    }
    if (item->sub_item && item->sub_item->handler) {
      GstSourceHandler *handler = item->sub_item->handler;

      if (gst_object_has_as_ancestor (element,
              (GstObject *) handler->urisourcebin))
        return handler;
    }
  }

  return NULL;
}

static void
gst_uri_decode_bin3_handle_message (GstBin * bin, GstMessage * msg)
{
  GstURIDecodeBin3 *uridecodebin = (GstURIDecodeBin3 *) bin;

  switch (GST_MESSAGE_TYPE (msg)) {
    case GST_MESSAGE_STREAMS_SELECTED:
    {
      GstSourceHandler *handler;
      GST_DEBUG_OBJECT (uridecodebin, "Handle streams selected");
      PLAY_ITEMS_LOCK (uridecodebin);
      /* Find the matching handler (if any) */
      if ((handler = find_source_handler_for_element (uridecodebin, msg->src))) {
        handler->expected_pads = gst_message_streams_selected_get_size (msg);
        GST_DEBUG_OBJECT (uridecodebin,
            "Got streams-selected for %s with %d streams selected",
            GST_ELEMENT_NAME (handler->urisourcebin), handler->expected_pads);
      }
      PLAY_ITEMS_UNLOCK (uridecodebin);
      break;
    }
    case GST_MESSAGE_BUFFERING:
    {
      GstSourceHandler *handler;
      GST_DEBUG_OBJECT (uridecodebin, "Handle buffering message");
      PLAY_ITEMS_LOCK (uridecodebin);
      /* Find the matching handler (if any) */
      handler = find_source_handler_for_element (uridecodebin, msg->src);
      if (!handler) {
        GST_LOG_OBJECT (uridecodebin, "No handler for message, dropping it");
        gst_message_unref (msg);
        msg = NULL;
      } else if (!uridecodebin->input_item->main_item
          || handler != uridecodebin->input_item->main_item->handler) {
        GST_LOG_OBJECT (uridecodebin,
            "Handler isn't active input item, storing message");
        /* Store the message for a later time */
        if (handler->pending_buffering_msg)
          gst_message_unref (handler->pending_buffering_msg);
        handler->pending_buffering_msg = msg;
        msg = NULL;
      } else {
        /* This is the active main input item, we can forward directly */
        GST_DEBUG_OBJECT (uridecodebin,
            "Forwarding message for active input item");
      }
      PLAY_ITEMS_UNLOCK (uridecodebin);
      break;

    }
    default:
      break;
  }

  if (msg)
    GST_BIN_CLASS (parent_class)->handle_message (bin, msg);
}

static gboolean
gst_uri_decodebin3_send_event (GstElement * element, GstEvent * event)
{
  GstURIDecodeBin3 *self = GST_URI_DECODE_BIN3 (element);

  if (GST_EVENT_IS_UPSTREAM (event) && self->decodebin)
    return gst_element_send_event (self->decodebin, event);

  return GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
}