summaryrefslogtreecommitdiff
path: root/gst/rtsp-server/rtsp-stream.c
blob: 39628d2aea7a4ac0da695c8e724fc2e63fcbc150 (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
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
/* GStreamer
 * Copyright (C) 2008 Wim Taymans <wim.taymans at gmail.com>
 * Copyright (C) 2015 Centricular Ltd
 *     Author: 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 St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */
/**
 * SECTION:rtsp-stream
 * @short_description: A media stream
 * @see_also: #GstRTSPMedia
 *
 * The #GstRTSPStream object manages the data transport for one stream. It
 * is created from a payloader element and a source pad that produce the RTP
 * packets for the stream.
 *
 * With gst_rtsp_stream_join_bin() the streaming elements are added to the bin
 * and rtpbin. gst_rtsp_stream_leave_bin() removes the elements again.
 *
 * The #GstRTSPStream will use the configured addresspool, as set with
 * gst_rtsp_stream_set_address_pool(), to allocate multicast addresses for the
 * stream. With gst_rtsp_stream_get_multicast_address() you can get the
 * configured address.
 *
 * With gst_rtsp_stream_get_server_port () you can get the port that the server
 * will use to receive RTCP. This is the part that the clients will use to send
 * RTCP to.
 *
 * With gst_rtsp_stream_add_transport() destinations can be added where the
 * stream should be sent to. Use gst_rtsp_stream_remove_transport() to remove
 * the destination again.
 *
 * Last reviewed on 2013-07-16 (1.0.0)
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <gio/gio.h>

#include <gst/app/gstappsrc.h>
#include <gst/app/gstappsink.h>

#include <gst/rtp/gstrtpbuffer.h>

#include "rtsp-stream.h"

#define GST_RTSP_STREAM_GET_PRIVATE(obj)  \
     (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_RTSP_STREAM, GstRTSPStreamPrivate))

struct _GstRTSPStreamPrivate
{
  GMutex lock;
  guint idx;
  /* Only one pad is ever set */
  GstPad *srcpad, *sinkpad;
  GstElement *payloader;
  guint buffer_size;
  GstBin *joined_bin;

  /* TRUE if this stream is running on
   * the client side of an RTSP link (for RECORD) */
  gboolean client_side;
  gchar *control;

  /* TRUE if stream is complete. This means that the receiver and the sender
   * parts are present in the stream. */
  gboolean is_complete;
  GstRTSPProfile profiles;
  GstRTSPLowerTrans protocols;

  /* pads on the rtpbin */
  GstPad *send_rtp_sink;
  GstPad *recv_rtp_src;
  GstPad *recv_sink[2];
  GstPad *send_src[2];

  /* the RTPSession object */
  GObject *session;

  /* SRTP encoder/decoder */
  GstElement *srtpenc;
  GstElement *srtpdec;
  GHashTable *keys;

  /* for UDP unicast */
  GstElement *udpsrc_v4[2];
  GstElement *udpsrc_v6[2];
  GstElement *udpqueue[2];
  GstElement *udpsink[2];
  GSocket *socket_v4[2];
  GSocket *socket_v6[2];

  /* for UDP multicast */
  GstElement *mcast_udpsrc_v4[2];
  GstElement *mcast_udpsrc_v6[2];
  GstElement *mcast_udpqueue[2];
  GstElement *mcast_udpsink[2];
  GSocket *mcast_socket_v4[2];
  GSocket *mcast_socket_v6[2];

  /* for TCP transport */
  GstElement *appsrc[2];
  GstClockTime appsrc_base_time[2];
  GstElement *appqueue[2];
  GstElement *appsink[2];

  GstElement *tee[2];
  GstElement *funnel[2];

  /* retransmission */
  GstElement *rtxsend;
  guint rtx_pt;
  GstClockTime rtx_time;

  /* pool used to manage unicast and multicast addresses */
  GstRTSPAddressPool *pool;

  /* unicast server addr/port */
  GstRTSPAddress *server_addr_v4;
  GstRTSPAddress *server_addr_v6;

  /* multicast addresses */
  GstRTSPAddress *mcast_addr_v4;
  GstRTSPAddress *mcast_addr_v6;

  gchar *multicast_iface;

  /* the caps of the stream */
  gulong caps_sig;
  GstCaps *caps;

  /* transports we stream to */
  guint n_active;
  GList *transports;
  guint transports_cookie;
  GList *tr_cache_rtp;
  GList *tr_cache_rtcp;
  guint tr_cache_cookie_rtp;
  guint tr_cache_cookie_rtcp;

  gint dscp_qos;

  /* stream blocking */
  gulong blocked_id[2];
  gboolean blocking;

  /* current stream postion */
  GstClockTime position;

  /* pt->caps map for RECORD streams */
  GHashTable *ptmap;

  GstRTSPPublishClockMode publish_clock_mode;
};

#define DEFAULT_CONTROL         NULL
#define DEFAULT_PROFILES        GST_RTSP_PROFILE_AVP
#define DEFAULT_PROTOCOLS       GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST | \
                                        GST_RTSP_LOWER_TRANS_TCP

enum
{
  PROP_0,
  PROP_CONTROL,
  PROP_PROFILES,
  PROP_PROTOCOLS,
  PROP_LAST
};

enum
{
  SIGNAL_NEW_RTP_ENCODER,
  SIGNAL_NEW_RTCP_ENCODER,
  SIGNAL_LAST
};

GST_DEBUG_CATEGORY_STATIC (rtsp_stream_debug);
#define GST_CAT_DEFAULT rtsp_stream_debug

static GQuark ssrc_stream_map_key;

static void gst_rtsp_stream_get_property (GObject * object, guint propid,
    GValue * value, GParamSpec * pspec);
static void gst_rtsp_stream_set_property (GObject * object, guint propid,
    const GValue * value, GParamSpec * pspec);

static void gst_rtsp_stream_finalize (GObject * obj);

static guint gst_rtsp_stream_signals[SIGNAL_LAST] = { 0 };

G_DEFINE_TYPE (GstRTSPStream, gst_rtsp_stream, G_TYPE_OBJECT);

static void
gst_rtsp_stream_class_init (GstRTSPStreamClass * klass)
{
  GObjectClass *gobject_class;

  g_type_class_add_private (klass, sizeof (GstRTSPStreamPrivate));

  gobject_class = G_OBJECT_CLASS (klass);

  gobject_class->get_property = gst_rtsp_stream_get_property;
  gobject_class->set_property = gst_rtsp_stream_set_property;
  gobject_class->finalize = gst_rtsp_stream_finalize;

  g_object_class_install_property (gobject_class, PROP_CONTROL,
      g_param_spec_string ("control", "Control",
          "The control string for this stream", DEFAULT_CONTROL,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  g_object_class_install_property (gobject_class, PROP_PROFILES,
      g_param_spec_flags ("profiles", "Profiles",
          "Allowed transfer profiles", GST_TYPE_RTSP_PROFILE,
          DEFAULT_PROFILES, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  g_object_class_install_property (gobject_class, PROP_PROTOCOLS,
      g_param_spec_flags ("protocols", "Protocols",
          "Allowed lower transport protocols", GST_TYPE_RTSP_LOWER_TRANS,
          DEFAULT_PROTOCOLS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  gst_rtsp_stream_signals[SIGNAL_NEW_RTP_ENCODER] =
      g_signal_new ("new-rtp-encoder", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST, 0, NULL, NULL, g_cclosure_marshal_generic,
      G_TYPE_NONE, 1, GST_TYPE_ELEMENT);

  gst_rtsp_stream_signals[SIGNAL_NEW_RTCP_ENCODER] =
      g_signal_new ("new-rtcp-encoder", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST, 0, NULL, NULL, g_cclosure_marshal_generic,
      G_TYPE_NONE, 1, GST_TYPE_ELEMENT);

  GST_DEBUG_CATEGORY_INIT (rtsp_stream_debug, "rtspstream", 0, "GstRTSPStream");

  ssrc_stream_map_key = g_quark_from_static_string ("GstRTSPServer.stream");
}

static void
gst_rtsp_stream_init (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv = GST_RTSP_STREAM_GET_PRIVATE (stream);

  GST_DEBUG ("new stream %p", stream);

  stream->priv = priv;

  priv->dscp_qos = -1;
  priv->control = g_strdup (DEFAULT_CONTROL);
  priv->profiles = DEFAULT_PROFILES;
  priv->protocols = DEFAULT_PROTOCOLS;
  priv->publish_clock_mode = GST_RTSP_PUBLISH_CLOCK_MODE_CLOCK;

  g_mutex_init (&priv->lock);

  priv->keys = g_hash_table_new_full (g_direct_hash, g_direct_equal,
      NULL, (GDestroyNotify) gst_caps_unref);
  priv->ptmap = g_hash_table_new_full (NULL, NULL, NULL,
      (GDestroyNotify) gst_caps_unref);
}

static void
gst_rtsp_stream_finalize (GObject * obj)
{
  GstRTSPStream *stream;
  GstRTSPStreamPrivate *priv;
  guint i;

  stream = GST_RTSP_STREAM (obj);
  priv = stream->priv;

  GST_DEBUG ("finalize stream %p", stream);

  /* we really need to be unjoined now */
  g_return_if_fail (priv->joined_bin == NULL);

  if (priv->mcast_addr_v4)
    gst_rtsp_address_free (priv->mcast_addr_v4);
  if (priv->mcast_addr_v6)
    gst_rtsp_address_free (priv->mcast_addr_v6);
  if (priv->server_addr_v4)
    gst_rtsp_address_free (priv->server_addr_v4);
  if (priv->server_addr_v6)
    gst_rtsp_address_free (priv->server_addr_v6);
  if (priv->pool)
    g_object_unref (priv->pool);
  if (priv->rtxsend)
    g_object_unref (priv->rtxsend);

  for (i = 0; i < 2; i++) {
    if (priv->socket_v4[i])
      g_object_unref (priv->socket_v4[i]);
    if (priv->socket_v6[i])
      g_object_unref (priv->socket_v6[i]);
    if (priv->mcast_socket_v4[i])
      g_object_unref (priv->mcast_socket_v4[i]);
    if (priv->mcast_socket_v6[i])
      g_object_unref (priv->mcast_socket_v6[i]);
  }

  g_free (priv->multicast_iface);

  gst_object_unref (priv->payloader);
  if (priv->srcpad)
    gst_object_unref (priv->srcpad);
  if (priv->sinkpad)
    gst_object_unref (priv->sinkpad);
  g_free (priv->control);
  g_mutex_clear (&priv->lock);

  g_hash_table_unref (priv->keys);
  g_hash_table_destroy (priv->ptmap);

  G_OBJECT_CLASS (gst_rtsp_stream_parent_class)->finalize (obj);
}

static void
gst_rtsp_stream_get_property (GObject * object, guint propid,
    GValue * value, GParamSpec * pspec)
{
  GstRTSPStream *stream = GST_RTSP_STREAM (object);

  switch (propid) {
    case PROP_CONTROL:
      g_value_take_string (value, gst_rtsp_stream_get_control (stream));
      break;
    case PROP_PROFILES:
      g_value_set_flags (value, gst_rtsp_stream_get_profiles (stream));
      break;
    case PROP_PROTOCOLS:
      g_value_set_flags (value, gst_rtsp_stream_get_protocols (stream));
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
  }
}

static void
gst_rtsp_stream_set_property (GObject * object, guint propid,
    const GValue * value, GParamSpec * pspec)
{
  GstRTSPStream *stream = GST_RTSP_STREAM (object);

  switch (propid) {
    case PROP_CONTROL:
      gst_rtsp_stream_set_control (stream, g_value_get_string (value));
      break;
    case PROP_PROFILES:
      gst_rtsp_stream_set_profiles (stream, g_value_get_flags (value));
      break;
    case PROP_PROTOCOLS:
      gst_rtsp_stream_set_protocols (stream, g_value_get_flags (value));
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, propid, pspec);
  }
}

/**
 * gst_rtsp_stream_new:
 * @idx: an index
 * @pad: a #GstPad
 * @payloader: a #GstElement
 *
 * Create a new media stream with index @idx that handles RTP data on
 * @pad and has a payloader element @payloader if @pad is a source pad
 * or a depayloader element @payloader if @pad is a sink pad.
 *
 * Returns: (transfer full): a new #GstRTSPStream
 */
GstRTSPStream *
gst_rtsp_stream_new (guint idx, GstElement * payloader, GstPad * pad)
{
  GstRTSPStreamPrivate *priv;
  GstRTSPStream *stream;

  g_return_val_if_fail (GST_IS_ELEMENT (payloader), NULL);
  g_return_val_if_fail (GST_IS_PAD (pad), NULL);

  stream = g_object_new (GST_TYPE_RTSP_STREAM, NULL);
  priv = stream->priv;
  priv->idx = idx;
  priv->payloader = gst_object_ref (payloader);
  if (GST_PAD_IS_SRC (pad))
    priv->srcpad = gst_object_ref (pad);
  else
    priv->sinkpad = gst_object_ref (pad);

  return stream;
}

/**
 * gst_rtsp_stream_get_index:
 * @stream: a #GstRTSPStream
 *
 * Get the stream index.
 *
 * Return: the stream index.
 */
guint
gst_rtsp_stream_get_index (GstRTSPStream * stream)
{
  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), -1);

  return stream->priv->idx;
}

/**
 * gst_rtsp_stream_get_pt:
 * @stream: a #GstRTSPStream
 *
 * Get the stream payload type.
 *
 * Return: the stream payload type.
 */
guint
gst_rtsp_stream_get_pt (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  guint pt;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), -1);

  priv = stream->priv;

  g_object_get (G_OBJECT (priv->payloader), "pt", &pt, NULL);

  return pt;
}

/**
 * gst_rtsp_stream_get_srcpad:
 * @stream: a #GstRTSPStream
 *
 * Get the srcpad associated with @stream.
 *
 * Returns: (transfer full): the srcpad. Unref after usage.
 */
GstPad *
gst_rtsp_stream_get_srcpad (GstRTSPStream * stream)
{
  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);

  if (!stream->priv->srcpad)
    return NULL;

  return gst_object_ref (stream->priv->srcpad);
}

/**
 * gst_rtsp_stream_get_sinkpad:
 * @stream: a #GstRTSPStream
 *
 * Get the sinkpad associated with @stream.
 *
 * Returns: (transfer full): the sinkpad. Unref after usage.
 */
GstPad *
gst_rtsp_stream_get_sinkpad (GstRTSPStream * stream)
{
  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);

  if (!stream->priv->sinkpad)
    return NULL;

  return gst_object_ref (stream->priv->sinkpad);
}

/**
 * gst_rtsp_stream_get_control:
 * @stream: a #GstRTSPStream
 *
 * Get the control string to identify this stream.
 *
 * Returns: (transfer full): the control string. g_free() after usage.
 */
gchar *
gst_rtsp_stream_get_control (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  gchar *result;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  if ((result = g_strdup (priv->control)) == NULL)
    result = g_strdup_printf ("stream=%u", priv->idx);
  g_mutex_unlock (&priv->lock);

  return result;
}

/**
 * gst_rtsp_stream_set_control:
 * @stream: a #GstRTSPStream
 * @control: a control string
 *
 * Set the control string in @stream.
 */
void
gst_rtsp_stream_set_control (GstRTSPStream * stream, const gchar * control)
{
  GstRTSPStreamPrivate *priv;

  g_return_if_fail (GST_IS_RTSP_STREAM (stream));

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  g_free (priv->control);
  priv->control = g_strdup (control);
  g_mutex_unlock (&priv->lock);
}

/**
 * gst_rtsp_stream_has_control:
 * @stream: a #GstRTSPStream
 * @control: a control string
 *
 * Check if @stream has the control string @control.
 *
 * Returns: %TRUE is @stream has @control as the control string
 */
gboolean
gst_rtsp_stream_has_control (GstRTSPStream * stream, const gchar * control)
{
  GstRTSPStreamPrivate *priv;
  gboolean res;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  if (priv->control)
    res = (g_strcmp0 (priv->control, control) == 0);
  else {
    guint streamid;

    if (sscanf (control, "stream=%u", &streamid) > 0)
      res = (streamid == priv->idx);
    else
      res = FALSE;
  }
  g_mutex_unlock (&priv->lock);

  return res;
}

/**
 * gst_rtsp_stream_set_mtu:
 * @stream: a #GstRTSPStream
 * @mtu: a new MTU
 *
 * Configure the mtu in the payloader of @stream to @mtu.
 */
void
gst_rtsp_stream_set_mtu (GstRTSPStream * stream, guint mtu)
{
  GstRTSPStreamPrivate *priv;

  g_return_if_fail (GST_IS_RTSP_STREAM (stream));

  priv = stream->priv;

  GST_LOG_OBJECT (stream, "set MTU %u", mtu);

  g_object_set (G_OBJECT (priv->payloader), "mtu", mtu, NULL);
}

/**
 * gst_rtsp_stream_get_mtu:
 * @stream: a #GstRTSPStream
 *
 * Get the configured MTU in the payloader of @stream.
 *
 * Returns: the MTU of the payloader.
 */
guint
gst_rtsp_stream_get_mtu (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  guint mtu;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), 0);

  priv = stream->priv;

  g_object_get (G_OBJECT (priv->payloader), "mtu", &mtu, NULL);

  return mtu;
}

/* Update the dscp qos property on the udp sinks */
static void
update_dscp_qos (GstRTSPStream * stream, GstElement ** udpsink)
{
  GstRTSPStreamPrivate *priv;

  priv = stream->priv;

  if (*udpsink) {
    g_object_set (G_OBJECT (*udpsink), "qos-dscp", priv->dscp_qos, NULL);
  }
}

/**
 * gst_rtsp_stream_set_dscp_qos:
 * @stream: a #GstRTSPStream
 * @dscp_qos: a new dscp qos value (0-63, or -1 to disable)
 *
 * Configure the dscp qos of the outgoing sockets to @dscp_qos.
 */
void
gst_rtsp_stream_set_dscp_qos (GstRTSPStream * stream, gint dscp_qos)
{
  GstRTSPStreamPrivate *priv;

  g_return_if_fail (GST_IS_RTSP_STREAM (stream));

  priv = stream->priv;

  GST_LOG_OBJECT (stream, "set DSCP QoS %d", dscp_qos);

  if (dscp_qos < -1 || dscp_qos > 63) {
    GST_WARNING_OBJECT (stream, "trying to set illegal dscp qos %d", dscp_qos);
    return;
  }

  priv->dscp_qos = dscp_qos;

  update_dscp_qos (stream, priv->udpsink);
}

/**
 * gst_rtsp_stream_get_dscp_qos:
 * @stream: a #GstRTSPStream
 *
 * Get the configured DSCP QoS in of the outgoing sockets.
 *
 * Returns: the DSCP QoS value of the outgoing sockets, or -1 if disbled.
 */
gint
gst_rtsp_stream_get_dscp_qos (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), -1);

  priv = stream->priv;

  return priv->dscp_qos;
}

/**
 * gst_rtsp_stream_is_transport_supported:
 * @stream: a #GstRTSPStream
 * @transport: (transfer none): a #GstRTSPTransport
 *
 * Check if @transport can be handled by stream
 *
 * Returns: %TRUE if @transport can be handled by @stream.
 */
gboolean
gst_rtsp_stream_is_transport_supported (GstRTSPStream * stream,
    GstRTSPTransport * transport)
{
  GstRTSPStreamPrivate *priv;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  if (transport->trans != GST_RTSP_TRANS_RTP)
    goto unsupported_transmode;

  if (!(transport->profile & priv->profiles))
    goto unsupported_profile;

  if (!(transport->lower_transport & priv->protocols))
    goto unsupported_ltrans;

  g_mutex_unlock (&priv->lock);

  return TRUE;

  /* ERRORS */
unsupported_transmode:
  {
    GST_DEBUG ("unsupported transport mode %d", transport->trans);
    g_mutex_unlock (&priv->lock);
    return FALSE;
  }
unsupported_profile:
  {
    GST_DEBUG ("unsupported profile %d", transport->profile);
    g_mutex_unlock (&priv->lock);
    return FALSE;
  }
unsupported_ltrans:
  {
    GST_DEBUG ("unsupported lower transport %d", transport->lower_transport);
    g_mutex_unlock (&priv->lock);
    return FALSE;
  }
}

/**
 * gst_rtsp_stream_set_profiles:
 * @stream: a #GstRTSPStream
 * @profiles: the new profiles
 *
 * Configure the allowed profiles for @stream.
 */
void
gst_rtsp_stream_set_profiles (GstRTSPStream * stream, GstRTSPProfile profiles)
{
  GstRTSPStreamPrivate *priv;

  g_return_if_fail (GST_IS_RTSP_STREAM (stream));

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  priv->profiles = profiles;
  g_mutex_unlock (&priv->lock);
}

/**
 * gst_rtsp_stream_get_profiles:
 * @stream: a #GstRTSPStream
 *
 * Get the allowed profiles of @stream.
 *
 * Returns: a #GstRTSPProfile
 */
GstRTSPProfile
gst_rtsp_stream_get_profiles (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  GstRTSPProfile res;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), GST_RTSP_PROFILE_UNKNOWN);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  res = priv->profiles;
  g_mutex_unlock (&priv->lock);

  return res;
}

/**
 * gst_rtsp_stream_set_protocols:
 * @stream: a #GstRTSPStream
 * @protocols: the new flags
 *
 * Configure the allowed lower transport for @stream.
 */
void
gst_rtsp_stream_set_protocols (GstRTSPStream * stream,
    GstRTSPLowerTrans protocols)
{
  GstRTSPStreamPrivate *priv;

  g_return_if_fail (GST_IS_RTSP_STREAM (stream));

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  priv->protocols = protocols;
  g_mutex_unlock (&priv->lock);
}

/**
 * gst_rtsp_stream_get_protocols:
 * @stream: a #GstRTSPStream
 *
 * Get the allowed protocols of @stream.
 *
 * Returns: a #GstRTSPLowerTrans
 */
GstRTSPLowerTrans
gst_rtsp_stream_get_protocols (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  GstRTSPLowerTrans res;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream),
      GST_RTSP_LOWER_TRANS_UNKNOWN);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  res = priv->protocols;
  g_mutex_unlock (&priv->lock);

  return res;
}

/**
 * gst_rtsp_stream_set_address_pool:
 * @stream: a #GstRTSPStream
 * @pool: (transfer none): a #GstRTSPAddressPool
 *
 * configure @pool to be used as the address pool of @stream.
 */
void
gst_rtsp_stream_set_address_pool (GstRTSPStream * stream,
    GstRTSPAddressPool * pool)
{
  GstRTSPStreamPrivate *priv;
  GstRTSPAddressPool *old;

  g_return_if_fail (GST_IS_RTSP_STREAM (stream));

  priv = stream->priv;

  GST_LOG_OBJECT (stream, "set address pool %p", pool);

  g_mutex_lock (&priv->lock);
  if ((old = priv->pool) != pool)
    priv->pool = pool ? g_object_ref (pool) : NULL;
  else
    old = NULL;
  g_mutex_unlock (&priv->lock);

  if (old)
    g_object_unref (old);
}

/**
 * gst_rtsp_stream_get_address_pool:
 * @stream: a #GstRTSPStream
 *
 * Get the #GstRTSPAddressPool used as the address pool of @stream.
 *
 * Returns: (transfer full): the #GstRTSPAddressPool of @stream. g_object_unref() after
 * usage.
 */
GstRTSPAddressPool *
gst_rtsp_stream_get_address_pool (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  GstRTSPAddressPool *result;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  if ((result = priv->pool))
    g_object_ref (result);
  g_mutex_unlock (&priv->lock);

  return result;
}

/**
 * gst_rtsp_stream_set_multicast_iface:
 * @stream: a #GstRTSPStream
 * @multicast_iface: (transfer none): a multicast interface name
 *
 * configure @multicast_iface to be used for @stream.
 */
void
gst_rtsp_stream_set_multicast_iface (GstRTSPStream * stream,
    const gchar * multicast_iface)
{
  GstRTSPStreamPrivate *priv;
  gchar *old;

  g_return_if_fail (GST_IS_RTSP_STREAM (stream));

  priv = stream->priv;

  GST_LOG_OBJECT (stream, "set multicast iface %s",
      GST_STR_NULL (multicast_iface));

  g_mutex_lock (&priv->lock);
  if ((old = priv->multicast_iface) != multicast_iface)
    priv->multicast_iface = multicast_iface ? g_strdup (multicast_iface) : NULL;
  else
    old = NULL;
  g_mutex_unlock (&priv->lock);

  if (old)
    g_free (old);
}

/**
 * gst_rtsp_stream_get_multicast_iface:
 * @stream: a #GstRTSPStream
 *
 * Get the multicast interface used for @stream.
 *
 * Returns: (transfer full): the multicast interface for @stream. g_free() after
 * usage.
 */
gchar *
gst_rtsp_stream_get_multicast_iface (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  gchar *result;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  if ((result = priv->multicast_iface))
    result = g_strdup (result);
  g_mutex_unlock (&priv->lock);

  return result;
}

/**
 * gst_rtsp_stream_get_multicast_address:
 * @stream: a #GstRTSPStream
 * @family: the #GSocketFamily
 *
 * Get the multicast address of @stream for @family. The original
 * #GstRTSPAddress is cached and copy is returned, so freeing the return value
 * won't release the address from the pool.
 *
 * Returns: (transfer full) (nullable): the #GstRTSPAddress of @stream
 * or %NULL when no address could be allocated. gst_rtsp_address_free()
 * after usage.
 */
GstRTSPAddress *
gst_rtsp_stream_get_multicast_address (GstRTSPStream * stream,
    GSocketFamily family)
{
  GstRTSPStreamPrivate *priv;
  GstRTSPAddress *result;
  GstRTSPAddress **addrp;
  GstRTSPAddressFlags flags;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);

  priv = stream->priv;

  g_mutex_lock (&stream->priv->lock);

  if (family == G_SOCKET_FAMILY_IPV6) {
    flags = GST_RTSP_ADDRESS_FLAG_IPV6;
    addrp = &priv->mcast_addr_v6;
  } else {
    flags = GST_RTSP_ADDRESS_FLAG_IPV4;
    addrp = &priv->mcast_addr_v4;
  }

  if (*addrp == NULL) {
    if (priv->pool == NULL)
      goto no_pool;

    flags |= GST_RTSP_ADDRESS_FLAG_EVEN_PORT | GST_RTSP_ADDRESS_FLAG_MULTICAST;

    *addrp = gst_rtsp_address_pool_acquire_address (priv->pool, flags, 2);
    if (*addrp == NULL)
      goto no_address;

    /* FIXME: Also reserve the same port with unicast ANY address, since that's
     * where we are going to bind our socket. Probably loop until we find a port
     * available in both mcast and unicast pools. Maybe GstRTSPAddressPool
     * should do it for us when both GST_RTSP_ADDRESS_FLAG_MULTICAST and
     * GST_RTSP_ADDRESS_FLAG_UNICAST are givent. */
  }
  result = gst_rtsp_address_copy (*addrp);

  g_mutex_unlock (&stream->priv->lock);

  return result;

  /* ERRORS */
no_pool:
  {
    GST_ERROR_OBJECT (stream, "no address pool specified");
    g_mutex_unlock (&stream->priv->lock);
    return NULL;
  }
no_address:
  {
    GST_ERROR_OBJECT (stream, "failed to acquire address from pool");
    g_mutex_unlock (&stream->priv->lock);
    return NULL;
  }
}

/**
 * gst_rtsp_stream_reserve_address:
 * @stream: a #GstRTSPStream
 * @address: an address
 * @port: a port
 * @n_ports: n_ports
 * @ttl: a TTL
 *
 * Reserve @address and @port as the address and port of @stream. The original
 * #GstRTSPAddress is cached and copy is returned, so freeing the return value
 * won't release the address from the pool.
 *
 * Returns: (nullable): the #GstRTSPAddress of @stream or %NULL when
 * the address could be reserved. gst_rtsp_address_free() after usage.
 */
GstRTSPAddress *
gst_rtsp_stream_reserve_address (GstRTSPStream * stream,
    const gchar * address, guint port, guint n_ports, guint ttl)
{
  GstRTSPStreamPrivate *priv;
  GstRTSPAddress *result;
  GInetAddress *addr;
  GSocketFamily family;
  GstRTSPAddress **addrp;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
  g_return_val_if_fail (address != NULL, NULL);
  g_return_val_if_fail (port > 0, NULL);
  g_return_val_if_fail (n_ports > 0, NULL);
  g_return_val_if_fail (ttl > 0, NULL);

  priv = stream->priv;

  addr = g_inet_address_new_from_string (address);
  if (!addr) {
    GST_ERROR ("failed to get inet addr from %s", address);
    family = G_SOCKET_FAMILY_IPV4;
  } else {
    family = g_inet_address_get_family (addr);
    g_object_unref (addr);
  }

  if (family == G_SOCKET_FAMILY_IPV6)
    addrp = &priv->mcast_addr_v6;
  else
    addrp = &priv->mcast_addr_v4;

  g_mutex_lock (&priv->lock);
  if (*addrp == NULL) {
    GstRTSPAddressPoolResult res;

    if (priv->pool == NULL)
      goto no_pool;

    res = gst_rtsp_address_pool_reserve_address (priv->pool, address,
        port, n_ports, ttl, addrp);
    if (res != GST_RTSP_ADDRESS_POOL_OK)
      goto no_address;

    /* FIXME: Also reserve the same port with unicast ANY address, since that's
     * where we are going to bind our socket. */
  } else {
    if (g_ascii_strcasecmp ((*addrp)->address, address) ||
        (*addrp)->port != port || (*addrp)->n_ports != n_ports ||
        (*addrp)->ttl != ttl)
      goto different_address;
  }
  result = gst_rtsp_address_copy (*addrp);
  g_mutex_unlock (&priv->lock);

  return result;

  /* ERRORS */
no_pool:
  {
    GST_ERROR_OBJECT (stream, "no address pool specified");
    g_mutex_unlock (&priv->lock);
    return NULL;
  }
no_address:
  {
    GST_ERROR_OBJECT (stream, "failed to acquire address %s from pool",
        address);
    g_mutex_unlock (&priv->lock);
    return NULL;
  }
different_address:
  {
    GST_ERROR_OBJECT (stream,
        "address %s is not the same as %s that was already reserved",
        address, (*addrp)->address);
    g_mutex_unlock (&priv->lock);
    return NULL;
  }
}

/* must be called with lock */
static void
set_socket_for_udpsink (GstElement * udpsink, GSocket * socket,
    GSocketFamily family)
{
  const gchar *multisink_socket;

  if (family == G_SOCKET_FAMILY_IPV6)
    multisink_socket = "socket-v6";
  else
    multisink_socket = "socket";

  g_object_set (G_OBJECT (udpsink), multisink_socket, socket, NULL);
}

/* must be called with lock */
static void
set_multicast_socket_for_udpsink (GstElement * udpsink, GSocket * socket,
    GSocketFamily family, const gchar * multicast_iface,
    const gchar * addr_str, gint port)
{
  set_socket_for_udpsink (udpsink, socket, family);

  if (multicast_iface) {
    g_object_set (G_OBJECT (udpsink), "multicast-iface", multicast_iface, NULL);
  }

  g_signal_emit_by_name (udpsink, "add", addr_str, port, NULL);
}


/* must be called with lock */
static void
set_unicast_socket_for_udpsink (GstElement * udpsink, GSocket * socket,
    GSocketFamily family)
{
  set_socket_for_udpsink (udpsink, socket, family);
}

static guint16
get_port_from_socket (GSocket * socket)
{
  guint16 port;
  GSocketAddress *sockaddr;
  GError *err;

  GST_DEBUG ("socket: %p", socket);
  sockaddr = g_socket_get_local_address (socket, &err);
  if (sockaddr == NULL || !G_IS_INET_SOCKET_ADDRESS (sockaddr)) {
    g_clear_object (&sockaddr);
    GST_ERROR ("failed to get sockaddr: %s", err->message);
    g_error_free (err);
    return 0;
  }

  port = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (sockaddr));
  g_object_unref (sockaddr);

  return port;
}


static gboolean
create_and_configure_udpsink (GstRTSPStream * stream, GstElement ** udpsink,
    GSocket * socket_v4, GSocket * socket_v6, gboolean multicast,
    gboolean is_rtp)
{
  GstRTSPStreamPrivate *priv = stream->priv;

  *udpsink = gst_element_factory_make ("multiudpsink", NULL);

  if (!*udpsink)
    goto no_udp_protocol;

  /* configure sinks */

  g_object_set (G_OBJECT (*udpsink), "close-socket", FALSE, NULL);

  g_object_set (G_OBJECT (*udpsink), "send-duplicates", FALSE, NULL);

  if (is_rtp)
    g_object_set (G_OBJECT (*udpsink), "buffer-size", priv->buffer_size, NULL);
  else
    g_object_set (G_OBJECT (*udpsink), "sync", FALSE, NULL);

  /* Needs to be async for RECORD streams, otherwise we will never go to
   * PLAYING because the sinks will wait for data while the udpsrc can't
   * provide data with timestamps in PAUSED. */
  if (!is_rtp || priv->sinkpad)
    g_object_set (G_OBJECT (*udpsink), "async", FALSE, NULL);

  if (multicast) {
    /* join multicast group when adding clients, so we'll start receiving from it.
     * We cannot rely on the udpsrc to join the group since its socket is always a
     * local unicast one. */
    g_object_set (G_OBJECT (*udpsink), "auto-multicast", TRUE, NULL);

    g_object_set (G_OBJECT (*udpsink), "loop", FALSE, NULL);
  }

  /* update the dscp qos field in the sinks */
  update_dscp_qos (stream, udpsink);

  if (priv->server_addr_v4) {
    GST_DEBUG_OBJECT (stream, "udp IPv4, configure udpsinks");
    set_unicast_socket_for_udpsink (*udpsink, socket_v4, G_SOCKET_FAMILY_IPV4);
  }

  if (priv->server_addr_v6) {
    GST_DEBUG_OBJECT (stream, "udp IPv6, configure udpsinks");
    set_unicast_socket_for_udpsink (*udpsink, socket_v6, G_SOCKET_FAMILY_IPV6);
  }

  if (multicast) {
    gint port;
    if (priv->mcast_addr_v4) {
      GST_DEBUG_OBJECT (stream, "mcast IPv4, configure udpsinks");
      port = get_port_from_socket (socket_v4);
      if (!port)
        goto get_port_failed;
      set_multicast_socket_for_udpsink (*udpsink, socket_v4,
          G_SOCKET_FAMILY_IPV4, priv->multicast_iface,
          priv->mcast_addr_v4->address, port);
    }

    if (priv->mcast_addr_v6) {
      GST_DEBUG_OBJECT (stream, "mcast IPv6, configure udpsinks");
      port = get_port_from_socket (socket_v6);
      if (!port)
        goto get_port_failed;
      set_multicast_socket_for_udpsink (*udpsink, socket_v6,
          G_SOCKET_FAMILY_IPV6, priv->multicast_iface,
          priv->mcast_addr_v6->address, port);
    }

  }

  return TRUE;

  /* ERRORS */
no_udp_protocol:
  {
    GST_ERROR_OBJECT (stream, "failed to create udpsink element");
    return FALSE;
  }
get_port_failed:
  {
    GST_ERROR_OBJECT (stream, "failed to get udp port");
    return FALSE;
  }
}

/* must be called with lock */
static gboolean
create_and_configure_udpsource (GstElement ** udpsrc, GSocket * socket)
{
  GstStateChangeReturn ret;

  g_assert (socket != NULL);

  *udpsrc = gst_element_factory_make ("udpsrc", NULL);
  if (*udpsrc == NULL)
    goto error;

  g_object_set (G_OBJECT (*udpsrc), "socket", socket, NULL);

  /* The udpsrc cannot do the join because its socket is always a local unicast
   * one. The udpsink sharing the same socket will do it for us. */
  g_object_set (G_OBJECT (*udpsrc), "auto-multicast", FALSE, NULL);

  g_object_set (G_OBJECT (*udpsrc), "loop", FALSE, NULL);

  g_object_set (G_OBJECT (*udpsrc), "close-socket", FALSE, NULL);

  ret = gst_element_set_state (*udpsrc, GST_STATE_READY);
  if (ret == GST_STATE_CHANGE_FAILURE)
    goto error;

  return TRUE;

  /* ERRORS */
error:
  {
    if (*udpsrc) {
      gst_element_set_state (*udpsrc, GST_STATE_NULL);
      g_clear_object (udpsrc);
    }
    return FALSE;
  }
}

static gboolean
alloc_ports_one_family (GstRTSPStream * stream, GSocketFamily family,
    GSocket * socket_out[2], GstRTSPAddress ** server_addr_out,
    gboolean multicast, GstRTSPTransport * ct)
{
  GstRTSPStreamPrivate *priv = stream->priv;
  GSocket *rtp_socket = NULL;
  GSocket *rtcp_socket;
  gint tmp_rtp, tmp_rtcp;
  guint count;
  GList *rejected_addresses = NULL;
  GstRTSPAddress *addr = NULL;
  GInetAddress *inetaddr = NULL;
  GSocketAddress *rtp_sockaddr = NULL;
  GSocketAddress *rtcp_sockaddr = NULL;
  GstRTSPAddressPool *pool;

  pool = priv->pool;
  count = 0;

  /* Start with random port */
  tmp_rtp = 0;

  rtcp_socket = g_socket_new (family, G_SOCKET_TYPE_DATAGRAM,
      G_SOCKET_PROTOCOL_UDP, NULL);
  if (!rtcp_socket)
    goto no_udp_protocol;
  g_socket_set_multicast_loopback (rtcp_socket, FALSE);

  /* try to allocate 2 UDP ports, the RTP port should be an even
   * number and the RTCP port should be the next (uneven) port */
again:

  if (rtp_socket == NULL) {
    rtp_socket = g_socket_new (family, G_SOCKET_TYPE_DATAGRAM,
        G_SOCKET_PROTOCOL_UDP, NULL);
    if (!rtp_socket)
      goto no_udp_protocol;
    g_socket_set_multicast_loopback (rtp_socket, FALSE);
  }

  if ((pool && gst_rtsp_address_pool_has_unicast_addresses (pool)) || multicast) {
    GstRTSPAddressFlags flags;

    if (addr)
      rejected_addresses = g_list_prepend (rejected_addresses, addr);

    if (!pool)
      goto no_pool;

    flags = GST_RTSP_ADDRESS_FLAG_EVEN_PORT;
    if (multicast)
      flags |= GST_RTSP_ADDRESS_FLAG_MULTICAST;
    else
      flags |= GST_RTSP_ADDRESS_FLAG_UNICAST;

    if (family == G_SOCKET_FAMILY_IPV6)
      flags |= GST_RTSP_ADDRESS_FLAG_IPV6;
    else
      flags |= GST_RTSP_ADDRESS_FLAG_IPV4;

    addr = gst_rtsp_address_pool_acquire_address (pool, flags, 2);

    if (addr == NULL)
      goto no_address;

    tmp_rtp = addr->port;

    g_clear_object (&inetaddr);
    /* FIXME: Does it really work with the IP_MULTICAST_ALL socket option and
     * socket control message set in udpsrc? */
    if (multicast)
      inetaddr = g_inet_address_new_any (family);
    else
      inetaddr = g_inet_address_new_from_string (addr->address);
  } else {
    if (tmp_rtp != 0) {
      tmp_rtp += 2;
      if (++count > 20)
        goto no_ports;
    }

    if (inetaddr == NULL)
      inetaddr = g_inet_address_new_any (family);
  }

  rtp_sockaddr = g_inet_socket_address_new (inetaddr, tmp_rtp);
  if (!g_socket_bind (rtp_socket, rtp_sockaddr, FALSE, NULL)) {
    GST_DEBUG_OBJECT (stream, "rtp bind() failed, will try again");
    g_object_unref (rtp_sockaddr);
    goto again;
  }
  g_object_unref (rtp_sockaddr);

  rtp_sockaddr = g_socket_get_local_address (rtp_socket, NULL);
  if (rtp_sockaddr == NULL || !G_IS_INET_SOCKET_ADDRESS (rtp_sockaddr)) {
    g_clear_object (&rtp_sockaddr);
    goto socket_error;
  }

  tmp_rtp =
      g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (rtp_sockaddr));
  g_object_unref (rtp_sockaddr);

  /* check if port is even */
  if ((tmp_rtp & 1) != 0) {
    /* port not even, close and allocate another */
    tmp_rtp++;
    g_clear_object (&rtp_socket);
    goto again;
  }

  /* set port */
  tmp_rtcp = tmp_rtp + 1;

  rtcp_sockaddr = g_inet_socket_address_new (inetaddr, tmp_rtcp);
  if (!g_socket_bind (rtcp_socket, rtcp_sockaddr, FALSE, NULL)) {
    GST_DEBUG_OBJECT (stream, "rctp bind() failed, will try again");
    g_object_unref (rtcp_sockaddr);
    g_clear_object (&rtp_socket);
    goto again;
  }
  g_object_unref (rtcp_sockaddr);

  if (!addr) {
    addr = g_slice_new0 (GstRTSPAddress);
    addr->address = g_inet_address_to_string (inetaddr);
    addr->port = tmp_rtp;
    addr->n_ports = 2;
  }

  g_clear_object (&inetaddr);

  socket_out[0] = rtp_socket;
  socket_out[1] = rtcp_socket;
  *server_addr_out = addr;

  GST_DEBUG_OBJECT (stream, "allocated address: %s and ports: %d, %d",
      addr->address, tmp_rtp, tmp_rtcp);

  g_list_free_full (rejected_addresses, (GDestroyNotify) gst_rtsp_address_free);

  return TRUE;

  /* ERRORS */
no_udp_protocol:
  {
    GST_ERROR_OBJECT (stream, "failed to allocate UDP ports: protocol error");
    goto cleanup;
  }
no_pool:
  {
    GST_ERROR_OBJECT (stream,
        "failed to allocate UDP ports: no address pool specified");
    goto cleanup;
  }
no_address:
  {
    GST_ERROR_OBJECT (stream, "failed to acquire address from pool");
    goto cleanup;
  }
no_ports:
  {
    GST_ERROR_OBJECT (stream, "failed to allocate UDP ports: no ports");
    goto cleanup;
  }
socket_error:
  {
    GST_ERROR_OBJECT (stream, "failed to allocate UDP ports: socket error");
    goto cleanup;
  }
cleanup:
  {
    if (inetaddr)
      g_object_unref (inetaddr);
    g_list_free_full (rejected_addresses,
        (GDestroyNotify) gst_rtsp_address_free);
    if (addr)
      gst_rtsp_address_free (addr);
    if (rtp_socket)
      g_object_unref (rtp_socket);
    if (rtcp_socket)
      g_object_unref (rtcp_socket);
    return FALSE;
  }
}

/**
 * gst_rtsp_stream_allocate_udp_sockets:
 * @stream: a #GstRTSPStream
 * @family: protocol family
 * @transport: transport method
 * @use_client_settings: Whether to use client settings or not
 *
 * Allocates RTP and RTCP ports.
 *
 * Returns: %TRUE if the RTP and RTCP sockets have been succeccully allocated.
 */
gboolean
gst_rtsp_stream_allocate_udp_sockets (GstRTSPStream * stream,
    GSocketFamily family, GstRTSPTransport * ct,
    gboolean use_transport_settings)
{
  GstRTSPStreamPrivate *priv;
  gboolean ret = FALSE;
  GstRTSPLowerTrans transport;
  gboolean allocated = FALSE;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
  g_return_val_if_fail (ct != NULL, FALSE);
  priv = stream->priv;

  transport = ct->lower_transport;

  g_mutex_lock (&priv->lock);

  if (transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
    if (family == G_SOCKET_FAMILY_IPV4 && priv->mcast_socket_v4[0])
      allocated = TRUE;
    else if (family == G_SOCKET_FAMILY_IPV6 && priv->mcast_socket_v6[0])
      allocated = TRUE;
  } else if (transport == GST_RTSP_LOWER_TRANS_UDP) {
    if (family == G_SOCKET_FAMILY_IPV4 && priv->socket_v4[0])
      allocated = TRUE;
    else if (family == G_SOCKET_FAMILY_IPV6 && priv->socket_v6[0])
      allocated = TRUE;
  }

  if (allocated) {
    GST_DEBUG_OBJECT (stream, "Allocated already");
    g_mutex_unlock (&priv->lock);
    return TRUE;
  }

  if (family == G_SOCKET_FAMILY_IPV4) {
    /* IPv4 */
    if (transport == GST_RTSP_LOWER_TRANS_UDP) {
      /* UDP unicast */
      GST_DEBUG_OBJECT (stream, "GST_RTSP_LOWER_TRANS_UDP, ipv4");
      ret = alloc_ports_one_family (stream, G_SOCKET_FAMILY_IPV4,
          priv->socket_v4, &priv->server_addr_v4, FALSE, ct);
    } else {
      /* multicast */
      GST_DEBUG_OBJECT (stream, "GST_RTSP_LOWER_TRANS_MCAST_UDP, ipv4");
      ret = alloc_ports_one_family (stream, G_SOCKET_FAMILY_IPV4,
          priv->mcast_socket_v4, &priv->mcast_addr_v4, TRUE, ct);
    }
  } else {
    /* IPv6 */
    if (transport == GST_RTSP_LOWER_TRANS_UDP) {
      /* unicast */
      GST_DEBUG_OBJECT (stream, "GST_RTSP_LOWER_TRANS_UDP, ipv6");
      ret = alloc_ports_one_family (stream, G_SOCKET_FAMILY_IPV6,
          priv->socket_v6, &priv->server_addr_v6, FALSE, ct);

    } else {
      /* multicast */
      GST_DEBUG_OBJECT (stream, "GST_RTSP_LOWER_TRANS_MCAST_UDP, ipv6");
      ret = alloc_ports_one_family (stream, G_SOCKET_FAMILY_IPV6,
          priv->mcast_socket_v6, &priv->mcast_addr_v6, TRUE, ct);
    }
  }
  g_mutex_unlock (&priv->lock);

  return ret;
}

/**
 * gst_rtsp_stream_set_client_side:
 * @stream: a #GstRTSPStream
 * @client_side: TRUE if this #GstRTSPStream is running on the 'client' side of
 * an RTSP connection.
 *
 * Sets the #GstRTSPStream as a 'client side' stream - used for sending
 * streams to an RTSP server via RECORD. This has the practical effect
 * of changing which UDP port numbers are used when setting up the local
 * side of the stream sending to be either the 'server' or 'client' pair
 * of a configured UDP transport.
 */
void
gst_rtsp_stream_set_client_side (GstRTSPStream * stream, gboolean client_side)
{
  GstRTSPStreamPrivate *priv;

  g_return_if_fail (GST_IS_RTSP_STREAM (stream));
  priv = stream->priv;
  g_mutex_lock (&priv->lock);
  priv->client_side = client_side;
  g_mutex_unlock (&priv->lock);
}

/**
 * gst_rtsp_stream_is_client_side:
 * @stream: a #GstRTSPStream
 *
 * See gst_rtsp_stream_set_client_side()
 *
 * Returns: TRUE if this #GstRTSPStream is client-side.
 */
gboolean
gst_rtsp_stream_is_client_side (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  gboolean ret;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);

  priv = stream->priv;
  g_mutex_lock (&priv->lock);
  ret = priv->client_side;
  g_mutex_unlock (&priv->lock);

  return ret;
}

/**
 * gst_rtsp_stream_get_server_port:
 * @stream: a #GstRTSPStream
 * @server_port: (out): result server port
 * @family: the port family to get
 *
 * Fill @server_port with the port pair used by the server. This function can
 * only be called when @stream has been joined.
 */
void
gst_rtsp_stream_get_server_port (GstRTSPStream * stream,
    GstRTSPRange * server_port, GSocketFamily family)
{
  GstRTSPStreamPrivate *priv;

  g_return_if_fail (GST_IS_RTSP_STREAM (stream));
  priv = stream->priv;
  g_return_if_fail (priv->joined_bin != NULL);

  if (server_port) {
    server_port->min = 0;
    server_port->max = 0;
  }

  g_mutex_lock (&priv->lock);
  if (family == G_SOCKET_FAMILY_IPV4) {
    if (server_port && priv->server_addr_v4) {
      server_port->min = priv->server_addr_v4->port;
      server_port->max =
          priv->server_addr_v4->port + priv->server_addr_v4->n_ports - 1;
    }
  } else {
    if (server_port && priv->server_addr_v6) {
      server_port->min = priv->server_addr_v6->port;
      server_port->max =
          priv->server_addr_v6->port + priv->server_addr_v6->n_ports - 1;
    }
  }
  g_mutex_unlock (&priv->lock);
}

/**
 * gst_rtsp_stream_get_rtpsession:
 * @stream: a #GstRTSPStream
 *
 * Get the RTP session of this stream.
 *
 * Returns: (transfer full): The RTP session of this stream. Unref after usage.
 */
GObject *
gst_rtsp_stream_get_rtpsession (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  GObject *session;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  if ((session = priv->session))
    g_object_ref (session);
  g_mutex_unlock (&priv->lock);

  return session;
}

/**
 * gst_rtsp_stream_get_srtp_encoder:
 * @stream: a #GstRTSPStream
 *
 * Get the SRTP encoder for this stream.
 *
 * Returns: (transfer full): The SRTP encoder for this stream. Unref after usage.
 */
GstElement *
gst_rtsp_stream_get_srtp_encoder (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  GstElement *encoder;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  if ((encoder = priv->srtpenc))
    g_object_ref (encoder);
  g_mutex_unlock (&priv->lock);

  return encoder;
}

/**
 * gst_rtsp_stream_get_ssrc:
 * @stream: a #GstRTSPStream
 * @ssrc: (out): result ssrc
 *
 * Get the SSRC used by the RTP session of this stream. This function can only
 * be called when @stream has been joined.
 */
void
gst_rtsp_stream_get_ssrc (GstRTSPStream * stream, guint * ssrc)
{
  GstRTSPStreamPrivate *priv;

  g_return_if_fail (GST_IS_RTSP_STREAM (stream));
  priv = stream->priv;
  g_return_if_fail (priv->joined_bin != NULL);

  g_mutex_lock (&priv->lock);
  if (ssrc && priv->session)
    g_object_get (priv->session, "internal-ssrc", ssrc, NULL);
  g_mutex_unlock (&priv->lock);
}

/**
 * gst_rtsp_stream_set_retransmission_time:
 * @stream: a #GstRTSPStream
 * @time: a #GstClockTime
 *
 * Set the amount of time to store retransmission packets.
 */
void
gst_rtsp_stream_set_retransmission_time (GstRTSPStream * stream,
    GstClockTime time)
{
  GST_DEBUG_OBJECT (stream, "set retransmission time %" G_GUINT64_FORMAT, time);

  g_mutex_lock (&stream->priv->lock);
  stream->priv->rtx_time = time;
  if (stream->priv->rtxsend)
    g_object_set (stream->priv->rtxsend, "max-size-time",
        GST_TIME_AS_MSECONDS (time), NULL);
  g_mutex_unlock (&stream->priv->lock);
}

/**
 * gst_rtsp_stream_get_retransmission_time:
 * @stream: a #GstRTSPStream
 *
 * Get the amount of time to store retransmission data.
 *
 * Returns: the amount of time to store retransmission data.
 */
GstClockTime
gst_rtsp_stream_get_retransmission_time (GstRTSPStream * stream)
{
  GstClockTime ret;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), 0);

  g_mutex_lock (&stream->priv->lock);
  ret = stream->priv->rtx_time;
  g_mutex_unlock (&stream->priv->lock);

  return ret;
}

/**
 * gst_rtsp_stream_set_retransmission_pt:
 * @stream: a #GstRTSPStream
 * @rtx_pt: a #guint
 *
 * Set the payload type (pt) for retransmission of this stream.
 */
void
gst_rtsp_stream_set_retransmission_pt (GstRTSPStream * stream, guint rtx_pt)
{
  g_return_if_fail (GST_IS_RTSP_STREAM (stream));

  GST_DEBUG_OBJECT (stream, "set retransmission pt %u", rtx_pt);

  g_mutex_lock (&stream->priv->lock);
  stream->priv->rtx_pt = rtx_pt;
  if (stream->priv->rtxsend) {
    guint pt = gst_rtsp_stream_get_pt (stream);
    gchar *pt_s = g_strdup_printf ("%d", pt);
    GstStructure *rtx_pt_map = gst_structure_new ("application/x-rtp-pt-map",
        pt_s, G_TYPE_UINT, rtx_pt, NULL);
    g_object_set (stream->priv->rtxsend, "payload-type-map", rtx_pt_map, NULL);
    g_free (pt_s);
    gst_structure_free (rtx_pt_map);
  }
  g_mutex_unlock (&stream->priv->lock);
}

/**
 * gst_rtsp_stream_get_retransmission_pt:
 * @stream: a #GstRTSPStream
 *
 * Get the payload-type used for retransmission of this stream
 *
 * Returns: The retransmission PT.
 */
guint
gst_rtsp_stream_get_retransmission_pt (GstRTSPStream * stream)
{
  guint rtx_pt;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), 0);

  g_mutex_lock (&stream->priv->lock);
  rtx_pt = stream->priv->rtx_pt;
  g_mutex_unlock (&stream->priv->lock);

  return rtx_pt;
}

/**
 * gst_rtsp_stream_set_buffer_size:
 * @stream: a #GstRTSPStream
 * @size: the buffer size
 *
 * Set the size of the UDP transmission buffer (in bytes)
 * Needs to be set before the stream is joined to a bin.
 *
 * Since: 1.6
 */
void
gst_rtsp_stream_set_buffer_size (GstRTSPStream * stream, guint size)
{
  g_mutex_lock (&stream->priv->lock);
  stream->priv->buffer_size = size;
  g_mutex_unlock (&stream->priv->lock);
}

/**
 * gst_rtsp_stream_get_buffer_size:
 * @stream: a #GstRTSPStream
 *
 * Get the size of the UDP transmission buffer (in bytes)
 *
 * Returns: the size of the UDP TX buffer
 *
 * Since: 1.6
 */
guint
gst_rtsp_stream_get_buffer_size (GstRTSPStream * stream)
{
  guint buffer_size;

  g_mutex_lock (&stream->priv->lock);
  buffer_size = stream->priv->buffer_size;
  g_mutex_unlock (&stream->priv->lock);

  return buffer_size;
}

/* executed from streaming thread */
static void
caps_notify (GstPad * pad, GParamSpec * unused, GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv = stream->priv;
  GstCaps *newcaps, *oldcaps;

  newcaps = gst_pad_get_current_caps (pad);

  GST_INFO ("stream %p received caps %p, %" GST_PTR_FORMAT, stream, newcaps,
      newcaps);

  g_mutex_lock (&priv->lock);
  oldcaps = priv->caps;
  priv->caps = newcaps;
  g_mutex_unlock (&priv->lock);

  if (oldcaps)
    gst_caps_unref (oldcaps);
}

static void
dump_structure (const GstStructure * s)
{
  gchar *sstr;

  sstr = gst_structure_to_string (s);
  GST_INFO ("structure: %s", sstr);
  g_free (sstr);
}

static GstRTSPStreamTransport *
find_transport (GstRTSPStream * stream, const gchar * rtcp_from)
{
  GstRTSPStreamPrivate *priv = stream->priv;
  GList *walk;
  GstRTSPStreamTransport *result = NULL;
  const gchar *tmp;
  gchar *dest;
  guint port;

  if (rtcp_from == NULL)
    return NULL;

  tmp = g_strrstr (rtcp_from, ":");
  if (tmp == NULL)
    return NULL;

  port = atoi (tmp + 1);
  dest = g_strndup (rtcp_from, tmp - rtcp_from);

  g_mutex_lock (&priv->lock);
  GST_INFO ("finding %s:%d in %d transports", dest, port,
      g_list_length (priv->transports));

  for (walk = priv->transports; walk; walk = g_list_next (walk)) {
    GstRTSPStreamTransport *trans = walk->data;
    const GstRTSPTransport *tr;
    gint min, max;

    tr = gst_rtsp_stream_transport_get_transport (trans);

    if (priv->client_side) {
      /* In client side mode the 'destination' is the RTSP server, so send
       * to those ports */
      min = tr->server_port.min;
      max = tr->server_port.max;
    } else {
      min = tr->client_port.min;
      max = tr->client_port.max;
    }

    if ((g_ascii_strcasecmp (tr->destination, dest) == 0) &&
        (min == port || max == port)) {
      result = trans;
      break;
    }
  }
  if (result)
    g_object_ref (result);
  g_mutex_unlock (&priv->lock);

  g_free (dest);

  return result;
}

static GstRTSPStreamTransport *
check_transport (GObject * source, GstRTSPStream * stream)
{
  GstStructure *stats;
  GstRTSPStreamTransport *trans;

  /* see if we have a stream to match with the origin of the RTCP packet */
  trans = g_object_get_qdata (source, ssrc_stream_map_key);
  if (trans == NULL) {
    g_object_get (source, "stats", &stats, NULL);
    if (stats) {
      const gchar *rtcp_from;

      dump_structure (stats);

      rtcp_from = gst_structure_get_string (stats, "rtcp-from");
      if ((trans = find_transport (stream, rtcp_from))) {
        GST_INFO ("%p: found transport %p for source  %p", stream, trans,
            source);
        g_object_set_qdata_full (source, ssrc_stream_map_key, trans,
            g_object_unref);
      }
      gst_structure_free (stats);
    }
  }
  return trans;
}


static void
on_new_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
{
  GstRTSPStreamTransport *trans;

  GST_INFO ("%p: new source %p", stream, source);

  trans = check_transport (source, stream);

  if (trans)
    GST_INFO ("%p: source %p for transport %p", stream, source, trans);
}

static void
on_ssrc_sdes (GObject * session, GObject * source, GstRTSPStream * stream)
{
  GST_INFO ("%p: new SDES %p", stream, source);
}

static void
on_ssrc_active (GObject * session, GObject * source, GstRTSPStream * stream)
{
  GstRTSPStreamTransport *trans;

  trans = check_transport (source, stream);

  if (trans) {
    GST_INFO ("%p: source %p in transport %p is active", stream, source, trans);
    gst_rtsp_stream_transport_keep_alive (trans);
  }
#ifdef DUMP_STATS
  {
    GstStructure *stats;
    g_object_get (source, "stats", &stats, NULL);
    if (stats) {
      dump_structure (stats);
      gst_structure_free (stats);
    }
  }
#endif
}

static void
on_bye_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
{
  GST_INFO ("%p: source %p bye", stream, source);
}

static void
on_bye_timeout (GObject * session, GObject * source, GstRTSPStream * stream)
{
  GstRTSPStreamTransport *trans;

  GST_INFO ("%p: source %p bye timeout", stream, source);

  if ((trans = g_object_get_qdata (source, ssrc_stream_map_key))) {
    gst_rtsp_stream_transport_set_timed_out (trans, TRUE);
    g_object_set_qdata (source, ssrc_stream_map_key, NULL);
  }
}

static void
on_timeout (GObject * session, GObject * source, GstRTSPStream * stream)
{
  GstRTSPStreamTransport *trans;

  GST_INFO ("%p: source %p timeout", stream, source);

  if ((trans = g_object_get_qdata (source, ssrc_stream_map_key))) {
    gst_rtsp_stream_transport_set_timed_out (trans, TRUE);
    g_object_set_qdata (source, ssrc_stream_map_key, NULL);
  }
}

static void
on_new_sender_ssrc (GObject * session, GObject * source, GstRTSPStream * stream)
{
  GST_INFO ("%p: new sender source %p", stream, source);
#ifndef DUMP_STATS
  {
    GstStructure *stats;
    g_object_get (source, "stats", &stats, NULL);
    if (stats) {
      dump_structure (stats);
      gst_structure_free (stats);
    }
  }
#endif
}

static void
on_sender_ssrc_active (GObject * session, GObject * source,
    GstRTSPStream * stream)
{
#ifndef DUMP_STATS
  {
    GstStructure *stats;
    g_object_get (source, "stats", &stats, NULL);
    if (stats) {
      dump_structure (stats);
      gst_structure_free (stats);
    }
  }
#endif
}

static void
clear_tr_cache (GstRTSPStreamPrivate * priv, gboolean is_rtp)
{
  if (is_rtp) {
    g_list_foreach (priv->tr_cache_rtp, (GFunc) g_object_unref, NULL);
    g_list_free (priv->tr_cache_rtp);
    priv->tr_cache_rtp = NULL;
  } else {
    g_list_foreach (priv->tr_cache_rtcp, (GFunc) g_object_unref, NULL);
    g_list_free (priv->tr_cache_rtcp);
    priv->tr_cache_rtcp = NULL;
  }
}

static GstFlowReturn
handle_new_sample (GstAppSink * sink, gpointer user_data)
{
  GstRTSPStreamPrivate *priv;
  GList *walk;
  GstSample *sample;
  GstBuffer *buffer;
  GstRTSPStream *stream;
  gboolean is_rtp;

  sample = gst_app_sink_pull_sample (sink);
  if (!sample)
    return GST_FLOW_OK;

  stream = (GstRTSPStream *) user_data;
  priv = stream->priv;
  buffer = gst_sample_get_buffer (sample);

  is_rtp = GST_ELEMENT_CAST (sink) == priv->appsink[0];

  g_mutex_lock (&priv->lock);
  if (is_rtp) {
    if (priv->tr_cache_cookie_rtp != priv->transports_cookie) {
      clear_tr_cache (priv, is_rtp);
      for (walk = priv->transports; walk; walk = g_list_next (walk)) {
        GstRTSPStreamTransport *tr = (GstRTSPStreamTransport *) walk->data;
        priv->tr_cache_rtp =
            g_list_prepend (priv->tr_cache_rtp, g_object_ref (tr));
      }
      priv->tr_cache_cookie_rtp = priv->transports_cookie;
    }
  } else {
    if (priv->tr_cache_cookie_rtcp != priv->transports_cookie) {
      clear_tr_cache (priv, is_rtp);
      for (walk = priv->transports; walk; walk = g_list_next (walk)) {
        GstRTSPStreamTransport *tr = (GstRTSPStreamTransport *) walk->data;
        priv->tr_cache_rtcp =
            g_list_prepend (priv->tr_cache_rtcp, g_object_ref (tr));
      }
      priv->tr_cache_cookie_rtcp = priv->transports_cookie;
    }
  }
  g_mutex_unlock (&priv->lock);

  if (is_rtp) {
    for (walk = priv->tr_cache_rtp; walk; walk = g_list_next (walk)) {
      GstRTSPStreamTransport *tr = (GstRTSPStreamTransport *) walk->data;
      gst_rtsp_stream_transport_send_rtp (tr, buffer);
    }
  } else {
    for (walk = priv->tr_cache_rtcp; walk; walk = g_list_next (walk)) {
      GstRTSPStreamTransport *tr = (GstRTSPStreamTransport *) walk->data;
      gst_rtsp_stream_transport_send_rtcp (tr, buffer);
    }
  }
  gst_sample_unref (sample);

  return GST_FLOW_OK;
}

static GstAppSinkCallbacks sink_cb = {
  NULL,                         /* not interested in EOS */
  NULL,                         /* not interested in preroll samples */
  handle_new_sample,
};

static GstElement *
get_rtp_encoder (GstRTSPStream * stream, guint session)
{
  GstRTSPStreamPrivate *priv = stream->priv;

  if (priv->srtpenc == NULL) {
    gchar *name;

    name = g_strdup_printf ("srtpenc_%u", session);
    priv->srtpenc = gst_element_factory_make ("srtpenc", name);
    g_free (name);

    g_object_set (priv->srtpenc, "random-key", TRUE, NULL);
  }
  return gst_object_ref (priv->srtpenc);
}

static GstElement *
request_rtp_encoder (GstElement * rtpbin, guint session, GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv = stream->priv;
  GstElement *oldenc, *enc;
  GstPad *pad;
  gchar *name;

  if (priv->idx != session)
    return NULL;

  GST_DEBUG_OBJECT (stream, "make RTP encoder for session %u", session);

  oldenc = priv->srtpenc;
  enc = get_rtp_encoder (stream, session);
  name = g_strdup_printf ("rtp_sink_%d", session);
  pad = gst_element_get_request_pad (enc, name);
  g_free (name);
  gst_object_unref (pad);

  if (oldenc == NULL)
    g_signal_emit (stream, gst_rtsp_stream_signals[SIGNAL_NEW_RTP_ENCODER], 0,
        enc);

  return enc;
}

static GstElement *
request_rtcp_encoder (GstElement * rtpbin, guint session,
    GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv = stream->priv;
  GstElement *oldenc, *enc;
  GstPad *pad;
  gchar *name;

  if (priv->idx != session)
    return NULL;

  GST_DEBUG_OBJECT (stream, "make RTCP encoder for session %u", session);

  oldenc = priv->srtpenc;
  enc = get_rtp_encoder (stream, session);
  name = g_strdup_printf ("rtcp_sink_%d", session);
  pad = gst_element_get_request_pad (enc, name);
  g_free (name);
  gst_object_unref (pad);

  if (oldenc == NULL)
    g_signal_emit (stream, gst_rtsp_stream_signals[SIGNAL_NEW_RTCP_ENCODER], 0,
        enc);

  return enc;
}

static GstCaps *
request_key (GstElement * srtpdec, guint ssrc, GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv = stream->priv;
  GstCaps *caps;

  GST_DEBUG ("request key %08x", ssrc);

  g_mutex_lock (&priv->lock);
  if ((caps = g_hash_table_lookup (priv->keys, GINT_TO_POINTER (ssrc))))
    gst_caps_ref (caps);
  g_mutex_unlock (&priv->lock);

  return caps;
}

static GstElement *
request_rtp_rtcp_decoder (GstElement * rtpbin, guint session,
    GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv = stream->priv;

  if (priv->idx != session)
    return NULL;

  if (priv->srtpdec == NULL) {
    gchar *name;

    name = g_strdup_printf ("srtpdec_%u", session);
    priv->srtpdec = gst_element_factory_make ("srtpdec", name);
    g_free (name);

    g_signal_connect (priv->srtpdec, "request-key",
        (GCallback) request_key, stream);
  }
  return gst_object_ref (priv->srtpdec);
}

/**
 * gst_rtsp_stream_request_aux_sender:
 * @stream: a #GstRTSPStream
 * @sessid: the session id
 *
 * Creating a rtxsend bin
 *
 * Returns: (transfer full): a #GstElement.
 *
 * Since: 1.6
 */
GstElement *
gst_rtsp_stream_request_aux_sender (GstRTSPStream * stream, guint sessid)
{
  GstElement *bin;
  GstPad *pad;
  GstStructure *pt_map;
  gchar *name;
  guint pt, rtx_pt;
  gchar *pt_s;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);

  pt = gst_rtsp_stream_get_pt (stream);
  pt_s = g_strdup_printf ("%u", pt);
  rtx_pt = stream->priv->rtx_pt;

  GST_INFO ("creating rtxsend with pt %u to %u", pt, rtx_pt);

  bin = gst_bin_new (NULL);
  stream->priv->rtxsend = gst_element_factory_make ("rtprtxsend", NULL);
  pt_map = gst_structure_new ("application/x-rtp-pt-map",
      pt_s, G_TYPE_UINT, rtx_pt, NULL);
  g_object_set (stream->priv->rtxsend, "payload-type-map", pt_map,
      "max-size-time", GST_TIME_AS_MSECONDS (stream->priv->rtx_time), NULL);
  g_free (pt_s);
  gst_structure_free (pt_map);
  gst_bin_add (GST_BIN (bin), gst_object_ref (stream->priv->rtxsend));

  pad = gst_element_get_static_pad (stream->priv->rtxsend, "src");
  name = g_strdup_printf ("src_%u", sessid);
  gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
  g_free (name);
  gst_object_unref (pad);

  pad = gst_element_get_static_pad (stream->priv->rtxsend, "sink");
  name = g_strdup_printf ("sink_%u", sessid);
  gst_element_add_pad (bin, gst_ghost_pad_new (name, pad));
  g_free (name);
  gst_object_unref (pad);

  return bin;
}

/**
 * gst_rtsp_stream_set_pt_map:
 * @stream: a #GstRTSPStream
 * @pt: the pt
 * @caps: a #GstCaps
 *
 * Configure a pt map between @pt and @caps.
 */
void
gst_rtsp_stream_set_pt_map (GstRTSPStream * stream, guint pt, GstCaps * caps)
{
  GstRTSPStreamPrivate *priv = stream->priv;

  g_mutex_lock (&priv->lock);
  g_hash_table_insert (priv->ptmap, GINT_TO_POINTER (pt), gst_caps_ref (caps));
  g_mutex_unlock (&priv->lock);
}

/**
 * gst_rtsp_stream_set_publish_clock_mode:
 * @stream: a #GstRTSPStream
 * @mode: the clock publish mode
 *
 * Sets if and how the stream clock should be published according to RFC7273.
 *
 * Since: 1.8
 */
void
gst_rtsp_stream_set_publish_clock_mode (GstRTSPStream * stream,
    GstRTSPPublishClockMode mode)
{
  GstRTSPStreamPrivate *priv;

  priv = stream->priv;
  g_mutex_lock (&priv->lock);
  priv->publish_clock_mode = mode;
  g_mutex_unlock (&priv->lock);
}

/**
 * gst_rtsp_stream_get_publish_clock_mode:
 * @stream: a #GstRTSPStream
 *
 * Gets if and how the stream clock should be published according to RFC7273.
 *
 * Returns: The GstRTSPPublishClockMode
 *
 * Since: 1.8
 */
GstRTSPPublishClockMode
gst_rtsp_stream_get_publish_clock_mode (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  GstRTSPPublishClockMode ret;

  priv = stream->priv;
  g_mutex_lock (&priv->lock);
  ret = priv->publish_clock_mode;
  g_mutex_unlock (&priv->lock);

  return ret;
}

static GstCaps *
request_pt_map (GstElement * rtpbin, guint session, guint pt,
    GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv = stream->priv;
  GstCaps *caps = NULL;

  g_mutex_lock (&priv->lock);

  if (priv->idx == session) {
    caps = g_hash_table_lookup (priv->ptmap, GINT_TO_POINTER (pt));
    if (caps) {
      GST_DEBUG ("Stream %p, pt %u: caps %" GST_PTR_FORMAT, stream, pt, caps);
      gst_caps_ref (caps);
    } else {
      GST_DEBUG ("Stream %p, pt %u: no caps", stream, pt);
    }
  }

  g_mutex_unlock (&priv->lock);

  return caps;
}

static void
pad_added (GstElement * rtpbin, GstPad * pad, GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv = stream->priv;
  gchar *name;
  GstPadLinkReturn ret;
  guint sessid;

  GST_DEBUG ("Stream %p added pad %s:%s for pad %s:%s", stream,
      GST_DEBUG_PAD_NAME (pad), GST_DEBUG_PAD_NAME (priv->sinkpad));

  name = gst_pad_get_name (pad);
  if (sscanf (name, "recv_rtp_src_%u", &sessid) != 1) {
    g_free (name);
    return;
  }
  g_free (name);

  if (priv->idx != sessid)
    return;

  if (gst_pad_is_linked (priv->sinkpad)) {
    GST_WARNING ("Stream %p: Pad %s:%s is linked already", stream,
        GST_DEBUG_PAD_NAME (priv->sinkpad));
    return;
  }

  /* link the RTP pad to the session manager, it should not really fail unless
   * this is not really an RTP pad */
  ret = gst_pad_link (pad, priv->sinkpad);
  if (ret != GST_PAD_LINK_OK)
    goto link_failed;
  priv->recv_rtp_src = gst_object_ref (pad);

  return;

/* ERRORS */
link_failed:
  {
    GST_ERROR ("Stream %p: Failed to link pads %s:%s and %s:%s", stream,
        GST_DEBUG_PAD_NAME (pad), GST_DEBUG_PAD_NAME (priv->sinkpad));
  }
}

static void
on_npt_stop (GstElement * rtpbin, guint session, guint ssrc,
    GstRTSPStream * stream)
{
  /* TODO: What to do here other than this? */
  GST_DEBUG ("Stream %p: Got EOS", stream);
  gst_pad_send_event (stream->priv->sinkpad, gst_event_new_eos ());
}

typedef struct _ProbeData ProbeData;

struct _ProbeData
{
  GstRTSPStream *stream;
  /* existing sink, already linked to tee */
  GstElement *sink1;
  /* new sink, about to be linked */
  GstElement *sink2;
  /* new queue element, that will be linked to tee and sink1 */
  GstElement **queue1;
  /* new queue element, that will be linked to tee and sink2 */
  GstElement **queue2;
  GstPad *sink_pad;
  GstPad *tee_pad;
  guint index;
};

static void
free_cb_data (gpointer user_data)
{
  ProbeData *data = user_data;

  gst_object_unref (data->stream);
  gst_object_unref (data->sink1);
  gst_object_unref (data->sink2);
  gst_object_unref (data->sink_pad);
  gst_object_unref (data->tee_pad);
  g_free (data);
}


static void
create_and_plug_queue_to_unlinked_stream (GstRTSPStream * stream,
    GstElement * tee, GstElement * sink, GstElement ** queue)
{
  GstRTSPStreamPrivate *priv = stream->priv;
  GstPad *tee_pad;
  GstPad *queue_pad;
  GstPad *sink_pad;

  /* create queue for the new stream */
  *queue = gst_element_factory_make ("queue", NULL);
  g_object_set (*queue, "max-size-buffers", 1, "max-size-bytes", 0,
      "max-size-time", G_GINT64_CONSTANT (0), NULL);
  gst_bin_add (priv->joined_bin, *queue);

  /* link tee to queue */
  tee_pad = gst_element_get_request_pad (tee, "src_%u");
  queue_pad = gst_element_get_static_pad (*queue, "sink");
  gst_pad_link (tee_pad, queue_pad);
  gst_object_unref (queue_pad);
  gst_object_unref (tee_pad);

  /* link queue to sink */
  queue_pad = gst_element_get_static_pad (*queue, "src");
  sink_pad = gst_element_get_static_pad (sink, "sink");
  gst_pad_link (queue_pad, sink_pad);
  gst_object_unref (queue_pad);
  gst_object_unref (sink_pad);

  gst_element_sync_state_with_parent (sink);
  gst_element_sync_state_with_parent (*queue);
}

static GstPadProbeReturn
create_and_plug_queue_to_linked_stream_probe_cb (GstPad * inpad,
    GstPadProbeInfo * info, gpointer user_data)
{
  GstRTSPStreamPrivate *priv;
  ProbeData *data = user_data;
  GstRTSPStream *stream;
  GstElement **queue1;
  GstElement **queue2;
  GstPad *sink_pad;
  GstPad *tee_pad;
  GstPad *queue_pad;
  guint index;

  stream = data->stream;
  priv = stream->priv;
  queue1 = data->queue1;
  queue2 = data->queue2;
  sink_pad = data->sink_pad;
  tee_pad = data->tee_pad;
  index = data->index;

  /* unlink tee and the existing sink:
   *   .-----.    .---------.
   *   | tee |    |  sink1  |
   * sink   src->sink       |
   *   '-----'    '---------'
   */
  g_assert (gst_pad_unlink (tee_pad, sink_pad));

  /* add queue to the already existing stream */
  *queue1 = gst_element_factory_make ("queue", NULL);
  g_object_set (*queue1, "max-size-buffers", 1, "max-size-bytes", 0,
      "max-size-time", G_GINT64_CONSTANT (0), NULL);
  gst_bin_add (priv->joined_bin, *queue1);

  /* link tee, queue and sink:
   *   .-----.    .---------.    .---------.
   *   | tee |    |  queue1 |    | sink1   |
   * sink   src->sink      src->sink       |
   *   '-----'    '---------'    '---------'
   */
  queue_pad = gst_element_get_static_pad (*queue1, "sink");
  gst_pad_link (tee_pad, queue_pad);
  gst_object_unref (queue_pad);
  queue_pad = gst_element_get_static_pad (*queue1, "src");
  gst_pad_link (queue_pad, sink_pad);
  gst_object_unref (queue_pad);

  gst_element_sync_state_with_parent (*queue1);

  /* create queue and link it to tee and the new sink */
  create_and_plug_queue_to_unlinked_stream (stream,
      priv->tee[index], data->sink2, queue2);

  /* the final stream:
   *
   *    .-----.    .---------.    .---------.
   *    | tee |    |  queue1 |    | sink1   |
   *  sink   src->sink      src->sink       |
   *    |     |    '---------'    '---------'
   *    |     |    .---------.    .---------.
   *    |     |    |  queue2 |    | sink2   |
   *    |    src->sink      src->sink       |
   *    '-----'    '---------'    '---------'
   */

  return GST_PAD_PROBE_REMOVE;
}

static void
create_and_plug_queue_to_linked_stream (GstRTSPStream * stream,
    GstElement * sink1, GstElement * sink2, guint index, GstElement ** queue1,
    GstElement ** queue2)
{
  ProbeData *data;

  data = g_new0 (ProbeData, 1);
  data->stream = gst_object_ref (stream);
  data->sink1 = gst_object_ref (sink1);
  data->sink2 = gst_object_ref (sink2);
  data->queue1 = queue1;
  data->queue2 = queue2;
  data->index = index;

  data->sink_pad = gst_element_get_static_pad (sink1, "sink");
  g_assert (data->sink_pad);
  data->tee_pad = gst_pad_get_peer (data->sink_pad);
  g_assert (data->tee_pad);

  gst_pad_add_probe (data->tee_pad, GST_PAD_PROBE_TYPE_IDLE,
      create_and_plug_queue_to_linked_stream_probe_cb, data, free_cb_data);
}

static void
plug_udp_sink (GstRTSPStream * stream, GstElement * sink_to_plug,
    GstElement ** queue_to_plug, guint index, gboolean is_mcast)
{
  GstRTSPStreamPrivate *priv = stream->priv;
  GstElement *existing_sink;

  if (is_mcast)
    existing_sink = priv->udpsink[index];
  else
    existing_sink = priv->mcast_udpsink[index];

  GST_DEBUG_OBJECT (stream, "plug %s sink", is_mcast ? "mcast" : "udp");

  /* add sink to the bin */
  gst_bin_add (priv->joined_bin, sink_to_plug);

  if (priv->appsink[index] && existing_sink) {

    /* queues are already added for the existing stream, add one for
       the newly added udp stream */
    create_and_plug_queue_to_unlinked_stream (stream, priv->tee[index],
        sink_to_plug, queue_to_plug);

  } else if (priv->appsink[index] || existing_sink) {
    GstElement **queue;
    GstElement *element;

    /* add queue to the already existing stream plus the newly created udp
       stream */
    if (priv->appsink[index]) {
      element = priv->appsink[index];
      queue = &priv->appqueue[index];
    } else {
      element = existing_sink;
      if (is_mcast)
        queue = &priv->udpqueue[index];
      else
        queue = &priv->mcast_udpqueue[index];
    }

    create_and_plug_queue_to_linked_stream (stream, element, sink_to_plug,
        index, queue, queue_to_plug);

  } else {
    GstPad *tee_pad;
    GstPad *sink_pad;

    GST_DEBUG_OBJECT (stream, "creating first stream");

    /* no need to add queues */
    tee_pad = gst_element_get_request_pad (priv->tee[index], "src_%u");
    sink_pad = gst_element_get_static_pad (sink_to_plug, "sink");
    gst_pad_link (tee_pad, sink_pad);
    gst_object_unref (tee_pad);
    gst_object_unref (sink_pad);
  }

  gst_element_sync_state_with_parent (sink_to_plug);
}

static void
plug_tcp_sink (GstRTSPStream * stream, guint index)
{
  GstRTSPStreamPrivate *priv = stream->priv;

  GST_DEBUG_OBJECT (stream, "plug tcp sink");

  /* add sink to the bin */
  gst_bin_add (priv->joined_bin, priv->appsink[index]);

  if (priv->mcast_udpsink[index] && priv->udpsink[index]) {

    /* queues are already added for the existing stream, add one for
       the newly added tcp stream */
    create_and_plug_queue_to_unlinked_stream (stream,
        priv->tee[index], priv->appsink[index], &priv->appqueue[index]);

  } else if (priv->mcast_udpsink[index] || priv->udpsink[index]) {
    GstElement **queue;
    GstElement *element;

    /* add queue to the already existing stream plus the newly created tcp
       stream */
    if (priv->mcast_udpsink[index]) {
      element = priv->mcast_udpsink[index];
      queue = &priv->mcast_udpqueue[index];
    } else {
      element = priv->udpsink[index];
      queue = &priv->udpqueue[index];
    }

    create_and_plug_queue_to_linked_stream (stream, element,
        priv->appsink[index], index, queue, &priv->appqueue[index]);

  } else {
    GstPad *tee_pad;
    GstPad *sink_pad;

    /* no need to add queues */
    tee_pad = gst_element_get_request_pad (priv->tee[index], "src_%u");
    sink_pad = gst_element_get_static_pad (priv->appsink[index], "sink");
    gst_pad_link (tee_pad, sink_pad);
    gst_object_unref (tee_pad);
    gst_object_unref (sink_pad);
  }

  gst_element_sync_state_with_parent (priv->appsink[index]);
}

static void
plug_sink (GstRTSPStream * stream, const GstRTSPTransport * transport,
    guint index)
{
  GstRTSPStreamPrivate *priv;
  gboolean is_tcp, is_udp, is_mcast;
  priv = stream->priv;

  is_tcp = transport->lower_transport == GST_RTSP_LOWER_TRANS_TCP;
  is_udp = transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP;
  is_mcast = transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST;

  if (is_udp)
    plug_udp_sink (stream, priv->udpsink[index],
        &priv->udpqueue[index], index, FALSE);

  else if (is_mcast)
    plug_udp_sink (stream, priv->mcast_udpsink[index],
        &priv->mcast_udpqueue[index], index, TRUE);

  else if (is_tcp)
    plug_tcp_sink (stream, index);
}

/* must be called with lock */
static gboolean
create_sender_part (GstRTSPStream * stream, const GstRTSPTransport * transport)
{
  GstRTSPStreamPrivate *priv;
  GstPad *pad;
  GstBin *bin;
  gboolean is_tcp, is_udp, is_mcast;
  gint i;

  GST_DEBUG_OBJECT (stream, "create sender part");
  priv = stream->priv;
  bin = priv->joined_bin;

  is_tcp = transport->lower_transport == GST_RTSP_LOWER_TRANS_TCP;
  is_udp = transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP;
  is_mcast = transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST;

  GST_DEBUG_OBJECT (stream, "tcp: %d, udp: %d, mcast: %d", is_tcp, is_udp,
      is_mcast);

  if (is_udp && !priv->server_addr_v4 && !priv->server_addr_v6) {
    GST_WARNING_OBJECT (stream, "no sockets assigned for UDP");
    return FALSE;
  }

  if (is_mcast && !priv->mcast_addr_v4 && !priv->mcast_addr_v6) {
    GST_WARNING_OBJECT (stream, "no sockets assigned for UDP multicast");
    return FALSE;
  }

  for (i = 0; i < 2; i++) {
    gboolean link_tee = FALSE;
    /* For the sender we create this bit of pipeline for both
     * RTP and RTCP.
     * Initially there will be only one active transport for
     * the stream, so the pipeline will look like this:
     *
     * .--------.      .-----.    .---------.
     * | rtpbin |      | tee |    |  sink   |
     * |       send->sink   src->sink       |
     * '--------'      '-----'    '---------'
     *
     * For each new transport, the already existing branch will
     * be reconfigured by adding a queue element:
     *
     * .--------.      .-----.    .---------.    .---------.
     * | rtpbin |      | tee |    |  queue  |    | udpsink |
     * |       send->sink   src->sink      src->sink       |
     * '--------'      |     |    '---------'    '---------'
     *                 |     |    .---------.    .---------.
     *                 |     |    |  queue  |    | udpsink |
     *                 |    src->sink      src->sink       |
     *                 |     |    '---------'    '---------'
     *                 |     |    .---------.    .---------.
     *                 |     |    |  queue  |    | appsink |
     *                 |    src->sink      src->sink       |
     *                 '-----'    '---------'    '---------'
     */

    /* Only link the RTP send src if we're going to send RTP, link
     * the RTCP send src always */
    if (!priv->srcpad && i == 0)
      continue;

    if (!priv->tee[i]) {
      /* make tee for RTP/RTCP */
      priv->tee[i] = gst_element_factory_make ("tee", NULL);
      gst_bin_add (bin, priv->tee[i]);
      link_tee = TRUE;
    }

    if (is_udp && !priv->udpsink[i]) {
      /* we create only one pair of udpsinks for IPv4 and IPv6 */
      create_and_configure_udpsink (stream, &priv->udpsink[i],
          priv->socket_v4[i], priv->socket_v6[i], FALSE, (i == 0));
      plug_sink (stream, transport, i);
    } else if (is_mcast && !priv->mcast_udpsink[i]) {
      /* we create only one pair of mcast-udpsinks for IPv4 and IPv6 */
      create_and_configure_udpsink (stream, &priv->mcast_udpsink[i],
          priv->mcast_socket_v4[i], priv->mcast_socket_v6[i], TRUE, (i == 0));
      plug_sink (stream, transport, i);
    } else if (is_tcp && !priv->appsink[i]) {
      /* make appsink */
      priv->appsink[i] = gst_element_factory_make ("appsink", NULL);
      g_object_set (priv->appsink[i], "emit-signals", FALSE, NULL);

      /* we need to set sync and preroll to FALSE for the sink to avoid
       * deadlock. This is only needed for sink sending RTCP data. */
      if (i == 1)
        g_object_set (priv->appsink[i], "async", FALSE, "sync", FALSE, NULL);

      gst_app_sink_set_callbacks (GST_APP_SINK_CAST (priv->appsink[i]),
          &sink_cb, stream, NULL);
      plug_sink (stream, transport, i);
    }

    if (link_tee) {
      /* and link to rtpbin send pad */
      gst_element_sync_state_with_parent (priv->tee[i]);
      pad = gst_element_get_static_pad (priv->tee[i], "sink");
      gst_pad_link (priv->send_src[i], pad);
      gst_object_unref (pad);
    }
  }

  return TRUE;
}

/* must be called with lock */
static void
plug_src (GstRTSPStream * stream, GstBin * bin, GstElement * src,
    GstElement * funnel)
{
  GstRTSPStreamPrivate *priv;
  GstPad *pad, *selpad;

  priv = stream->priv;

  if (priv->srcpad) {
    /* we set and keep these to playing so that they don't cause NO_PREROLL return
     * values. This is only relevant for PLAY pipelines */
    gst_element_set_state (src, GST_STATE_PLAYING);
    gst_element_set_locked_state (src, TRUE);
  }

  /* add src */
  gst_bin_add (bin, src);

  /* and link to the funnel */
  selpad = gst_element_get_request_pad (funnel, "sink_%u");
  pad = gst_element_get_static_pad (src, "src");
  gst_pad_link (pad, selpad);
  gst_object_unref (pad);
  gst_object_unref (selpad);
}

/* must be called with lock */
static gboolean
create_receiver_part (GstRTSPStream * stream, const GstRTSPTransport *
    transport)
{
  GstRTSPStreamPrivate *priv;
  GstPad *pad;
  GstBin *bin;
  gboolean tcp;
  gboolean udp;
  gboolean mcast;
  gint i;

  GST_DEBUG_OBJECT (stream, "create receiver part");
  priv = stream->priv;
  bin = priv->joined_bin;

  tcp = transport->lower_transport == GST_RTSP_LOWER_TRANS_TCP;
  udp = transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP;
  mcast = transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST;

  for (i = 0; i < 2; i++) {
    /* For the receiver we create this bit of pipeline for both
     * RTP and RTCP. We receive RTP/RTCP on appsrc and udpsrc
     * and it is all funneled into the rtpbin receive pad.
     *
     *
     * .--------.     .--------.    .--------.
     * | udpsrc |     | funnel |    | rtpbin |
     * | RTP    src->sink      src->sink     |
     * '--------'     |        |    |        |
     * .--------.     |        |    |        |
     * | appsrc |     |        |    |        |
     * | RTP    src->sink      |    |        |
     * '--------'     '--------'    |        |
     *                              |        |
     * .--------.     .--------.    |        |
     * | udpsrc |     | funnel |    |        |
     * | RTCP   src->sink      src->sink     |
     * '--------'     |        |    '--------'
     * .--------.     |        |
     * | appsrc |     |        |
     * | RTCP   src->sink      |
     * '--------'     '--------'
     */

    if (!priv->sinkpad && i == 0) {
      /* Only connect recv RTP sink if we expect to receive RTP. Connect recv
       * RTCP sink always */
      continue;
    }

    /* make funnel for the RTP/RTCP receivers */
    priv->funnel[i] = gst_element_factory_make ("funnel", NULL);
    gst_bin_add (bin, priv->funnel[i]);

    pad = gst_element_get_static_pad (priv->funnel[i], "src");
    gst_pad_link (pad, priv->recv_sink[i]);
    gst_object_unref (pad);

    if (udp && !priv->udpsrc_v4[i] && priv->server_addr_v4) {
      GST_DEBUG_OBJECT (stream, "udp IPv4, create and configure udpsources");
      if (!create_and_configure_udpsource (&priv->udpsrc_v4[i],
              priv->socket_v4[i]))
        goto udpsrc_error;

      plug_src (stream, bin, priv->udpsrc_v4[i], priv->funnel[i]);
    }

    if (udp && !priv->udpsrc_v6[i] && priv->server_addr_v6) {
      GST_DEBUG_OBJECT (stream, "udp IPv6, create and configure udpsources");
      if (!create_and_configure_udpsource (&priv->udpsrc_v6[i],
              priv->socket_v6[i]))
        goto udpsrc_error;

      plug_src (stream, bin, priv->udpsrc_v6[i], priv->funnel[i]);
    }

    if (mcast && !priv->mcast_udpsrc_v4[i] && priv->mcast_addr_v4) {
      GST_DEBUG_OBJECT (stream, "mcast IPv4, create and configure udpsources");
      if (!create_and_configure_udpsource (&priv->mcast_udpsrc_v4[i],
              priv->mcast_socket_v4[i]))
        goto mcast_udpsrc_error;
      plug_src (stream, bin, priv->mcast_udpsrc_v4[i], priv->funnel[i]);
    }

    if (mcast && !priv->mcast_udpsrc_v6[i] && priv->mcast_addr_v6) {
      GST_DEBUG_OBJECT (stream, "mcast IPv6, create and configure udpsources");
      if (!create_and_configure_udpsource (&priv->mcast_udpsrc_v6[i],
              priv->mcast_socket_v6[i]))
        goto mcast_udpsrc_error;
      plug_src (stream, bin, priv->mcast_udpsrc_v6[i], priv->funnel[i]);
    }

    if (tcp && !priv->appsrc[i]) {
      /* make and add appsrc */
      priv->appsrc[i] = gst_element_factory_make ("appsrc", NULL);
      priv->appsrc_base_time[i] = -1;
      g_object_set (priv->appsrc[i], "format", GST_FORMAT_TIME, "is-live",
          TRUE, NULL);
      plug_src (stream, bin, priv->appsrc[i], priv->funnel[i]);
    }

    gst_element_sync_state_with_parent (priv->funnel[i]);
  }

  return TRUE;

mcast_udpsrc_error:
udpsrc_error:
  return FALSE;
}

static gboolean
check_mcast_part_for_transport (GstRTSPStream * stream,
    const GstRTSPTransport * tr)
{
  GstRTSPStreamPrivate *priv = stream->priv;
  GInetAddress *inetaddr;
  GSocketFamily family;
  GstRTSPAddress *mcast_addr;

  /* Check if it's a ipv4 or ipv6 transport */
  inetaddr = g_inet_address_new_from_string (tr->destination);
  family = g_inet_address_get_family (inetaddr);
  g_object_unref (inetaddr);

  /* Select fields corresponding to the family */
  if (family == G_SOCKET_FAMILY_IPV4) {
    mcast_addr = priv->mcast_addr_v4;
  } else {
    mcast_addr = priv->mcast_addr_v6;
  }

  /* We support only one mcast group per family, make sure this transport
   * matches it. */
  if (!mcast_addr)
    goto no_addr;

  if (g_ascii_strcasecmp (tr->destination, mcast_addr->address) != 0 ||
      tr->port.min != mcast_addr->port ||
      tr->port.max != mcast_addr->port + mcast_addr->n_ports - 1 ||
      tr->ttl != mcast_addr->ttl)
    goto wrong_addr;

  return TRUE;

no_addr:
  {
    GST_WARNING_OBJECT (stream, "Adding mcast transport, but no mcast address "
        "has been reserved");
    return FALSE;
  }
wrong_addr:
  {
    GST_WARNING_OBJECT (stream, "Adding mcast transport, but it doesn't match "
        "the reserved address");
    return FALSE;
  }
}

/**
 * gst_rtsp_stream_join_bin:
 * @stream: a #GstRTSPStream
 * @bin: (transfer none): a #GstBin to join
 * @rtpbin: (transfer none): a rtpbin element in @bin
 * @state: the target state of the new elements
 *
 * Join the #GstBin @bin that contains the element @rtpbin.
 *
 * @stream will link to @rtpbin, which must be inside @bin. The elements
 * added to @bin will be set to the state given in @state.
 *
 * Returns: %TRUE on success.
 */
gboolean
gst_rtsp_stream_join_bin (GstRTSPStream * stream, GstBin * bin,
    GstElement * rtpbin, GstState state)
{
  GstRTSPStreamPrivate *priv;
  guint idx;
  gchar *name;
  GstPadLinkReturn ret;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
  g_return_val_if_fail (GST_IS_BIN (bin), FALSE);
  g_return_val_if_fail (GST_IS_ELEMENT (rtpbin), FALSE);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  if (priv->joined_bin != NULL)
    goto was_joined;

  /* create a session with the same index as the stream */
  idx = priv->idx;

  GST_INFO ("stream %p joining bin as session %u", stream, idx);

  if (priv->profiles & GST_RTSP_PROFILE_SAVP
      || priv->profiles & GST_RTSP_PROFILE_SAVPF) {
    /* For SRTP */
    g_signal_connect (rtpbin, "request-rtp-encoder",
        (GCallback) request_rtp_encoder, stream);
    g_signal_connect (rtpbin, "request-rtcp-encoder",
        (GCallback) request_rtcp_encoder, stream);
    g_signal_connect (rtpbin, "request-rtp-decoder",
        (GCallback) request_rtp_rtcp_decoder, stream);
    g_signal_connect (rtpbin, "request-rtcp-decoder",
        (GCallback) request_rtp_rtcp_decoder, stream);
  }

  if (priv->sinkpad) {
    g_signal_connect (rtpbin, "request-pt-map",
        (GCallback) request_pt_map, stream);
  }

  /* get pads from the RTP session element for sending and receiving
   * RTP/RTCP*/
  if (priv->srcpad) {
    /* get a pad for sending RTP */
    name = g_strdup_printf ("send_rtp_sink_%u", idx);
    priv->send_rtp_sink = gst_element_get_request_pad (rtpbin, name);
    g_free (name);

    /* link the RTP pad to the session manager, it should not really fail unless
     * this is not really an RTP pad */
    ret = gst_pad_link (priv->srcpad, priv->send_rtp_sink);
    if (ret != GST_PAD_LINK_OK)
      goto link_failed;

    name = g_strdup_printf ("send_rtp_src_%u", idx);
    priv->send_src[0] = gst_element_get_static_pad (rtpbin, name);
    g_free (name);
  } else {
    /* RECORD case: need to connect our sinkpad from here */
    g_signal_connect (rtpbin, "pad-added", (GCallback) pad_added, stream);
    /* EOS */
    g_signal_connect (rtpbin, "on-npt-stop", (GCallback) on_npt_stop, stream);

    name = g_strdup_printf ("recv_rtp_sink_%u", idx);
    priv->recv_sink[0] = gst_element_get_request_pad (rtpbin, name);
    g_free (name);
  }

  name = g_strdup_printf ("send_rtcp_src_%u", idx);
  priv->send_src[1] = gst_element_get_request_pad (rtpbin, name);
  g_free (name);
  name = g_strdup_printf ("recv_rtcp_sink_%u", idx);
  priv->recv_sink[1] = gst_element_get_request_pad (rtpbin, name);
  g_free (name);

  /* get the session */
  g_signal_emit_by_name (rtpbin, "get-internal-session", idx, &priv->session);

  g_signal_connect (priv->session, "on-new-ssrc", (GCallback) on_new_ssrc,
      stream);
  g_signal_connect (priv->session, "on-ssrc-sdes", (GCallback) on_ssrc_sdes,
      stream);
  g_signal_connect (priv->session, "on-ssrc-active",
      (GCallback) on_ssrc_active, stream);
  g_signal_connect (priv->session, "on-bye-ssrc", (GCallback) on_bye_ssrc,
      stream);
  g_signal_connect (priv->session, "on-bye-timeout",
      (GCallback) on_bye_timeout, stream);
  g_signal_connect (priv->session, "on-timeout", (GCallback) on_timeout,
      stream);

  /* signal for sender ssrc */
  g_signal_connect (priv->session, "on-new-sender-ssrc",
      (GCallback) on_new_sender_ssrc, stream);
  g_signal_connect (priv->session, "on-sender-ssrc-active",
      (GCallback) on_sender_ssrc_active, stream);

  if (priv->srcpad) {
    /* be notified of caps changes */
    priv->caps_sig = g_signal_connect (priv->send_src[0], "notify::caps",
        (GCallback) caps_notify, stream);
    priv->caps = gst_pad_get_current_caps (priv->send_src[0]);
  }

  priv->joined_bin = bin;
  GST_DEBUG_OBJECT (stream, "successfully joined bin");
  g_mutex_unlock (&priv->lock);

  return TRUE;

  /* ERRORS */
was_joined:
  {
    g_mutex_unlock (&priv->lock);
    return TRUE;
  }
link_failed:
  {
    GST_WARNING ("failed to link stream %u", idx);
    gst_object_unref (priv->send_rtp_sink);
    priv->send_rtp_sink = NULL;
    g_mutex_unlock (&priv->lock);
    return FALSE;
  }
}

static void
clear_element (GstBin * bin, GstElement ** elementptr)
{
  if (*elementptr) {
    gst_element_set_locked_state (*elementptr, FALSE);
    gst_element_set_state (*elementptr, GST_STATE_NULL);
    if (GST_ELEMENT_PARENT (*elementptr))
      gst_bin_remove (bin, *elementptr);
    else
      gst_object_unref (*elementptr);
    *elementptr = NULL;
  }
}

/**
 * gst_rtsp_stream_leave_bin:
 * @stream: a #GstRTSPStream
 * @bin: (transfer none): a #GstBin
 * @rtpbin: (transfer none): a rtpbin #GstElement
 *
 * Remove the elements of @stream from @bin.
 *
 * Return: %TRUE on success.
 */
gboolean
gst_rtsp_stream_leave_bin (GstRTSPStream * stream, GstBin * bin,
    GstElement * rtpbin)
{
  GstRTSPStreamPrivate *priv;
  gint i;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
  g_return_val_if_fail (GST_IS_BIN (bin), FALSE);
  g_return_val_if_fail (GST_IS_ELEMENT (rtpbin), FALSE);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  if (priv->joined_bin == NULL)
    goto was_not_joined;
  if (priv->joined_bin != bin)
    goto wrong_bin;

  priv->joined_bin = NULL;

  /* all transports must be removed by now */
  if (priv->transports != NULL)
    goto transports_not_removed;

  clear_tr_cache (priv, TRUE);
  clear_tr_cache (priv, FALSE);

  GST_INFO ("stream %p leaving bin", stream);

  if (priv->srcpad) {
    gst_pad_unlink (priv->srcpad, priv->send_rtp_sink);

    g_signal_handler_disconnect (priv->send_src[0], priv->caps_sig);
    gst_element_release_request_pad (rtpbin, priv->send_rtp_sink);
    gst_object_unref (priv->send_rtp_sink);
    priv->send_rtp_sink = NULL;
  } else if (priv->recv_rtp_src) {
    gst_pad_unlink (priv->recv_rtp_src, priv->sinkpad);
    gst_object_unref (priv->recv_rtp_src);
    priv->recv_rtp_src = NULL;
  }

  for (i = 0; i < 2; i++) {
    clear_element (bin, &priv->udpsrc_v4[i]);
    clear_element (bin, &priv->udpsrc_v6[i]);
    clear_element (bin, &priv->udpqueue[i]);
    clear_element (bin, &priv->udpsink[i]);

    clear_element (bin, &priv->mcast_udpsrc_v4[i]);
    clear_element (bin, &priv->mcast_udpsrc_v6[i]);
    clear_element (bin, &priv->mcast_udpqueue[i]);
    clear_element (bin, &priv->mcast_udpsink[i]);

    clear_element (bin, &priv->appsrc[i]);
    clear_element (bin, &priv->appqueue[i]);
    clear_element (bin, &priv->appsink[i]);

    clear_element (bin, &priv->tee[i]);
    clear_element (bin, &priv->funnel[i]);

    if (priv->sinkpad || i == 1) {
      gst_element_release_request_pad (rtpbin, priv->recv_sink[i]);
      gst_object_unref (priv->recv_sink[i]);
      priv->recv_sink[i] = NULL;
    }
  }

  if (priv->srcpad) {
    gst_object_unref (priv->send_src[0]);
    priv->send_src[0] = NULL;
  }

  gst_element_release_request_pad (rtpbin, priv->send_src[1]);
  gst_object_unref (priv->send_src[1]);
  priv->send_src[1] = NULL;

  g_object_unref (priv->session);
  priv->session = NULL;
  if (priv->caps)
    gst_caps_unref (priv->caps);
  priv->caps = NULL;

  if (priv->srtpenc)
    gst_object_unref (priv->srtpenc);
  if (priv->srtpdec)
    gst_object_unref (priv->srtpdec);

  if (priv->mcast_addr_v4)
    gst_rtsp_address_free (priv->mcast_addr_v4);
  priv->mcast_addr_v4 = NULL;
  if (priv->mcast_addr_v6)
    gst_rtsp_address_free (priv->mcast_addr_v6);
  priv->mcast_addr_v6 = NULL;
  if (priv->server_addr_v4)
    gst_rtsp_address_free (priv->server_addr_v4);
  priv->server_addr_v4 = NULL;
  if (priv->server_addr_v6)
    gst_rtsp_address_free (priv->server_addr_v6);
  priv->server_addr_v6 = NULL;

  g_mutex_unlock (&priv->lock);

  return TRUE;

was_not_joined:
  {
    g_mutex_unlock (&priv->lock);
    return TRUE;
  }
transports_not_removed:
  {
    GST_ERROR_OBJECT (stream, "can't leave bin (transports not removed)");
    g_mutex_unlock (&priv->lock);
    return FALSE;
  }
wrong_bin:
  {
    GST_ERROR_OBJECT (stream, "leaving the wrong bin");
    g_mutex_unlock (&priv->lock);
    return FALSE;
  }
}

/**
 * gst_rtsp_stream_get_joined_bin:
 * @stream: a #GstRTSPStream
 *
 * Get the previous joined bin with gst_rtsp_stream_join_bin() or NULL.
 *
 * Return: (transfer full): the joined bin or NULL.
 */
GstBin *
gst_rtsp_stream_get_joined_bin (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  GstBin *bin = NULL;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  bin = priv->joined_bin ? gst_object_ref (priv->joined_bin) : NULL;
  g_mutex_unlock (&priv->lock);

  return bin;
}

/**
 * gst_rtsp_stream_get_rtpinfo:
 * @stream: a #GstRTSPStream
 * @rtptime: (allow-none): result RTP timestamp
 * @seq: (allow-none): result RTP seqnum
 * @clock_rate: (allow-none): the clock rate
 * @running_time: result running-time
 *
 * Retrieve the current rtptime, seq and running-time. This is used to
 * construct a RTPInfo reply header.
 *
 * Returns: %TRUE when rtptime, seq and running-time could be determined.
 */
gboolean
gst_rtsp_stream_get_rtpinfo (GstRTSPStream * stream,
    guint * rtptime, guint * seq, guint * clock_rate,
    GstClockTime * running_time)
{
  GstRTSPStreamPrivate *priv;
  GstStructure *stats;
  GObjectClass *payobjclass;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);

  priv = stream->priv;

  payobjclass = G_OBJECT_GET_CLASS (priv->payloader);

  g_mutex_lock (&priv->lock);

  /* First try to extract the information from the last buffer on the sinks.
   * This will have a more accurate sequence number and timestamp, as between
   * the payloader and the sink there can be some queues
   */
  if (priv->udpsink[0] || priv->appsink[0]) {
    GstSample *last_sample;

    if (priv->udpsink[0])
      g_object_get (priv->udpsink[0], "last-sample", &last_sample, NULL);
    else
      g_object_get (priv->appsink[0], "last-sample", &last_sample, NULL);

    if (last_sample) {
      GstCaps *caps;
      GstBuffer *buffer;
      GstSegment *segment;
      GstStructure *s;
      GstRTPBuffer rtp_buffer = GST_RTP_BUFFER_INIT;

      caps = gst_sample_get_caps (last_sample);
      buffer = gst_sample_get_buffer (last_sample);
      segment = gst_sample_get_segment (last_sample);
      s = gst_caps_get_structure (caps, 0);

      if (gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp_buffer)) {
        guint ssrc_buf = gst_rtp_buffer_get_ssrc (&rtp_buffer);
        guint ssrc_stream = 0;
        if (gst_structure_has_field_typed (s, "ssrc", G_TYPE_UINT) &&
            gst_structure_get_uint (s, "ssrc", &ssrc_stream) &&
            ssrc_buf != ssrc_stream) {
          /* Skip buffers from auxiliary streams. */
          GST_DEBUG_OBJECT (stream,
              "not a buffer from the payloader, SSRC: %08x", ssrc_buf);

          gst_rtp_buffer_unmap (&rtp_buffer);
          gst_sample_unref (last_sample);
          goto stats;
        }

        if (seq) {
          *seq = gst_rtp_buffer_get_seq (&rtp_buffer);
        }

        if (rtptime) {
          *rtptime = gst_rtp_buffer_get_timestamp (&rtp_buffer);
        }

        gst_rtp_buffer_unmap (&rtp_buffer);

        if (running_time) {
          *running_time =
              gst_segment_to_running_time (segment, GST_FORMAT_TIME,
              GST_BUFFER_TIMESTAMP (buffer));
        }

        if (clock_rate) {
          gst_structure_get_int (s, "clock-rate", (gint *) clock_rate);

          if (*clock_rate == 0 && running_time)
            *running_time = GST_CLOCK_TIME_NONE;
        }
        gst_sample_unref (last_sample);

        goto done;
      } else {
        gst_sample_unref (last_sample);
      }
    }
  }

stats:
  if (g_object_class_find_property (payobjclass, "stats")) {
    g_object_get (priv->payloader, "stats", &stats, NULL);
    if (stats == NULL)
      goto no_stats;

    if (seq)
      gst_structure_get_uint (stats, "seqnum", seq);

    if (rtptime)
      gst_structure_get_uint (stats, "timestamp", rtptime);

    if (running_time)
      gst_structure_get_clock_time (stats, "running-time", running_time);

    if (clock_rate) {
      gst_structure_get_uint (stats, "clock-rate", clock_rate);
      if (*clock_rate == 0 && running_time)
        *running_time = GST_CLOCK_TIME_NONE;
    }
    gst_structure_free (stats);
  } else {
    if (!g_object_class_find_property (payobjclass, "seqnum") ||
        !g_object_class_find_property (payobjclass, "timestamp"))
      goto no_stats;

    if (seq)
      g_object_get (priv->payloader, "seqnum", seq, NULL);

    if (rtptime)
      g_object_get (priv->payloader, "timestamp", rtptime, NULL);

    if (running_time)
      *running_time = GST_CLOCK_TIME_NONE;
  }

done:
  g_mutex_unlock (&priv->lock);

  return TRUE;

  /* ERRORS */
no_stats:
  {
    GST_WARNING ("Could not get payloader stats");
    g_mutex_unlock (&priv->lock);
    return FALSE;
  }
}

/**
 * gst_rtsp_stream_get_caps:
 * @stream: a #GstRTSPStream
 *
 * Retrieve the current caps of @stream.
 *
 * Returns: (transfer full): the #GstCaps of @stream. use gst_caps_unref()
 * after usage.
 */
GstCaps *
gst_rtsp_stream_get_caps (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  GstCaps *result;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  if ((result = priv->caps))
    gst_caps_ref (result);
  g_mutex_unlock (&priv->lock);

  return result;
}

/**
 * gst_rtsp_stream_recv_rtp:
 * @stream: a #GstRTSPStream
 * @buffer: (transfer full): a #GstBuffer
 *
 * Handle an RTP buffer for the stream. This method is usually called when a
 * message has been received from a client using the TCP transport.
 *
 * This function takes ownership of @buffer.
 *
 * Returns: a GstFlowReturn.
 */
GstFlowReturn
gst_rtsp_stream_recv_rtp (GstRTSPStream * stream, GstBuffer * buffer)
{
  GstRTSPStreamPrivate *priv;
  GstFlowReturn ret;
  GstElement *element;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), GST_FLOW_ERROR);
  priv = stream->priv;
  g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);
  g_return_val_if_fail (priv->joined_bin != NULL, FALSE);

  g_mutex_lock (&priv->lock);
  if (priv->appsrc[0])
    element = gst_object_ref (priv->appsrc[0]);
  else
    element = NULL;
  g_mutex_unlock (&priv->lock);

  if (element) {
    if (priv->appsrc_base_time[0] == -1) {
      /* Take current running_time. This timestamp will be put on
       * the first buffer of each stream because we are a live source and so we
       * timestamp with the running_time. When we are dealing with TCP, we also
       * only timestamp the first buffer (using the DISCONT flag) because a server
       * typically bursts data, for which we don't want to compensate by speeding
       * up the media. The other timestamps will be interpollated from this one
       * using the RTP timestamps. */
      GST_OBJECT_LOCK (element);
      if (GST_ELEMENT_CLOCK (element)) {
        GstClockTime now;
        GstClockTime base_time;

        now = gst_clock_get_time (GST_ELEMENT_CLOCK (element));
        base_time = GST_ELEMENT_CAST (element)->base_time;

        priv->appsrc_base_time[0] = now - base_time;
        GST_BUFFER_TIMESTAMP (buffer) = priv->appsrc_base_time[0];
        GST_DEBUG ("stream %p: first buffer at time %" GST_TIME_FORMAT
            ", base %" GST_TIME_FORMAT, stream, GST_TIME_ARGS (now),
            GST_TIME_ARGS (base_time));
      }
      GST_OBJECT_UNLOCK (element);
    }

    ret = gst_app_src_push_buffer (GST_APP_SRC_CAST (element), buffer);
    gst_object_unref (element);
  } else {
    ret = GST_FLOW_OK;
  }
  return ret;
}

/**
 * gst_rtsp_stream_recv_rtcp:
 * @stream: a #GstRTSPStream
 * @buffer: (transfer full): a #GstBuffer
 *
 * Handle an RTCP buffer for the stream. This method is usually called when a
 * message has been received from a client using the TCP transport.
 *
 * This function takes ownership of @buffer.
 *
 * Returns: a GstFlowReturn.
 */
GstFlowReturn
gst_rtsp_stream_recv_rtcp (GstRTSPStream * stream, GstBuffer * buffer)
{
  GstRTSPStreamPrivate *priv;
  GstFlowReturn ret;
  GstElement *element;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), GST_FLOW_ERROR);
  priv = stream->priv;
  g_return_val_if_fail (GST_IS_BUFFER (buffer), GST_FLOW_ERROR);

  if (priv->joined_bin == NULL) {
    gst_buffer_unref (buffer);
    return GST_FLOW_NOT_LINKED;
  }
  g_mutex_lock (&priv->lock);
  if (priv->appsrc[1])
    element = gst_object_ref (priv->appsrc[1]);
  else
    element = NULL;
  g_mutex_unlock (&priv->lock);

  if (element) {
    if (priv->appsrc_base_time[1] == -1) {
      /* Take current running_time. This timestamp will be put on
       * the first buffer of each stream because we are a live source and so we
       * timestamp with the running_time. When we are dealing with TCP, we also
       * only timestamp the first buffer (using the DISCONT flag) because a server
       * typically bursts data, for which we don't want to compensate by speeding
       * up the media. The other timestamps will be interpollated from this one
       * using the RTP timestamps. */
      GST_OBJECT_LOCK (element);
      if (GST_ELEMENT_CLOCK (element)) {
        GstClockTime now;
        GstClockTime base_time;

        now = gst_clock_get_time (GST_ELEMENT_CLOCK (element));
        base_time = GST_ELEMENT_CAST (element)->base_time;

        priv->appsrc_base_time[1] = now - base_time;
        GST_BUFFER_TIMESTAMP (buffer) = priv->appsrc_base_time[1];
        GST_DEBUG ("stream %p: first buffer at time %" GST_TIME_FORMAT
            ", base %" GST_TIME_FORMAT, stream, GST_TIME_ARGS (now),
            GST_TIME_ARGS (base_time));
      }
      GST_OBJECT_UNLOCK (element);
    }

    ret = gst_app_src_push_buffer (GST_APP_SRC_CAST (element), buffer);
    gst_object_unref (element);
  } else {
    ret = GST_FLOW_OK;
    gst_buffer_unref (buffer);
  }
  return ret;
}

/* must be called with lock */
static gboolean
update_transport (GstRTSPStream * stream, GstRTSPStreamTransport * trans,
    gboolean add)
{
  GstRTSPStreamPrivate *priv = stream->priv;
  const GstRTSPTransport *tr;

  tr = gst_rtsp_stream_transport_get_transport (trans);

  switch (tr->lower_transport) {
    case GST_RTSP_LOWER_TRANS_UDP_MCAST:
    {
      if (add) {
        if (!check_mcast_part_for_transport (stream, tr))
          goto mcast_error;
        priv->transports = g_list_prepend (priv->transports, trans);
      } else {
        priv->transports = g_list_remove (priv->transports, trans);
      }
      break;
    }
    case GST_RTSP_LOWER_TRANS_UDP:
    {
      gchar *dest;
      gint min, max;
      guint ttl = 0;

      dest = tr->destination;
      if (tr->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST) {
        min = tr->port.min;
        max = tr->port.max;
        ttl = tr->ttl;
      } else if (priv->client_side) {
        /* In client side mode the 'destination' is the RTSP server, so send
         * to those ports */
        min = tr->server_port.min;
        max = tr->server_port.max;
      } else {
        min = tr->client_port.min;
        max = tr->client_port.max;
      }

      if (add) {
        if (ttl > 0) {
          GST_INFO ("setting ttl-mc %d", ttl);
          if (priv->udpsink[0])
            g_object_set (G_OBJECT (priv->udpsink[0]), "ttl-mc", ttl, NULL);
          g_object_set (G_OBJECT (priv->udpsink[1]), "ttl-mc", ttl, NULL);
        }
        GST_INFO ("adding %s:%d-%d", dest, min, max);
        if (priv->udpsink[0])
          g_signal_emit_by_name (priv->udpsink[0], "add", dest, min, NULL);
        g_signal_emit_by_name (priv->udpsink[1], "add", dest, max, NULL);
        priv->transports = g_list_prepend (priv->transports, trans);
      } else {
        GST_INFO ("removing %s:%d-%d", dest, min, max);
        if (priv->udpsink[0])
          g_signal_emit_by_name (priv->udpsink[0], "remove", dest, min, NULL);
        g_signal_emit_by_name (priv->udpsink[1], "remove", dest, max, NULL);
        priv->transports = g_list_remove (priv->transports, trans);
      }
      priv->transports_cookie++;
      break;
    }
    case GST_RTSP_LOWER_TRANS_TCP:
      if (add) {
        GST_INFO ("adding TCP %s", tr->destination);
        priv->transports = g_list_prepend (priv->transports, trans);
      } else {
        GST_INFO ("removing TCP %s", tr->destination);
        priv->transports = g_list_remove (priv->transports, trans);
      }
      priv->transports_cookie++;
      break;
    default:
      goto unknown_transport;
  }
  return TRUE;

  /* ERRORS */
unknown_transport:
  {
    GST_INFO ("Unknown transport %d", tr->lower_transport);
    return FALSE;
  }
mcast_error:
  {
    return FALSE;
  }
}


/**
 * gst_rtsp_stream_add_transport:
 * @stream: a #GstRTSPStream
 * @trans: (transfer none): a #GstRTSPStreamTransport
 *
 * Add the transport in @trans to @stream. The media of @stream will
 * then also be send to the values configured in @trans.
 *
 * @stream must be joined to a bin.
 *
 * @trans must contain a valid #GstRTSPTransport.
 *
 * Returns: %TRUE if @trans was added
 */
gboolean
gst_rtsp_stream_add_transport (GstRTSPStream * stream,
    GstRTSPStreamTransport * trans)
{
  GstRTSPStreamPrivate *priv;
  gboolean res;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
  priv = stream->priv;
  g_return_val_if_fail (GST_IS_RTSP_STREAM_TRANSPORT (trans), FALSE);
  g_return_val_if_fail (priv->joined_bin != NULL, FALSE);

  g_mutex_lock (&priv->lock);
  res = update_transport (stream, trans, TRUE);
  g_mutex_unlock (&priv->lock);

  return res;
}

/**
 * gst_rtsp_stream_remove_transport:
 * @stream: a #GstRTSPStream
 * @trans: (transfer none): a #GstRTSPStreamTransport
 *
 * Remove the transport in @trans from @stream. The media of @stream will
 * not be sent to the values configured in @trans.
 *
 * @stream must be joined to a bin.
 *
 * @trans must contain a valid #GstRTSPTransport.
 *
 * Returns: %TRUE if @trans was removed
 */
gboolean
gst_rtsp_stream_remove_transport (GstRTSPStream * stream,
    GstRTSPStreamTransport * trans)
{
  GstRTSPStreamPrivate *priv;
  gboolean res;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
  priv = stream->priv;
  g_return_val_if_fail (GST_IS_RTSP_STREAM_TRANSPORT (trans), FALSE);
  g_return_val_if_fail (priv->joined_bin != NULL, FALSE);

  g_mutex_lock (&priv->lock);
  res = update_transport (stream, trans, FALSE);
  g_mutex_unlock (&priv->lock);

  return res;
}

/**
 * gst_rtsp_stream_update_crypto:
 * @stream: a #GstRTSPStream
 * @ssrc: the SSRC
 * @crypto: (transfer none) (allow-none): a #GstCaps with crypto info
 *
 * Update the new crypto information for @ssrc in @stream. If information
 * for @ssrc did not exist, it will be added. If information
 * for @ssrc existed, it will be replaced. If @crypto is %NULL, it will
 * be removed from @stream.
 *
 * Returns: %TRUE if @crypto could be updated
 */
gboolean
gst_rtsp_stream_update_crypto (GstRTSPStream * stream,
    guint ssrc, GstCaps * crypto)
{
  GstRTSPStreamPrivate *priv;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);
  g_return_val_if_fail (crypto == NULL || GST_IS_CAPS (crypto), FALSE);

  priv = stream->priv;

  GST_DEBUG_OBJECT (stream, "update key for %08x", ssrc);

  g_mutex_lock (&priv->lock);
  if (crypto)
    g_hash_table_insert (priv->keys, GINT_TO_POINTER (ssrc),
        gst_caps_ref (crypto));
  else
    g_hash_table_remove (priv->keys, GINT_TO_POINTER (ssrc));
  g_mutex_unlock (&priv->lock);

  return TRUE;
}

/**
 * gst_rtsp_stream_get_rtp_socket:
 * @stream: a #GstRTSPStream
 * @family: the socket family
 *
 * Get the RTP socket from @stream for a @family.
 *
 * @stream must be joined to a bin.
 *
 * Returns: (transfer full) (nullable): the RTP socket or %NULL if no
 * socket could be allocated for @family. Unref after usage
 */
GSocket *
gst_rtsp_stream_get_rtp_socket (GstRTSPStream * stream, GSocketFamily family)
{
  GstRTSPStreamPrivate *priv = GST_RTSP_STREAM_GET_PRIVATE (stream);
  GSocket *socket;
  const gchar *name;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
  g_return_val_if_fail (family == G_SOCKET_FAMILY_IPV4 ||
      family == G_SOCKET_FAMILY_IPV6, NULL);
  g_return_val_if_fail (priv->udpsink[0], NULL);

  if (family == G_SOCKET_FAMILY_IPV6)
    name = "socket-v6";
  else
    name = "socket";

  g_object_get (priv->udpsink[0], name, &socket, NULL);

  return socket;
}

/**
 * gst_rtsp_stream_get_rtcp_socket:
 * @stream: a #GstRTSPStream
 * @family: the socket family
 *
 * Get the RTCP socket from @stream for a @family.
 *
 * @stream must be joined to a bin.
 *
 * Returns: (transfer full) (nullable): the RTCP socket or %NULL if no
 * socket could be allocated for @family. Unref after usage
 */
GSocket *
gst_rtsp_stream_get_rtcp_socket (GstRTSPStream * stream, GSocketFamily family)
{
  GstRTSPStreamPrivate *priv = GST_RTSP_STREAM_GET_PRIVATE (stream);
  GSocket *socket;
  const gchar *name;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
  g_return_val_if_fail (family == G_SOCKET_FAMILY_IPV4 ||
      family == G_SOCKET_FAMILY_IPV6, NULL);
  g_return_val_if_fail (priv->udpsink[1], NULL);

  if (family == G_SOCKET_FAMILY_IPV6)
    name = "socket-v6";
  else
    name = "socket";

  g_object_get (priv->udpsink[1], name, &socket, NULL);

  return socket;
}

/**
 * gst_rtsp_stream_get_rtp_multicast_socket:
 * @stream: a #GstRTSPStream
 * @family: the socket family
 *
 * Get the multicast RTP socket from @stream for a @family.
 *
 * Returns: (transfer full) (nullable): the multicast RTP socket or %NULL if no
 * socket could be allocated for @family. Unref after usage
 */
GSocket *
gst_rtsp_stream_get_rtp_multicast_socket (GstRTSPStream * stream,
    GSocketFamily family)
{
  GstRTSPStreamPrivate *priv = GST_RTSP_STREAM_GET_PRIVATE (stream);
  GSocket *socket;
  const gchar *name;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
  g_return_val_if_fail (family == G_SOCKET_FAMILY_IPV4 ||
      family == G_SOCKET_FAMILY_IPV6, NULL);
  g_return_val_if_fail (priv->mcast_udpsink[0], NULL);

  if (family == G_SOCKET_FAMILY_IPV6)
    name = "socket-v6";
  else
    name = "socket";

  g_object_get (priv->mcast_udpsink[0], name, &socket, NULL);

  return socket;
}

/**
 * gst_rtsp_stream_get_rtcp_multicast_socket:
 * @stream: a #GstRTSPStream
 * @family: the socket family
 *
 * Get the multicast RTCP socket from @stream for a @family.
 *
 * Returns: (transfer full) (nullable): the multicast RTCP socket or %NULL if no
 * socket could be allocated for @family. Unref after usage
 */
GSocket *
gst_rtsp_stream_get_rtcp_multicast_socket (GstRTSPStream * stream,
    GSocketFamily family)
{
  GstRTSPStreamPrivate *priv = GST_RTSP_STREAM_GET_PRIVATE (stream);
  GSocket *socket;
  const gchar *name;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);
  g_return_val_if_fail (family == G_SOCKET_FAMILY_IPV4 ||
      family == G_SOCKET_FAMILY_IPV6, NULL);
  g_return_val_if_fail (priv->mcast_udpsink[1], NULL);

  if (family == G_SOCKET_FAMILY_IPV6)
    name = "socket-v6";
  else
    name = "socket";

  g_object_get (priv->mcast_udpsink[1], name, &socket, NULL);

  return socket;
}

/**
 * gst_rtsp_stream_set_seqnum:
 * @stream: a #GstRTSPStream
 * @seqnum: a new sequence number
 *
 * Configure the sequence number in the payloader of @stream to @seqnum.
 */
void
gst_rtsp_stream_set_seqnum_offset (GstRTSPStream * stream, guint16 seqnum)
{
  GstRTSPStreamPrivate *priv;

  g_return_if_fail (GST_IS_RTSP_STREAM (stream));

  priv = stream->priv;

  g_object_set (G_OBJECT (priv->payloader), "seqnum-offset", seqnum, NULL);
}

/**
 * gst_rtsp_stream_get_seqnum:
 * @stream: a #GstRTSPStream
 *
 * Get the configured sequence number in the payloader of @stream.
 *
 * Returns: the sequence number of the payloader.
 */
guint16
gst_rtsp_stream_get_current_seqnum (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  guint seqnum;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), 0);

  priv = stream->priv;

  g_object_get (G_OBJECT (priv->payloader), "seqnum", &seqnum, NULL);

  return seqnum;
}

/**
 * gst_rtsp_stream_transport_filter:
 * @stream: a #GstRTSPStream
 * @func: (scope call) (allow-none): a callback
 * @user_data: (closure): user data passed to @func
 *
 * Call @func for each transport managed by @stream. The result value of @func
 * determines what happens to the transport. @func will be called with @stream
 * locked so no further actions on @stream can be performed from @func.
 *
 * If @func returns #GST_RTSP_FILTER_REMOVE, the transport will be removed from
 * @stream.
 *
 * If @func returns #GST_RTSP_FILTER_KEEP, the transport will remain in @stream.
 *
 * If @func returns #GST_RTSP_FILTER_REF, the transport will remain in @stream but
 * will also be added with an additional ref to the result #GList of this
 * function..
 *
 * When @func is %NULL, #GST_RTSP_FILTER_REF will be assumed for each transport.
 *
 * Returns: (element-type GstRTSPStreamTransport) (transfer full): a #GList with all
 * transports for which @func returned #GST_RTSP_FILTER_REF. After usage, each
 * element in the #GList should be unreffed before the list is freed.
 */
GList *
gst_rtsp_stream_transport_filter (GstRTSPStream * stream,
    GstRTSPStreamTransportFilterFunc func, gpointer user_data)
{
  GstRTSPStreamPrivate *priv;
  GList *result, *walk, *next;
  GHashTable *visited = NULL;
  guint cookie;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), NULL);

  priv = stream->priv;

  result = NULL;
  if (func)
    visited = g_hash_table_new_full (NULL, NULL, g_object_unref, NULL);

  g_mutex_lock (&priv->lock);
restart:
  cookie = priv->transports_cookie;
  for (walk = priv->transports; walk; walk = next) {
    GstRTSPStreamTransport *trans = walk->data;
    GstRTSPFilterResult res;
    gboolean changed;

    next = g_list_next (walk);

    if (func) {
      /* only visit each transport once */
      if (g_hash_table_contains (visited, trans))
        continue;

      g_hash_table_add (visited, g_object_ref (trans));
      g_mutex_unlock (&priv->lock);

      res = func (stream, trans, user_data);

      g_mutex_lock (&priv->lock);
    } else
      res = GST_RTSP_FILTER_REF;

    changed = (cookie != priv->transports_cookie);

    switch (res) {
      case GST_RTSP_FILTER_REMOVE:
        update_transport (stream, trans, FALSE);
        break;
      case GST_RTSP_FILTER_REF:
        result = g_list_prepend (result, g_object_ref (trans));
        break;
      case GST_RTSP_FILTER_KEEP:
      default:
        break;
    }
    if (changed)
      goto restart;
  }
  g_mutex_unlock (&priv->lock);

  if (func)
    g_hash_table_unref (visited);

  return result;
}

static GstPadProbeReturn
pad_blocking (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
{
  GstRTSPStreamPrivate *priv;
  GstRTSPStream *stream;
  GstBuffer *buffer = NULL;

  stream = user_data;
  priv = stream->priv;

  GST_DEBUG_OBJECT (pad, "now blocking");

  g_mutex_lock (&priv->lock);
  priv->blocking = TRUE;

  if ((info->type & GST_PAD_PROBE_TYPE_BUFFER)) {
    buffer = gst_pad_probe_info_get_buffer (info);
  } else if ((info->type & GST_PAD_PROBE_TYPE_BUFFER_LIST)) {
    GstBufferList *list = gst_pad_probe_info_get_buffer_list (info);
    buffer = gst_buffer_list_get (list, 0);
  } else {
    g_assert_not_reached ();
  }

  g_assert (buffer);
  priv->position = GST_BUFFER_TIMESTAMP (buffer);
  GST_DEBUG_OBJECT (stream, "buffer position: %" GST_TIME_FORMAT,
      GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)));
  g_mutex_unlock (&priv->lock);

  gst_element_post_message (priv->payloader,
      gst_message_new_element (GST_OBJECT_CAST (priv->payloader),
          gst_structure_new_empty ("GstRTSPStreamBlocking")));

  return GST_PAD_PROBE_OK;
}

static void
set_blocked (GstRTSPStream * stream, gboolean blocked)
{
  GstRTSPStreamPrivate *priv;
  int i;

  GST_DEBUG_OBJECT (stream, "blocked: %d", blocked);

  priv = stream->priv;

  if (blocked) {
    for (i = 0; i < 2; i++) {
      if (priv->blocked_id[i] != 0)
        continue;
      if (priv->send_src[i]) {
        priv->blocking = FALSE;
        priv->blocked_id[i] = gst_pad_add_probe (priv->send_src[i],
            GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER |
            GST_PAD_PROBE_TYPE_BUFFER_LIST, pad_blocking,
            g_object_ref (stream), g_object_unref);
      }
    }
  } else {
    for (i = 0; i < 2; i++) {
      if (priv->blocked_id[i] != 0) {
        gst_pad_remove_probe (priv->send_src[i], priv->blocked_id[i]);
        priv->blocked_id[i] = 0;
      }
    }
    priv->blocking = FALSE;
  }
}

/**
 * gst_rtsp_stream_set_blocked:
 * @stream: a #GstRTSPStream
 * @blocked: boolean indicating we should block or unblock
 *
 * Blocks or unblocks the dataflow on @stream.
 *
 * Returns: %TRUE on success
 */
gboolean
gst_rtsp_stream_set_blocked (GstRTSPStream * stream, gboolean blocked)
{
  GstRTSPStreamPrivate *priv;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);

  priv = stream->priv;
  g_mutex_lock (&priv->lock);
  set_blocked (stream, blocked);
  g_mutex_unlock (&priv->lock);

  return TRUE;
}

/**
 * gst_rtsp_stream_ublock_linked:
 * @stream: a #GstRTSPStream
 *
 * Unblocks the dataflow on @stream if it is linked.
 *
 * Returns: %TRUE on success
 */
gboolean
gst_rtsp_stream_unblock_linked (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);

  priv = stream->priv;
  g_mutex_lock (&priv->lock);
  if (priv->send_src[0] && gst_pad_is_linked (priv->send_src[0]))
    set_blocked (stream, FALSE);
  g_mutex_unlock (&priv->lock);

  return TRUE;
}

/**
 * gst_rtsp_stream_is_blocking:
 * @stream: a #GstRTSPStream
 *
 * Check if @stream is blocking on a #GstBuffer.
 *
 * Returns: %TRUE if @stream is blocking
 */
gboolean
gst_rtsp_stream_is_blocking (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  gboolean result;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  result = priv->blocking;
  g_mutex_unlock (&priv->lock);

  return result;
}

/**
 * gst_rtsp_stream_query_position:
 * @stream: a #GstRTSPStream
 * @position: current position of a #GstRTSPStream
 *
 * Query the position of the stream in %GST_FORMAT_TIME. This only considers
 * the RTP parts of the pipeline and not the RTCP parts.
 *
 * Returns: %TRUE if the position could be queried
 */
gboolean
gst_rtsp_stream_query_position (GstRTSPStream * stream, gint64 * position)
{
  GstRTSPStreamPrivate *priv;
  GstElement *sink;
  GstPad *pad = NULL;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);

  /* query position: if no sinks have been added yet,
   * we obtain the position from the pad otherwise we query the sinks */

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  /* depending on the transport type, it should query corresponding sink */
  if (priv->protocols & GST_RTSP_LOWER_TRANS_UDP)
    sink = priv->udpsink[0];
  else if (priv->protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST)
    sink = priv->mcast_udpsink[0];
  else
    sink = priv->appsink[0];

  if (sink) {
    gst_object_ref (sink);
  } else if (priv->send_src[0]) {
    pad = gst_object_ref (priv->send_src[0]);
  } else {
    g_mutex_unlock (&priv->lock);
    GST_WARNING_OBJECT (stream, "Couldn't obtain postion: erroneous pipeline");
    return FALSE;
  }
  g_mutex_unlock (&priv->lock);

  if (sink) {
    if (!gst_element_query_position (sink, GST_FORMAT_TIME, position)) {
      GST_WARNING_OBJECT (stream,
          "Couldn't obtain postion: position query failed");
      gst_object_unref (sink);
      return FALSE;
    }
    gst_object_unref (sink);
  } else if (pad) {
    GstEvent *event;
    const GstSegment *segment;

    event = gst_pad_get_sticky_event (pad, GST_EVENT_SEGMENT, 0);
    if (!event) {
      GST_WARNING_OBJECT (stream, "Couldn't obtain postion: no segment event");
      gst_object_unref (pad);
      return FALSE;
    }

    gst_event_parse_segment (event, &segment);
    if (segment->format != GST_FORMAT_TIME) {
      *position = -1;
    } else {
      g_mutex_lock (&priv->lock);
      *position = priv->position;
      g_mutex_unlock (&priv->lock);
      *position =
          gst_segment_to_stream_time (segment, GST_FORMAT_TIME, *position);
    }
    gst_event_unref (event);
    gst_object_unref (pad);
  }

  return TRUE;
}

/**
 * gst_rtsp_stream_query_stop:
 * @stream: a #GstRTSPStream
 * @stop: current stop of a #GstRTSPStream
 *
 * Query the stop of the stream in %GST_FORMAT_TIME. This only considers
 * the RTP parts of the pipeline and not the RTCP parts.
 *
 * Returns: %TRUE if the stop could be queried
 */
gboolean
gst_rtsp_stream_query_stop (GstRTSPStream * stream, gint64 * stop)
{
  GstRTSPStreamPrivate *priv;
  GstElement *sink;
  GstPad *pad = NULL;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);

  /* query stop position: if no sinks have been added yet,
   * we obtain the stop position from the pad otherwise we query the sinks */

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  /* depending on the transport type, it should query corresponding sink */
  if (priv->protocols & GST_RTSP_LOWER_TRANS_UDP)
    sink = priv->udpsink[0];
  else if (priv->protocols & GST_RTSP_LOWER_TRANS_UDP_MCAST)
    sink = priv->mcast_udpsink[0];
  else
    sink = priv->appsink[0];

  if (sink) {
    gst_object_ref (sink);
  } else if (priv->send_src[0]) {
    pad = gst_object_ref (priv->send_src[0]);
  } else {
    g_mutex_unlock (&priv->lock);
    GST_WARNING_OBJECT (stream, "Couldn't obtain stop: erroneous pipeline");
    return FALSE;
  }
  g_mutex_unlock (&priv->lock);

  if (sink) {
    GstQuery *query;
    GstFormat format;

    query = gst_query_new_segment (GST_FORMAT_TIME);
    if (!gst_element_query (sink, query)) {
      GST_WARNING_OBJECT (stream, "Couldn't obtain stop: element query failed");
      gst_query_unref (query);
      gst_object_unref (sink);
      return FALSE;
    }
    gst_query_parse_segment (query, NULL, &format, NULL, stop);
    if (format != GST_FORMAT_TIME)
      *stop = -1;
    gst_query_unref (query);
    gst_object_unref (sink);
  } else if (pad) {
    GstEvent *event;
    const GstSegment *segment;

    event = gst_pad_get_sticky_event (pad, GST_EVENT_SEGMENT, 0);
    if (!event) {
      GST_WARNING_OBJECT (stream, "Couldn't obtain stop: no segment event");
      gst_object_unref (pad);
      return FALSE;
    }
    gst_event_parse_segment (event, &segment);
    if (segment->format != GST_FORMAT_TIME) {
      *stop = -1;
    } else {
      *stop = segment->stop;
      if (*stop == -1)
        *stop = segment->duration;
      else
        *stop = gst_segment_to_stream_time (segment, GST_FORMAT_TIME, *stop);
    }
    gst_event_unref (event);
    gst_object_unref (pad);
  }

  return TRUE;
}

/**
 * gst_rtsp_stream_seekable:
 * @stream: a #GstRTSPStream
 *
 * Checks whether the individual @stream is seekable.
 *
 * Returns: %TRUE if @stream is seekable, else %FALSE.
 */
gboolean
gst_rtsp_stream_seekable (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  GstPad *pad = NULL;
  GstQuery *query = NULL;
  gboolean seekable = FALSE;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);

  /* query stop position: if no sinks have been added yet,
   * we obtain the stop position from the pad otherwise we query the sinks */

  priv = stream->priv;

  g_mutex_lock (&priv->lock);
  /* depending on the transport type, it should query corresponding sink */
  if (priv->srcpad) {
    pad = gst_object_ref (priv->srcpad);
  } else {
    g_mutex_unlock (&priv->lock);
    GST_WARNING_OBJECT (stream, "Pad not available, can't query seekability");
    goto beach;
  }
  g_mutex_unlock (&priv->lock);

  query = gst_query_new_seeking (GST_FORMAT_TIME);
  if (!gst_pad_query (pad, query)) {
    GST_WARNING_OBJECT (stream, "seeking query failed");
    goto beach;
  }
  gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);

beach:
  if (pad)
    gst_object_unref (pad);
  if (query)
    gst_query_unref (query);

  GST_DEBUG_OBJECT (stream, "Returning %d", seekable);

  return seekable;
}

/**
 * gst_rtsp_stream_complete_stream:
 * @stream: a #GstRTSPStream
 * @transport: a #GstRTSPTransport
 *
 * Add a receiver and sender part to the pipeline based on the transport from
 * SETUP.
 *
 * Returns: %TRUE if the stream has been sucessfully updated.
 */
gboolean
gst_rtsp_stream_complete_stream (GstRTSPStream * stream,
    const GstRTSPTransport * transport)
{
  GstRTSPStreamPrivate *priv;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);

  priv = stream->priv;
  GST_DEBUG_OBJECT (stream, "complete stream");

  g_mutex_lock (&priv->lock);

  if (!(priv->protocols & transport->lower_transport))
    goto unallowed_transport;

  if (!create_receiver_part (stream, transport))
    goto create_receiver_error;

  /* in the RECORD case, we only add RTCP sender part */
  if (!create_sender_part (stream, transport))
    goto create_sender_error;

  priv->is_complete = TRUE;
  g_mutex_unlock (&priv->lock);

  GST_DEBUG_OBJECT (stream, "pipeline sucsessfully updated");
  return TRUE;

create_receiver_error:
create_sender_error:
unallowed_transport:
  {
    g_mutex_unlock (&priv->lock);
    return FALSE;
  }
}

/**
 * gst_rtsp_stream_is_complete:
 * @stream: a #GstRTSPStream
 *
 * Checks whether the stream is complete, contains the receiver and the sender
 * parts. As the stream contains sink(s) element(s), it's possible to perform
 * seek operations on it.
 *
 * Returns: %TRUE if the stream contains at least one sink element.
 */
gboolean
gst_rtsp_stream_is_complete (GstRTSPStream * stream)
{
  GstRTSPStreamPrivate *priv;
  gboolean ret = FALSE;

  g_return_val_if_fail (GST_IS_RTSP_STREAM (stream), FALSE);

  priv = stream->priv;
  g_mutex_lock (&priv->lock);
  ret = priv->is_complete;
  g_mutex_unlock (&priv->lock);

  return ret;
}