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
// Copyright (C) 2016-2017 Sebastian Dröge <sebastian@centricular.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use gst_sys;
use miniobject::*;
use structure::*;
use GenericFormattedValue;
use GroupId;
use GstObjectExt;
use MessageType;
use Object;
use Seqnum;
use TagList;

use std::ffi::CStr;
use std::fmt;
use std::mem;
use std::ops::Deref;
use std::ptr;

use glib;
use glib::translate::{from_glib, from_glib_full, from_glib_none, mut_override, ToGlib, ToGlibPtr};
use glib::value::ToSendValue;
use glib::Cast;
use glib::IsA;

gst_define_mini_object_wrapper!(Message, MessageRef, gst_sys::GstMessage, [Debug,], || {
    gst_sys::gst_message_get_type()
});

impl MessageRef {
    pub fn get_src(&self) -> Option<Object> {
        unsafe { from_glib_none((*self.as_ptr()).src) }
    }

    pub fn get_seqnum(&self) -> Seqnum {
        unsafe { from_glib(gst_sys::gst_message_get_seqnum(self.as_mut_ptr())) }
    }

    pub fn get_structure(&self) -> Option<&StructureRef> {
        unsafe {
            let structure = gst_sys::gst_message_get_structure(self.as_mut_ptr());
            if structure.is_null() {
                None
            } else {
                Some(StructureRef::from_glib_borrow(structure))
            }
        }
    }

    pub fn view(&self) -> MessageView {
        let type_ = unsafe { (*self.as_ptr()).type_ };

        match type_ {
            gst_sys::GST_MESSAGE_EOS => MessageView::Eos(Eos(self)),
            gst_sys::GST_MESSAGE_ERROR => MessageView::Error(Error(self)),
            gst_sys::GST_MESSAGE_WARNING => MessageView::Warning(Warning(self)),
            gst_sys::GST_MESSAGE_INFO => MessageView::Info(Info(self)),
            gst_sys::GST_MESSAGE_TAG => MessageView::Tag(Tag(self)),
            gst_sys::GST_MESSAGE_BUFFERING => MessageView::Buffering(Buffering(self)),
            gst_sys::GST_MESSAGE_STATE_CHANGED => MessageView::StateChanged(StateChanged(self)),
            gst_sys::GST_MESSAGE_STATE_DIRTY => MessageView::StateDirty(StateDirty(self)),
            gst_sys::GST_MESSAGE_STEP_DONE => MessageView::StepDone(StepDone(self)),
            gst_sys::GST_MESSAGE_CLOCK_PROVIDE => MessageView::ClockProvide(ClockProvide(self)),
            gst_sys::GST_MESSAGE_CLOCK_LOST => MessageView::ClockLost(ClockLost(self)),
            gst_sys::GST_MESSAGE_NEW_CLOCK => MessageView::NewClock(NewClock(self)),
            gst_sys::GST_MESSAGE_STRUCTURE_CHANGE => {
                MessageView::StructureChange(StructureChange(self))
            }
            gst_sys::GST_MESSAGE_STREAM_STATUS => MessageView::StreamStatus(StreamStatus(self)),
            gst_sys::GST_MESSAGE_APPLICATION => MessageView::Application(Application(self)),
            gst_sys::GST_MESSAGE_ELEMENT => MessageView::Element(Element(self)),
            gst_sys::GST_MESSAGE_SEGMENT_START => MessageView::SegmentStart(SegmentStart(self)),
            gst_sys::GST_MESSAGE_SEGMENT_DONE => MessageView::SegmentDone(SegmentDone(self)),
            gst_sys::GST_MESSAGE_DURATION_CHANGED => {
                MessageView::DurationChanged(DurationChanged(self))
            }
            gst_sys::GST_MESSAGE_LATENCY => MessageView::Latency(Latency(self)),
            gst_sys::GST_MESSAGE_ASYNC_START => MessageView::AsyncStart(AsyncStart(self)),
            gst_sys::GST_MESSAGE_ASYNC_DONE => MessageView::AsyncDone(AsyncDone(self)),
            gst_sys::GST_MESSAGE_REQUEST_STATE => MessageView::RequestState(RequestState(self)),
            gst_sys::GST_MESSAGE_STEP_START => MessageView::StepStart(StepStart(self)),
            gst_sys::GST_MESSAGE_QOS => MessageView::Qos(Qos(self)),
            gst_sys::GST_MESSAGE_PROGRESS => MessageView::Progress(Progress(self)),
            gst_sys::GST_MESSAGE_TOC => MessageView::Toc(Toc(self)),
            gst_sys::GST_MESSAGE_RESET_TIME => MessageView::ResetTime(ResetTime(self)),
            gst_sys::GST_MESSAGE_STREAM_START => MessageView::StreamStart(StreamStart(self)),
            gst_sys::GST_MESSAGE_NEED_CONTEXT => MessageView::NeedContext(NeedContext(self)),
            gst_sys::GST_MESSAGE_HAVE_CONTEXT => MessageView::HaveContext(HaveContext(self)),
            gst_sys::GST_MESSAGE_DEVICE_ADDED => MessageView::DeviceAdded(DeviceAdded(self)),
            gst_sys::GST_MESSAGE_DEVICE_REMOVED => MessageView::DeviceRemoved(DeviceRemoved(self)),
            gst_sys::GST_MESSAGE_PROPERTY_NOTIFY => {
                MessageView::PropertyNotify(PropertyNotify(self))
            }
            gst_sys::GST_MESSAGE_STREAM_COLLECTION => {
                MessageView::StreamCollection(StreamCollection(self))
            }
            gst_sys::GST_MESSAGE_STREAMS_SELECTED => {
                MessageView::StreamsSelected(StreamsSelected(self))
            }
            gst_sys::GST_MESSAGE_DEVICE_CHANGED => MessageView::DeviceChanged(DeviceChanged(self)),
            _ => MessageView::Other,
        }
    }

    pub fn get_type(&self) -> MessageType {
        unsafe { from_glib((*self.as_ptr()).type_) }
    }
}

impl Message {
    /// Create a new eos message. This message is generated and posted in
    /// the sink elements of a GstBin. The bin will only forward the EOS
    /// message to the application if all sinks have posted an EOS message.
    /// ## `src`
    /// The object originating the message.
    ///
    /// # Returns
    ///
    /// The new eos message.
    ///
    /// MT safe.
    pub fn new_eos<'a>() -> EosBuilder<'a> {
        assert_initialized_main_thread!();
        EosBuilder::new()
    }

    /// Create a new error message. The message will copy `error` and
    /// `debug`. This message is posted by element when a fatal event
    /// occurred. The pipeline will probably (partially) stop. The application
    /// receiving this message should stop the pipeline.
    /// ## `src`
    /// The object originating the message.
    /// ## `error`
    /// The GError for this message.
    /// ## `debug`
    /// A debugging string.
    ///
    /// # Returns
    ///
    /// the new error message.
    ///
    /// MT safe.
    pub fn new_error<T: MessageErrorDomain>(error: T, message: &str) -> ErrorBuilder<T> {
        assert_initialized_main_thread!();
        ErrorBuilder::new(error, message)
    }

    /// Create a new warning message. The message will make copies of `error` and
    /// `debug`.
    /// ## `src`
    /// The object originating the message.
    /// ## `error`
    /// The GError for this message.
    /// ## `debug`
    /// A debugging string.
    ///
    /// # Returns
    ///
    /// the new warning message.
    ///
    /// MT safe.
    pub fn new_warning<T: MessageErrorDomain>(error: T, message: &str) -> WarningBuilder<T> {
        assert_initialized_main_thread!();
        WarningBuilder::new(error, message)
    }

    /// Create a new info message. The message will make copies of `error` and
    /// `debug`.
    /// ## `src`
    /// The object originating the message.
    /// ## `error`
    /// The GError for this message.
    /// ## `debug`
    /// A debugging string.
    ///
    /// # Returns
    ///
    /// the new info message.
    ///
    /// MT safe.
    pub fn new_info<T: MessageErrorDomain>(error: T, message: &str) -> InfoBuilder<T> {
        assert_initialized_main_thread!();
        InfoBuilder::new(error, message)
    }

    /// Create a new tag message. The message will take ownership of the tag list.
    /// The message is posted by elements that discovered a new taglist.
    /// ## `src`
    /// The object originating the message.
    /// ## `tag_list`
    /// the tag list for the message.
    ///
    /// # Returns
    ///
    /// the new tag message.
    ///
    /// MT safe.
    pub fn new_tag(tags: &TagList) -> TagBuilder {
        assert_initialized_main_thread!();
        TagBuilder::new(tags)
    }

    /// Create a new buffering message. This message can be posted by an element that
    /// needs to buffer data before it can continue processing. `percent` should be a
    /// value between 0 and 100. A value of 100 means that the buffering completed.
    ///
    /// When `percent` is < 100 the application should PAUSE a PLAYING pipeline. When
    /// `percent` is 100, the application can set the pipeline (back) to PLAYING.
    /// The application must be prepared to receive BUFFERING messages in the
    /// PREROLLING state and may only set the pipeline to PLAYING after receiving a
    /// message with `percent` set to 100, which can happen after the pipeline
    /// completed prerolling.
    ///
    /// MT safe.
    /// ## `src`
    /// The object originating the message.
    /// ## `percent`
    /// The buffering percent
    ///
    /// # Returns
    ///
    /// The new buffering message.
    pub fn new_buffering<'a>(percent: i32) -> BufferingBuilder<'a> {
        assert_initialized_main_thread!();
        BufferingBuilder::new(percent)
    }

    /// Create a state change message. This message is posted whenever an element
    /// changed its state.
    /// ## `src`
    /// The object originating the message.
    /// ## `oldstate`
    /// the previous state
    /// ## `newstate`
    /// the new (current) state
    /// ## `pending`
    /// the pending (target) state
    ///
    /// # Returns
    ///
    /// the new state change message.
    ///
    /// MT safe.
    pub fn new_state_changed<'a>(
        old: ::State,
        new: ::State,
        pending: ::State,
    ) -> StateChangedBuilder<'a> {
        assert_initialized_main_thread!();
        StateChangedBuilder::new(old, new, pending)
    }

    /// Create a state dirty message. This message is posted whenever an element
    /// changed its state asynchronously and is used internally to update the
    /// states of container objects.
    /// ## `src`
    /// The object originating the message
    ///
    /// # Returns
    ///
    /// the new state dirty message.
    ///
    /// MT safe.
    pub fn new_state_dirty<'a>() -> StateDirtyBuilder<'a> {
        assert_initialized_main_thread!();
        StateDirtyBuilder::new()
    }

    /// This message is posted by elements when they complete a part, when `intermediate` set
    /// to `true`, or a complete step operation.
    ///
    /// `duration` will contain the amount of time (in GST_FORMAT_TIME) of the stepped
    /// `amount` of media in format `format`.
    /// ## `src`
    /// The object originating the message.
    /// ## `format`
    /// the format of `amount`
    /// ## `amount`
    /// the amount of stepped data
    /// ## `rate`
    /// the rate of the stepped amount
    /// ## `flush`
    /// is this an flushing step
    /// ## `intermediate`
    /// is this an intermediate step
    /// ## `duration`
    /// the duration of the data
    /// ## `eos`
    /// the step caused EOS
    ///
    /// # Returns
    ///
    /// the new step_done message.
    ///
    /// MT safe.
    pub fn new_step_done<'a, V: Into<GenericFormattedValue>>(
        amount: V,
        rate: f64,
        flush: bool,
        intermediate: bool,
        duration: V,
        eos: bool,
    ) -> StepDoneBuilder<'a> {
        assert_initialized_main_thread!();
        StepDoneBuilder::new(
            amount.into(),
            rate,
            flush,
            intermediate,
            duration.into(),
            eos,
        )
    }

    /// Create a clock provide message. This message is posted whenever an
    /// element is ready to provide a clock or lost its ability to provide
    /// a clock (maybe because it paused or became EOS).
    ///
    /// This message is mainly used internally to manage the clock
    /// selection.
    /// ## `src`
    /// The object originating the message.
    /// ## `clock`
    /// the clock it provides
    /// ## `ready`
    /// `true` if the sender can provide a clock
    ///
    /// # Returns
    ///
    /// the new provide clock message.
    ///
    /// MT safe.
    pub fn new_clock_provide(clock: &::Clock, ready: bool) -> ClockProvideBuilder {
        assert_initialized_main_thread!();
        ClockProvideBuilder::new(clock, ready)
    }

    /// Create a clock lost message. This message is posted whenever the
    /// clock is not valid anymore.
    ///
    /// If this message is posted by the pipeline, the pipeline will
    /// select a new clock again when it goes to PLAYING. It might therefore
    /// be needed to set the pipeline to PAUSED and PLAYING again.
    /// ## `src`
    /// The object originating the message.
    /// ## `clock`
    /// the clock that was lost
    ///
    /// # Returns
    ///
    /// The new clock lost message.
    ///
    /// MT safe.
    pub fn new_clock_lost(clock: &::Clock) -> ClockLostBuilder {
        assert_initialized_main_thread!();
        ClockLostBuilder::new(clock)
    }

    /// Create a new clock message. This message is posted whenever the
    /// pipeline selects a new clock for the pipeline.
    /// ## `src`
    /// The object originating the message.
    /// ## `clock`
    /// the new selected clock
    ///
    /// # Returns
    ///
    /// The new new clock message.
    ///
    /// MT safe.
    pub fn new_new_clock(clock: &::Clock) -> NewClockBuilder {
        assert_initialized_main_thread!();
        NewClockBuilder::new(clock)
    }

    /// Create a new structure change message. This message is posted when the
    /// structure of a pipeline is in the process of being changed, for example
    /// when pads are linked or unlinked.
    ///
    /// `src` should be the sinkpad that unlinked or linked.
    /// ## `src`
    /// The object originating the message.
    /// ## `type_`
    /// The change type.
    /// ## `owner`
    /// The owner element of `src`.
    /// ## `busy`
    /// Whether the structure change is busy.
    ///
    /// # Returns
    ///
    /// the new structure change message.
    ///
    /// MT safe.
    pub fn new_structure_change(
        type_: ::StructureChangeType,
        owner: &::Element,
        busy: bool,
    ) -> StructureChangeBuilder {
        assert_initialized_main_thread!();
        StructureChangeBuilder::new(type_, owner, busy)
    }

    /// Create a new stream status message. This message is posted when a streaming
    /// thread is created/destroyed or when the state changed.
    /// ## `src`
    /// The object originating the message.
    /// ## `type_`
    /// The stream status type.
    /// ## `owner`
    /// the owner element of `src`.
    ///
    /// # Returns
    ///
    /// the new stream status message.
    ///
    /// MT safe.
    pub fn new_stream_status(type_: ::StreamStatusType, owner: &::Element) -> StreamStatusBuilder {
        assert_initialized_main_thread!();
        StreamStatusBuilder::new(type_, owner)
    }

    /// Create a new application-typed message. GStreamer will never create these
    /// messages; they are a gift from us to you. Enjoy.
    /// ## `src`
    /// The object originating the message.
    /// ## `structure`
    /// the structure for the message. The message
    ///  will take ownership of the structure.
    ///
    /// # Returns
    ///
    /// The new application message.
    ///
    /// MT safe.
    pub fn new_application<'a>(structure: ::Structure) -> ApplicationBuilder<'a> {
        assert_initialized_main_thread!();
        ApplicationBuilder::new(structure)
    }

    /// Create a new element-specific message. This is meant as a generic way of
    /// allowing one-way communication from an element to an application, for example
    /// "the firewire cable was unplugged". The format of the message should be
    /// documented in the element's documentation. The structure field can be `None`.
    /// ## `src`
    /// The object originating the message.
    /// ## `structure`
    /// The structure for the
    ///  message. The message will take ownership of the structure.
    ///
    /// # Returns
    ///
    /// The new element message.
    ///
    /// MT safe.
    pub fn new_element<'a>(structure: ::Structure) -> ElementBuilder<'a> {
        assert_initialized_main_thread!();
        ElementBuilder::new(structure)
    }

    /// Create a new segment message. This message is posted by elements that
    /// start playback of a segment as a result of a segment seek. This message
    /// is not received by the application but is used for maintenance reasons in
    /// container elements.
    /// ## `src`
    /// The object originating the message.
    /// ## `format`
    /// The format of the position being played
    /// ## `position`
    /// The position of the segment being played
    ///
    /// # Returns
    ///
    /// the new segment start message.
    ///
    /// MT safe.
    pub fn new_segment_start<'a, V: Into<GenericFormattedValue>>(
        position: V,
    ) -> SegmentStartBuilder<'a> {
        assert_initialized_main_thread!();
        let position = position.into();
        SegmentStartBuilder::new(position)
    }

    /// Create a new segment done message. This message is posted by elements that
    /// finish playback of a segment as a result of a segment seek. This message
    /// is received by the application after all elements that posted a segment_start
    /// have posted the segment_done.
    /// ## `src`
    /// The object originating the message.
    /// ## `format`
    /// The format of the position being done
    /// ## `position`
    /// The position of the segment being done
    ///
    /// # Returns
    ///
    /// the new segment done message.
    ///
    /// MT safe.
    pub fn new_segment_done<'a, V: Into<GenericFormattedValue>>(
        position: V,
    ) -> SegmentDoneBuilder<'a> {
        assert_initialized_main_thread!();
        let position = position.into();
        SegmentDoneBuilder::new(position)
    }

    /// Create a new duration changed message. This message is posted by elements
    /// that know the duration of a stream when the duration changes. This message
    /// is received by bins and is used to calculate the total duration of a
    /// pipeline.
    /// ## `src`
    /// The object originating the message.
    ///
    /// # Returns
    ///
    /// The new duration-changed message.
    ///
    /// MT safe.
    pub fn new_duration_changed<'a>() -> DurationChangedBuilder<'a> {
        assert_initialized_main_thread!();
        DurationChangedBuilder::new()
    }

    /// This message can be posted by elements when their latency requirements have
    /// changed.
    /// ## `src`
    /// The object originating the message.
    ///
    /// # Returns
    ///
    /// The new latency message.
    ///
    /// MT safe.
    pub fn new_latency<'a>() -> LatencyBuilder<'a> {
        assert_initialized_main_thread!();
        LatencyBuilder::new()
    }

    /// This message is posted by elements when they start an ASYNC state change.
    /// ## `src`
    /// The object originating the message.
    ///
    /// # Returns
    ///
    /// The new async_start message.
    ///
    /// MT safe.
    pub fn new_async_start<'a>() -> AsyncStartBuilder<'a> {
        assert_initialized_main_thread!();
        AsyncStartBuilder::new()
    }

    /// The message is posted when elements completed an ASYNC state change.
    /// `running_time` contains the time of the desired running_time when this
    /// elements goes to PLAYING. A value of `GST_CLOCK_TIME_NONE` for `running_time`
    /// means that the element has no clock interaction and thus doesn't care about
    /// the running_time of the pipeline.
    /// ## `src`
    /// The object originating the message.
    /// ## `running_time`
    /// the desired running_time
    ///
    /// # Returns
    ///
    /// The new async_done message.
    ///
    /// MT safe.
    pub fn new_async_done<'a>(running_time: ::ClockTime) -> AsyncDoneBuilder<'a> {
        assert_initialized_main_thread!();
        AsyncDoneBuilder::new(running_time)
    }

    /// This message can be posted by elements when they want to have their state
    /// changed. A typical use case would be an audio server that wants to pause the
    /// pipeline because a higher priority stream is being played.
    /// ## `src`
    /// The object originating the message.
    /// ## `state`
    /// The new requested state
    ///
    /// # Returns
    ///
    /// the new request state message.
    ///
    /// MT safe.
    pub fn new_request_state<'a>(state: ::State) -> RequestStateBuilder<'a> {
        assert_initialized_main_thread!();
        RequestStateBuilder::new(state)
    }

    /// This message is posted by elements when they accept or activate a new step
    /// event for `amount` in `format`.
    ///
    /// `active` is set to `false` when the element accepted the new step event and has
    /// queued it for execution in the streaming threads.
    ///
    /// `active` is set to `true` when the element has activated the step operation and
    /// is now ready to start executing the step in the streaming thread. After this
    /// message is emitted, the application can queue a new step operation in the
    /// element.
    /// ## `src`
    /// The object originating the message.
    /// ## `active`
    /// if the step is active or queued
    /// ## `format`
    /// the format of `amount`
    /// ## `amount`
    /// the amount of stepped data
    /// ## `rate`
    /// the rate of the stepped amount
    /// ## `flush`
    /// is this an flushing step
    /// ## `intermediate`
    /// is this an intermediate step
    ///
    /// # Returns
    ///
    /// The new step_start message.
    ///
    /// MT safe.
    pub fn new_step_start<'a, V: Into<GenericFormattedValue>>(
        active: bool,
        amount: V,
        rate: f64,
        flush: bool,
        intermediate: bool,
    ) -> StepStartBuilder<'a> {
        assert_initialized_main_thread!();
        StepStartBuilder::new(active, amount.into(), rate, flush, intermediate)
    }

    pub fn new_qos_builder<'a>(
        live: bool,
        running_time: ::ClockTime,
        stream_time: ::ClockTime,
        timestamp: ::ClockTime,
        duration: ::ClockTime,
    ) -> QosBuilder<'a> {
        assert_initialized_main_thread!();
        QosBuilder::new(live, running_time, stream_time, timestamp, duration)
    }

    /// Progress messages are posted by elements when they use an asynchronous task
    /// to perform actions triggered by a state change.
    ///
    /// `code` contains a well defined string describing the action.
    /// `text` should contain a user visible string detailing the current action.
    /// ## `src`
    /// The object originating the message.
    /// ## `type_`
    /// a `ProgressType`
    /// ## `code`
    /// a progress code
    /// ## `text`
    /// free, user visible text describing the progress
    ///
    /// # Returns
    ///
    /// The new qos message.
    pub fn new_progress<'a>(
        type_: ::ProgressType,
        code: &'a str,
        text: &'a str,
    ) -> ProgressBuilder<'a> {
        assert_initialized_main_thread!();
        ProgressBuilder::new(type_, code, text)
    }

    /// Create a new TOC message. The message is posted by elements
    /// that discovered or updated a TOC.
    /// ## `src`
    /// the object originating the message.
    /// ## `toc`
    /// `Toc` structure for the message.
    /// ## `updated`
    /// whether TOC was updated or not.
    ///
    /// # Returns
    ///
    /// a new TOC message.
    ///
    /// MT safe.
    pub fn new_toc(toc: &::Toc, updated: bool) -> TocBuilder {
        assert_initialized_main_thread!();
        TocBuilder::new(toc, updated)
    }

    /// This message is posted when the pipeline running-time should be reset to
    /// `running_time`, like after a flushing seek.
    /// ## `src`
    /// The object originating the message.
    /// ## `running_time`
    /// the requested running-time
    ///
    /// # Returns
    ///
    /// The new reset_time message.
    ///
    /// MT safe.
    pub fn new_reset_time<'a>(running_time: ::ClockTime) -> ResetTimeBuilder<'a> {
        assert_initialized_main_thread!();
        ResetTimeBuilder::new(running_time)
    }

    /// Create a new stream_start message. This message is generated and posted in
    /// the sink elements of a GstBin. The bin will only forward the STREAM_START
    /// message to the application if all sinks have posted an STREAM_START message.
    /// ## `src`
    /// The object originating the message.
    ///
    /// # Returns
    ///
    /// The new stream_start message.
    ///
    /// MT safe.
    pub fn new_stream_start<'a>() -> StreamStartBuilder<'a> {
        assert_initialized_main_thread!();
        StreamStartBuilder::new()
    }

    /// This message is posted when an element needs a specific `Context`.
    /// ## `src`
    /// The object originating the message.
    /// ## `context_type`
    /// The context type that is needed
    ///
    /// # Returns
    ///
    /// The new need-context message.
    ///
    /// MT safe.
    pub fn new_need_context(context_type: &str) -> NeedContextBuilder {
        assert_initialized_main_thread!();
        NeedContextBuilder::new(context_type)
    }

    /// This message is posted when an element has a new local `Context`.
    /// ## `src`
    /// The object originating the message.
    /// ## `context`
    /// the context
    ///
    /// # Returns
    ///
    /// The new have-context message.
    ///
    /// MT safe.
    pub fn new_have_context<'a>(context: ::Context) -> HaveContextBuilder<'a> {
        assert_initialized_main_thread!();
        HaveContextBuilder::new(context)
    }

    /// Creates a new device-added message. The device-added message is produced by
    /// `DeviceProvider` or a `DeviceMonitor`. They announce the appearance
    /// of monitored devices.
    /// ## `src`
    /// The `Object` that created the message
    /// ## `device`
    /// The new `Device`
    ///
    /// # Returns
    ///
    /// a newly allocated `Message`
    pub fn new_device_added(device: &::Device) -> DeviceAddedBuilder {
        assert_initialized_main_thread!();
        DeviceAddedBuilder::new(device)
    }

    /// Creates a new device-removed message. The device-removed message is produced
    /// by `DeviceProvider` or a `DeviceMonitor`. They announce the
    /// disappearance of monitored devices.
    /// ## `src`
    /// The `Object` that created the message
    /// ## `device`
    /// The removed `Device`
    ///
    /// # Returns
    ///
    /// a newly allocated `Message`
    pub fn new_device_removed(device: &::Device) -> DeviceRemovedBuilder {
        assert_initialized_main_thread!();
        DeviceRemovedBuilder::new(device)
    }

    ///
    /// Feature: `v1_10`
    ///
    /// ## `src`
    /// The `Object` whose property changed (may or may not be a `Element`)
    /// ## `property_name`
    /// name of the property that changed
    /// ## `val`
    /// new property value, or `None`
    ///
    /// # Returns
    ///
    /// a newly allocated `Message`
    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn new_property_notify(property_name: &str) -> PropertyNotifyBuilder {
        assert_initialized_main_thread!();
        PropertyNotifyBuilder::new(property_name)
    }

    /// Creates a new stream-collection message. The message is used to announce new
    /// `StreamCollection`
    ///
    /// Feature: `v1_10`
    ///
    /// ## `src`
    /// The `Object` that created the message
    /// ## `collection`
    /// The `StreamCollection`
    ///
    /// # Returns
    ///
    /// a newly allocated `Message`
    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn new_stream_collection(collection: &::StreamCollection) -> StreamCollectionBuilder {
        assert_initialized_main_thread!();
        StreamCollectionBuilder::new(collection)
    }

    /// Creates a new steams-selected message. The message is used to announce
    /// that an array of streams has been selected. This is generally in response
    /// to a `EventType::SelectStreams` event, or when an element (such as decodebin3)
    /// makes an initial selection of streams.
    ///
    /// The message also contains the `StreamCollection` to which the various streams
    /// belong to.
    ///
    /// Users of `Message::new_streams_selected` can add the selected streams with
    /// `Message::streams_selected_add`.
    ///
    /// Feature: `v1_10`
    ///
    /// ## `src`
    /// The `Object` that created the message
    /// ## `collection`
    /// The `StreamCollection`
    ///
    /// # Returns
    ///
    /// a newly allocated `Message`
    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn new_streams_selected(collection: &::StreamCollection) -> StreamsSelectedBuilder {
        assert_initialized_main_thread!();
        StreamsSelectedBuilder::new(collection)
    }

    /// Creates a new redirect message and adds a new entry to it. Redirect messages
    /// are posted when an element detects that the actual data has to be retrieved
    /// from a different location. This is useful if such a redirection cannot be
    /// handled inside a source element, for example when HTTP 302/303 redirects
    /// return a non-HTTP URL.
    ///
    /// The redirect message can hold multiple entries. The first one is added
    /// when the redirect message is created, with the given location, tag_list,
    /// entry_struct arguments. Use `Message::add_redirect_entry` to add more
    /// entries.
    ///
    /// Each entry has a location, a tag list, and a structure. All of these are
    /// optional. The tag list and structure are useful for additional metadata,
    /// such as bitrate statistics for the given location.
    ///
    /// By default, message recipients should treat entries in the order they are
    /// stored. The recipient should therefore try entry `0` first, and if this
    /// entry is not acceptable or working, try entry `1` etc. Senders must make
    /// sure that they add entries in this order. However, recipients are free to
    /// ignore the order and pick an entry that is "best" for them. One example
    /// would be a recipient that scans the entries for the one with the highest
    /// bitrate tag.
    ///
    /// The specified location string is copied. However, ownership over the tag
    /// list and structure are transferred to the message.
    ///
    /// Feature: `v1_10`
    ///
    /// ## `src`
    /// The `Object` whose property changed (may or may not be a `Element`)
    /// ## `location`
    /// location string for the new entry
    /// ## `tag_list`
    /// tag list for the new entry
    /// ## `entry_struct`
    /// structure for the new entry
    ///
    /// # Returns
    ///
    /// a newly allocated `Message`
    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn new_redirect(location: &str) -> RedirectBuilder {
        assert_initialized_main_thread!();
        RedirectBuilder::new(location)
    }

    /// Creates a new device-changed message. The device-changed message is produced
    /// by `DeviceProvider` or a `DeviceMonitor`. They announce that a device
    /// properties has changed and `device` represent the new modified version of `changed_device`.
    ///
    /// Feature: `v1_16`
    ///
    /// ## `src`
    /// The `Object` that created the message
    /// ## `device`
    /// The newly created device representing `replaced_device`
    ///  with its new configuration.
    ///
    /// # Returns
    ///
    /// a newly allocated `Message`
    #[cfg(any(feature = "v1_16", feature = "dox"))]
    pub fn new_device_changed<'a>(
        device: &'a ::Device,
        changed_device: &'a ::Device,
    ) -> DeviceChangedBuilder<'a> {
        assert_initialized_main_thread!();
        DeviceChangedBuilder::new(device, changed_device)
    }
}

impl fmt::Debug for MessageRef {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Message")
            .field("ptr", unsafe { &self.as_ptr() })
            .field("type", &unsafe {
                let type_ = gst_sys::gst_message_type_get_name((*self.as_ptr()).type_);
                CStr::from_ptr(type_).to_str().unwrap()
            })
            .field("seqnum", &self.get_seqnum())
            .field("src", &self.get_src().map(|s| s.get_name()))
            .field("structure", &self.get_structure())
            .finish()
    }
}

#[derive(Debug)]
pub enum MessageView<'a> {
    Eos(Eos<'a>),
    Error(Error<'a>),
    Warning(Warning<'a>),
    Info(Info<'a>),
    Tag(Tag<'a>),
    Buffering(Buffering<'a>),
    StateChanged(StateChanged<'a>),
    StateDirty(StateDirty<'a>),
    StepDone(StepDone<'a>),
    ClockProvide(ClockProvide<'a>),
    ClockLost(ClockLost<'a>),
    NewClock(NewClock<'a>),
    StructureChange(StructureChange<'a>),
    StreamStatus(StreamStatus<'a>),
    Application(Application<'a>),
    Element(Element<'a>),
    SegmentStart(SegmentStart<'a>),
    SegmentDone(SegmentDone<'a>),
    DurationChanged(DurationChanged<'a>),
    Latency(Latency<'a>),
    AsyncStart(AsyncStart<'a>),
    AsyncDone(AsyncDone<'a>),
    RequestState(RequestState<'a>),
    StepStart(StepStart<'a>),
    Qos(Qos<'a>),
    Progress(Progress<'a>),
    Toc(Toc<'a>),
    ResetTime(ResetTime<'a>),
    StreamStart(StreamStart<'a>),
    NeedContext(NeedContext<'a>),
    HaveContext(HaveContext<'a>),
    DeviceAdded(DeviceAdded<'a>),
    DeviceRemoved(DeviceRemoved<'a>),
    PropertyNotify(PropertyNotify<'a>),
    StreamCollection(StreamCollection<'a>),
    StreamsSelected(StreamsSelected<'a>),
    Redirect(Redirect<'a>),
    DeviceChanged(DeviceChanged<'a>),
    Other,
    __NonExhaustive,
}

macro_rules! declare_concrete_message(
    ($name:ident) => {
        #[derive(Debug)]
        pub struct $name<'a>(&'a MessageRef);

        impl<'a> Deref for $name<'a> {
            type Target = MessageRef;

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

declare_concrete_message!(Eos);

declare_concrete_message!(Error);
impl<'a> Error<'a> {
    pub fn get_error(&self) -> glib::Error {
        unsafe {
            let mut error = ptr::null_mut();

            gst_sys::gst_message_parse_error(self.as_mut_ptr(), &mut error, ptr::null_mut());

            from_glib_full(error)
        }
    }

    pub fn get_debug(&self) -> Option<String> {
        unsafe {
            let mut debug = ptr::null_mut();

            gst_sys::gst_message_parse_error(self.as_mut_ptr(), ptr::null_mut(), &mut debug);

            from_glib_full(debug)
        }
    }

    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn get_details(&self) -> Option<&StructureRef> {
        unsafe {
            let mut details = ptr::null();

            gst_sys::gst_message_parse_error_details(self.as_mut_ptr(), &mut details);

            if details.is_null() {
                None
            } else {
                Some(StructureRef::from_glib_borrow(details))
            }
        }
    }
}

declare_concrete_message!(Warning);
impl<'a> Warning<'a> {
    pub fn get_error(&self) -> glib::Error {
        unsafe {
            let mut error = ptr::null_mut();

            gst_sys::gst_message_parse_warning(self.as_mut_ptr(), &mut error, ptr::null_mut());

            from_glib_full(error)
        }
    }

    pub fn get_debug(&self) -> Option<String> {
        unsafe {
            let mut debug = ptr::null_mut();

            gst_sys::gst_message_parse_warning(self.as_mut_ptr(), ptr::null_mut(), &mut debug);

            from_glib_full(debug)
        }
    }

    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn get_details(&self) -> Option<&StructureRef> {
        unsafe {
            let mut details = ptr::null();

            gst_sys::gst_message_parse_error_details(self.as_mut_ptr(), &mut details);

            if details.is_null() {
                None
            } else {
                Some(StructureRef::from_glib_borrow(details))
            }
        }
    }
}

declare_concrete_message!(Info);
impl<'a> Info<'a> {
    pub fn get_error(&self) -> glib::Error {
        unsafe {
            let mut error = ptr::null_mut();

            gst_sys::gst_message_parse_info(self.as_mut_ptr(), &mut error, ptr::null_mut());

            from_glib_full(error)
        }
    }

    pub fn get_debug(&self) -> Option<String> {
        unsafe {
            let mut debug = ptr::null_mut();

            gst_sys::gst_message_parse_info(self.as_mut_ptr(), ptr::null_mut(), &mut debug);

            from_glib_full(debug)
        }
    }

    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn get_details(&self) -> Option<&StructureRef> {
        unsafe {
            let mut details = ptr::null();

            gst_sys::gst_message_parse_error_details(self.as_mut_ptr(), &mut details);

            if details.is_null() {
                None
            } else {
                Some(StructureRef::from_glib_borrow(details))
            }
        }
    }
}

declare_concrete_message!(Tag);
impl<'a> Tag<'a> {
    pub fn get_tags(&self) -> TagList {
        unsafe {
            let mut tags = ptr::null_mut();
            gst_sys::gst_message_parse_tag(self.as_mut_ptr(), &mut tags);
            from_glib_full(tags)
        }
    }
}

declare_concrete_message!(Buffering);
impl<'a> Buffering<'a> {
    pub fn get_percent(&self) -> i32 {
        unsafe {
            let mut p = mem::MaybeUninit::uninit();
            gst_sys::gst_message_parse_buffering(self.as_mut_ptr(), p.as_mut_ptr());
            p.assume_init()
        }
    }

    pub fn get_buffering_stats(&self) -> (::BufferingMode, i32, i32, i64) {
        unsafe {
            let mut mode = mem::MaybeUninit::uninit();
            let mut avg_in = mem::MaybeUninit::uninit();
            let mut avg_out = mem::MaybeUninit::uninit();
            let mut buffering_left = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_buffering_stats(
                self.as_mut_ptr(),
                mode.as_mut_ptr(),
                avg_in.as_mut_ptr(),
                avg_out.as_mut_ptr(),
                buffering_left.as_mut_ptr(),
            );

            (
                from_glib(mode.assume_init()),
                avg_in.assume_init(),
                avg_out.assume_init(),
                buffering_left.assume_init(),
            )
        }
    }
}

declare_concrete_message!(StateChanged);
impl<'a> StateChanged<'a> {
    pub fn get_old(&self) -> ::State {
        unsafe {
            let mut state = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_state_changed(
                self.as_mut_ptr(),
                state.as_mut_ptr(),
                ptr::null_mut(),
                ptr::null_mut(),
            );

            from_glib(state.assume_init())
        }
    }

    pub fn get_current(&self) -> ::State {
        unsafe {
            let mut state = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_state_changed(
                self.as_mut_ptr(),
                ptr::null_mut(),
                state.as_mut_ptr(),
                ptr::null_mut(),
            );

            from_glib(state.assume_init())
        }
    }

    pub fn get_pending(&self) -> ::State {
        unsafe {
            let mut state = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_state_changed(
                self.as_mut_ptr(),
                ptr::null_mut(),
                ptr::null_mut(),
                state.as_mut_ptr(),
            );

            from_glib(state.assume_init())
        }
    }
}

declare_concrete_message!(StateDirty);

declare_concrete_message!(StepDone);
impl<'a> StepDone<'a> {
    pub fn get(
        &self,
    ) -> (
        GenericFormattedValue,
        f64,
        bool,
        bool,
        GenericFormattedValue,
        bool,
    ) {
        unsafe {
            let mut format = mem::MaybeUninit::uninit();
            let mut amount = mem::MaybeUninit::uninit();
            let mut rate = mem::MaybeUninit::uninit();
            let mut flush = mem::MaybeUninit::uninit();
            let mut intermediate = mem::MaybeUninit::uninit();
            let mut duration = mem::MaybeUninit::uninit();
            let mut eos = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_step_done(
                self.as_mut_ptr(),
                format.as_mut_ptr(),
                amount.as_mut_ptr(),
                rate.as_mut_ptr(),
                flush.as_mut_ptr(),
                intermediate.as_mut_ptr(),
                duration.as_mut_ptr(),
                eos.as_mut_ptr(),
            );

            (
                GenericFormattedValue::new(
                    from_glib(format.assume_init()),
                    amount.assume_init() as i64,
                ),
                rate.assume_init(),
                from_glib(flush.assume_init()),
                from_glib(intermediate.assume_init()),
                GenericFormattedValue::new(
                    from_glib(format.assume_init()),
                    duration.assume_init() as i64,
                ),
                from_glib(eos.assume_init()),
            )
        }
    }
}

declare_concrete_message!(ClockProvide);
impl<'a> ClockProvide<'a> {
    pub fn get_clock(&self) -> Option<::Clock> {
        let mut clock = ptr::null_mut();

        unsafe {
            gst_sys::gst_message_parse_clock_provide(
                self.as_mut_ptr(),
                &mut clock,
                ptr::null_mut(),
            );

            from_glib_none(clock)
        }
    }

    pub fn get_ready(&self) -> bool {
        unsafe {
            let mut ready = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_clock_provide(
                self.as_mut_ptr(),
                ptr::null_mut(),
                ready.as_mut_ptr(),
            );

            from_glib(ready.assume_init())
        }
    }
}

declare_concrete_message!(ClockLost);
impl<'a> ClockLost<'a> {
    pub fn get_clock(&self) -> Option<::Clock> {
        let mut clock = ptr::null_mut();

        unsafe {
            gst_sys::gst_message_parse_clock_lost(self.as_mut_ptr(), &mut clock);

            from_glib_none(clock)
        }
    }
}

declare_concrete_message!(NewClock);
impl<'a> NewClock<'a> {
    pub fn get_clock(&self) -> Option<::Clock> {
        let mut clock = ptr::null_mut();

        unsafe {
            gst_sys::gst_message_parse_new_clock(self.as_mut_ptr(), &mut clock);

            from_glib_none(clock)
        }
    }
}

declare_concrete_message!(StructureChange);
impl<'a> StructureChange<'a> {
    pub fn get(&self) -> (::StructureChangeType, ::Element, bool) {
        unsafe {
            let mut type_ = mem::MaybeUninit::uninit();
            let mut owner = ptr::null_mut();
            let mut busy = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_structure_change(
                self.as_mut_ptr(),
                type_.as_mut_ptr(),
                &mut owner,
                busy.as_mut_ptr(),
            );

            (
                from_glib(type_.assume_init()),
                from_glib_none(owner),
                from_glib(busy.assume_init()),
            )
        }
    }
}

declare_concrete_message!(StreamStatus);
impl<'a> StreamStatus<'a> {
    pub fn get(&self) -> (::StreamStatusType, ::Element) {
        unsafe {
            let mut type_ = mem::MaybeUninit::uninit();
            let mut owner = ptr::null_mut();

            gst_sys::gst_message_parse_stream_status(
                self.as_mut_ptr(),
                type_.as_mut_ptr(),
                &mut owner,
            );

            (from_glib(type_.assume_init()), from_glib_none(owner))
        }
    }

    pub fn get_stream_status_object(&self) -> Option<glib::Value> {
        unsafe {
            let value = gst_sys::gst_message_get_stream_status_object(self.as_mut_ptr());

            from_glib_none(value)
        }
    }
}

declare_concrete_message!(Application);

declare_concrete_message!(Element);

declare_concrete_message!(SegmentStart);
impl<'a> SegmentStart<'a> {
    pub fn get(&self) -> GenericFormattedValue {
        unsafe {
            let mut format = mem::MaybeUninit::uninit();
            let mut position = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_segment_start(
                self.as_mut_ptr(),
                format.as_mut_ptr(),
                position.as_mut_ptr(),
            );

            GenericFormattedValue::new(from_glib(format.assume_init()), position.assume_init())
        }
    }
}

declare_concrete_message!(SegmentDone);
impl<'a> SegmentDone<'a> {
    pub fn get(&self) -> GenericFormattedValue {
        unsafe {
            let mut format = mem::MaybeUninit::uninit();
            let mut position = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_segment_done(
                self.as_mut_ptr(),
                format.as_mut_ptr(),
                position.as_mut_ptr(),
            );

            GenericFormattedValue::new(from_glib(format.assume_init()), position.assume_init())
        }
    }
}

declare_concrete_message!(DurationChanged);
declare_concrete_message!(Latency);
declare_concrete_message!(AsyncStart);

declare_concrete_message!(AsyncDone);
impl<'a> AsyncDone<'a> {
    pub fn get_running_time(&self) -> ::ClockTime {
        unsafe {
            let mut running_time = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_async_done(self.as_mut_ptr(), running_time.as_mut_ptr());

            from_glib(running_time.assume_init())
        }
    }
}

declare_concrete_message!(RequestState);
impl<'a> RequestState<'a> {
    pub fn get_requested_state(&self) -> ::State {
        unsafe {
            let mut state = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_request_state(self.as_mut_ptr(), state.as_mut_ptr());

            from_glib(state.assume_init())
        }
    }
}

declare_concrete_message!(StepStart);
impl<'a> StepStart<'a> {
    pub fn get(&self) -> (bool, GenericFormattedValue, f64, bool, bool) {
        unsafe {
            let mut active = mem::MaybeUninit::uninit();
            let mut format = mem::MaybeUninit::uninit();
            let mut amount = mem::MaybeUninit::uninit();
            let mut rate = mem::MaybeUninit::uninit();
            let mut flush = mem::MaybeUninit::uninit();
            let mut intermediate = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_step_start(
                self.as_mut_ptr(),
                active.as_mut_ptr(),
                format.as_mut_ptr(),
                amount.as_mut_ptr(),
                rate.as_mut_ptr(),
                flush.as_mut_ptr(),
                intermediate.as_mut_ptr(),
            );

            (
                from_glib(active.assume_init()),
                GenericFormattedValue::new(
                    from_glib(format.assume_init()),
                    amount.assume_init() as i64,
                ),
                rate.assume_init(),
                from_glib(flush.assume_init()),
                from_glib(intermediate.assume_init()),
            )
        }
    }
}

declare_concrete_message!(Qos);
impl<'a> Qos<'a> {
    pub fn get(&self) -> (bool, ::ClockTime, ::ClockTime, ::ClockTime, ::ClockTime) {
        unsafe {
            let mut live = mem::MaybeUninit::uninit();
            let mut running_time = mem::MaybeUninit::uninit();
            let mut stream_time = mem::MaybeUninit::uninit();
            let mut timestamp = mem::MaybeUninit::uninit();
            let mut duration = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_qos(
                self.as_mut_ptr(),
                live.as_mut_ptr(),
                running_time.as_mut_ptr(),
                stream_time.as_mut_ptr(),
                timestamp.as_mut_ptr(),
                duration.as_mut_ptr(),
            );

            (
                from_glib(live.assume_init()),
                from_glib(running_time.assume_init()),
                from_glib(stream_time.assume_init()),
                from_glib(timestamp.assume_init()),
                from_glib(duration.assume_init()),
            )
        }
    }

    pub fn get_values(&self) -> (i64, f64, i32) {
        unsafe {
            let mut jitter = mem::MaybeUninit::uninit();
            let mut proportion = mem::MaybeUninit::uninit();
            let mut quality = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_qos_values(
                self.as_mut_ptr(),
                jitter.as_mut_ptr(),
                proportion.as_mut_ptr(),
                quality.as_mut_ptr(),
            );

            (
                jitter.assume_init(),
                proportion.assume_init(),
                quality.assume_init(),
            )
        }
    }

    pub fn get_stats(&self) -> (GenericFormattedValue, GenericFormattedValue) {
        unsafe {
            let mut format = mem::MaybeUninit::uninit();
            let mut processed = mem::MaybeUninit::uninit();
            let mut dropped = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_qos_stats(
                self.as_mut_ptr(),
                format.as_mut_ptr(),
                processed.as_mut_ptr(),
                dropped.as_mut_ptr(),
            );

            (
                GenericFormattedValue::new(
                    from_glib(format.assume_init()),
                    processed.assume_init() as i64,
                ),
                GenericFormattedValue::new(
                    from_glib(format.assume_init()),
                    dropped.assume_init() as i64,
                ),
            )
        }
    }
}

declare_concrete_message!(Progress);
impl<'a> Progress<'a> {
    pub fn get(&self) -> (::ProgressType, &'a str, &'a str) {
        unsafe {
            let mut type_ = mem::MaybeUninit::uninit();
            let mut code = ptr::null_mut();
            let mut text = ptr::null_mut();

            gst_sys::gst_message_parse_progress(
                self.as_mut_ptr(),
                type_.as_mut_ptr(),
                &mut code,
                &mut text,
            );

            let code = CStr::from_ptr(code).to_str().unwrap();
            let text = CStr::from_ptr(text).to_str().unwrap();

            (from_glib(type_.assume_init()), code, text)
        }
    }
}

declare_concrete_message!(Toc);
impl<'a> Toc<'a> {
    pub fn get_toc(&self) -> (::Toc, bool) {
        unsafe {
            let mut toc = ptr::null_mut();
            let mut updated = mem::MaybeUninit::uninit();
            gst_sys::gst_message_parse_toc(self.as_mut_ptr(), &mut toc, updated.as_mut_ptr());
            (from_glib_full(toc), from_glib(updated.assume_init()))
        }
    }
}

declare_concrete_message!(ResetTime);
impl<'a> ResetTime<'a> {
    pub fn get_running_time(&self) -> ::ClockTime {
        unsafe {
            let mut running_time = mem::MaybeUninit::uninit();

            gst_sys::gst_message_parse_reset_time(self.as_mut_ptr(), running_time.as_mut_ptr());

            from_glib(running_time.assume_init())
        }
    }
}

declare_concrete_message!(StreamStart);
impl<'a> StreamStart<'a> {
    pub fn get_group_id(&self) -> Option<GroupId> {
        unsafe {
            let mut group_id = mem::MaybeUninit::uninit();

            if from_glib(gst_sys::gst_message_parse_group_id(
                self.as_mut_ptr(),
                group_id.as_mut_ptr(),
            )) {
                Some(from_glib(group_id.assume_init()))
            } else {
                None
            }
        }
    }
}

declare_concrete_message!(NeedContext);
impl<'a> NeedContext<'a> {
    pub fn get_context_type(&self) -> &str {
        unsafe {
            let mut context_type = ptr::null();

            gst_sys::gst_message_parse_context_type(self.as_mut_ptr(), &mut context_type);

            CStr::from_ptr(context_type).to_str().unwrap()
        }
    }
}

declare_concrete_message!(HaveContext);
impl<'a> HaveContext<'a> {
    pub fn get_context(&self) -> ::Context {
        unsafe {
            let mut context = ptr::null_mut();
            gst_sys::gst_message_parse_have_context(self.as_mut_ptr(), &mut context);
            from_glib_full(context)
        }
    }
}

declare_concrete_message!(DeviceAdded);
impl<'a> DeviceAdded<'a> {
    pub fn get_device(&self) -> ::Device {
        unsafe {
            let mut device = ptr::null_mut();

            gst_sys::gst_message_parse_device_added(self.as_mut_ptr(), &mut device);

            from_glib_full(device)
        }
    }
}

declare_concrete_message!(DeviceRemoved);
impl<'a> DeviceRemoved<'a> {
    pub fn get_device(&self) -> ::Device {
        unsafe {
            let mut device = ptr::null_mut();

            gst_sys::gst_message_parse_device_removed(self.as_mut_ptr(), &mut device);

            from_glib_full(device)
        }
    }
}

declare_concrete_message!(PropertyNotify);
impl<'a> PropertyNotify<'a> {
    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn get(&self) -> (Object, &str, Option<&'a glib::Value>) {
        unsafe {
            let mut object = ptr::null_mut();
            let mut property_name = ptr::null();
            let mut value = ptr::null();

            gst_sys::gst_message_parse_property_notify(
                self.as_mut_ptr(),
                &mut object,
                &mut property_name,
                &mut value,
            );

            (
                from_glib_none(object),
                CStr::from_ptr(property_name).to_str().unwrap(),
                if value.is_null() {
                    None
                } else {
                    Some(&*(value as *const glib::Value))
                },
            )
        }
    }
}

declare_concrete_message!(StreamCollection);
impl<'a> StreamCollection<'a> {
    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn get_stream_collection(&self) -> ::StreamCollection {
        unsafe {
            let mut collection = ptr::null_mut();

            gst_sys::gst_message_parse_stream_collection(self.as_mut_ptr(), &mut collection);

            from_glib_full(collection)
        }
    }
}

declare_concrete_message!(StreamsSelected);
impl<'a> StreamsSelected<'a> {
    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn get_stream_collection(&self) -> ::StreamCollection {
        unsafe {
            let mut collection = ptr::null_mut();

            gst_sys::gst_message_parse_streams_selected(self.as_mut_ptr(), &mut collection);

            from_glib_full(collection)
        }
    }

    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn get_streams(&self) -> Vec<::Stream> {
        unsafe {
            let n = gst_sys::gst_message_streams_selected_get_size(self.as_mut_ptr());

            (0..n)
                .map(|i| {
                    from_glib_full(gst_sys::gst_message_streams_selected_get_stream(
                        self.as_mut_ptr(),
                        i,
                    ))
                })
                .collect()
        }
    }
}

declare_concrete_message!(Redirect);
impl<'a> Redirect<'a> {
    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn get_entries(&self) -> Vec<(&str, Option<TagList>, Option<&StructureRef>)> {
        unsafe {
            let n = gst_sys::gst_message_get_num_redirect_entries(self.as_mut_ptr());

            (0..n)
                .map(|i| {
                    let mut location = ptr::null();
                    let mut tags = ptr::null_mut();
                    let mut structure = ptr::null();

                    gst_sys::gst_message_parse_redirect_entry(
                        self.as_mut_ptr(),
                        i,
                        &mut location,
                        &mut tags,
                        &mut structure,
                    );

                    let structure = if structure.is_null() {
                        None
                    } else {
                        Some(StructureRef::from_glib_borrow(structure))
                    };

                    (
                        CStr::from_ptr(location).to_str().unwrap(),
                        from_glib_none(tags),
                        structure,
                    )
                })
                .collect()
        }
    }
}

declare_concrete_message!(DeviceChanged);
impl<'a> DeviceChanged<'a> {
    #[cfg(any(feature = "v1_16", feature = "dox"))]
    pub fn get_device_changed(&self) -> (::Device, ::Device) {
        unsafe {
            let mut device = ptr::null_mut();
            let mut changed_device = ptr::null_mut();

            gst_sys::gst_message_parse_device_changed(
                self.as_mut_ptr(),
                &mut device,
                &mut changed_device,
            );

            (from_glib_full(device), from_glib_full(changed_device))
        }
    }
}

struct MessageBuilder<'a> {
    src: Option<Object>,
    seqnum: Option<Seqnum>,
    #[allow(unused)]
    other_fields: Vec<(&'a str, &'a dyn ToSendValue)>,
}

impl<'a> MessageBuilder<'a> {
    fn new() -> Self {
        Self {
            src: None,
            seqnum: None,
            other_fields: Vec::new(),
        }
    }

    pub fn src<O: IsA<Object> + Cast + Clone>(self, src: Option<&O>) -> Self {
        Self {
            src: src.map(|o| {
                let o = (*o).clone();
                o.upcast::<Object>()
            }),
            ..self
        }
    }

    fn seqnum(self, seqnum: Seqnum) -> Self {
        Self {
            seqnum: Some(seqnum),
            ..self
        }
    }

    #[cfg(any(feature = "v1_14", feature = "dox"))]
    fn other_fields(self, other_fields: &[(&'a str, &'a dyn ToSendValue)]) -> Self {
        Self {
            other_fields: self
                .other_fields
                .iter()
                .cloned()
                .chain(other_fields.iter().cloned())
                .collect(),
            ..self
        }
    }
}

macro_rules! message_builder_generic_impl {
    ($new_fn:expr) => {
        #[allow(clippy::needless_update)]
        pub fn src<O: IsA<Object> + Cast + Clone>(self, src: Option<&O>) -> Self {
            Self {
                builder: self.builder.src(src),
                ..self
            }
        }

        #[allow(clippy::needless_update)]
        pub fn seqnum(self, seqnum: Seqnum) -> Self {
            Self {
                builder: self.builder.seqnum(seqnum),
                ..self
            }
        }

        #[cfg(any(feature = "v1_14", feature = "dox"))]
        #[allow(clippy::needless_update)]
        pub fn other_fields(self, other_fields: &[(&'a str, &'a dyn ToSendValue)]) -> Self {
            Self {
                builder: self.builder.other_fields(other_fields),
                ..self
            }
        }

        pub fn build(mut self) -> Message {
            assert_initialized_main_thread!();
            unsafe {
                let src = self.builder.src.to_glib_none().0;
                let msg = $new_fn(&mut self, src);
                if let Some(seqnum) = self.builder.seqnum {
                    gst_sys::gst_message_set_seqnum(msg, seqnum.to_glib());
                }

                #[cfg(any(feature = "v1_14", feature = "dox"))]
                {
                    if !self.builder.other_fields.is_empty() {
                        let structure = gst_sys::gst_message_writable_structure(msg);

                        if !structure.is_null() {
                            let structure = StructureRef::from_glib_borrow_mut(structure as *mut _);

                            for (k, v) in self.builder.other_fields {
                                structure.set_value(k, v.to_send_value());
                            }
                        }
                    }
                }

                from_glib_full(msg)
            }
        }
    };
}

pub struct EosBuilder<'a> {
    builder: MessageBuilder<'a>,
}
impl<'a> EosBuilder<'a> {
    fn new() -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
        }
    }

    message_builder_generic_impl!(|_, src| gst_sys::gst_message_new_eos(src));
}

pub trait MessageErrorDomain: glib::error::ErrorDomain {}

impl MessageErrorDomain for ::CoreError {}
impl MessageErrorDomain for ::ResourceError {}
impl MessageErrorDomain for ::StreamError {}
impl MessageErrorDomain for ::LibraryError {}

pub struct ErrorBuilder<'a, T> {
    builder: MessageBuilder<'a>,
    error: T,
    message: &'a str,
    debug: Option<&'a str>,
    #[allow(unused)]
    details: Option<Structure>,
}
impl<'a, T: MessageErrorDomain> ErrorBuilder<'a, T> {
    fn new(error: T, message: &'a str) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            error,
            message,
            debug: None,
            details: None,
        }
    }

    pub fn debug(self, debug: &'a str) -> Self {
        Self {
            debug: Some(debug),
            ..self
        }
    }

    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn details(self, details: Structure) -> Self {
        Self {
            details: Some(details),
            ..self
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| {
        #[cfg(any(feature = "v1_10", feature = "dox"))]
        {
            let details = match s.details.take() {
                None => ptr::null_mut(),
                Some(details) => details.into_ptr(),
            };

            let error = glib::Error::new(s.error, s.message);

            gst_sys::gst_message_new_error_with_details(
                src,
                mut_override(error.to_glib_none().0),
                s.debug.to_glib_none().0,
                details,
            )
        }
        #[cfg(not(any(feature = "v1_10", feature = "dox")))]
        {
            let error = glib::Error::new(s.error, s.message);

            gst_sys::gst_message_new_error(
                src,
                mut_override(error.to_glib_none().0),
                s.debug.to_glib_none().0,
            )
        }
    });
}

pub struct WarningBuilder<'a, T> {
    builder: MessageBuilder<'a>,
    error: T,
    message: &'a str,
    debug: Option<&'a str>,
    #[allow(unused)]
    details: Option<Structure>,
}
impl<'a, T: MessageErrorDomain> WarningBuilder<'a, T> {
    fn new(error: T, message: &'a str) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            error,
            message,
            debug: None,
            details: None,
        }
    }

    pub fn debug(self, debug: &'a str) -> Self {
        Self {
            debug: Some(debug),
            ..self
        }
    }

    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn details(self, details: Structure) -> Self {
        Self {
            details: Some(details),
            ..self
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| {
        #[cfg(any(feature = "v1_10", feature = "dox"))]
        {
            let details = match s.details.take() {
                None => ptr::null_mut(),
                Some(details) => details.into_ptr(),
            };

            let error = glib::Error::new(s.error, s.message);

            gst_sys::gst_message_new_warning_with_details(
                src,
                mut_override(error.to_glib_none().0),
                s.debug.to_glib_none().0,
                details,
            )
        }
        #[cfg(not(any(feature = "v1_10", feature = "dox")))]
        {
            let error = glib::Error::new(s.error, s.message);

            gst_sys::gst_message_new_warning(
                src,
                mut_override(error.to_glib_none().0),
                s.debug.to_glib_none().0,
            )
        }
    });
}

pub struct InfoBuilder<'a, T> {
    builder: MessageBuilder<'a>,
    error: T,
    message: &'a str,
    debug: Option<&'a str>,
    #[allow(unused)]
    details: Option<Structure>,
}
impl<'a, T: MessageErrorDomain> InfoBuilder<'a, T> {
    fn new(error: T, message: &'a str) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            error,
            message,
            debug: None,
            details: None,
        }
    }

    pub fn debug(self, debug: &'a str) -> Self {
        Self {
            debug: Some(debug),
            ..self
        }
    }

    #[cfg(any(feature = "v1_10", feature = "dox"))]
    pub fn details(self, details: Structure) -> Self {
        Self {
            details: Some(details),
            ..self
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| {
        #[cfg(any(feature = "v1_10", feature = "dox"))]
        {
            let details = match s.details.take() {
                None => ptr::null_mut(),
                Some(details) => details.into_ptr(),
            };

            let error = glib::Error::new(s.error, s.message);

            gst_sys::gst_message_new_info_with_details(
                src,
                mut_override(error.to_glib_none().0),
                s.debug.to_glib_none().0,
                details,
            )
        }
        #[cfg(not(any(feature = "v1_10", feature = "dox")))]
        {
            let error = glib::Error::new(s.error, s.message);

            gst_sys::gst_message_new_info(
                src,
                mut_override(error.to_glib_none().0),
                s.debug.to_glib_none().0,
            )
        }
    });
}

pub struct TagBuilder<'a> {
    builder: MessageBuilder<'a>,
    tags: &'a TagList,
}
impl<'a> TagBuilder<'a> {
    fn new(tags: &'a TagList) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            tags,
        }
    }

    message_builder_generic_impl!(|s: &Self, src| gst_sys::gst_message_new_tag(
        src,
        s.tags.to_glib_full()
    ));
}

pub struct BufferingBuilder<'a> {
    builder: MessageBuilder<'a>,
    percent: i32,
    stats: Option<(::BufferingMode, i32, i32, i64)>,
}
impl<'a> BufferingBuilder<'a> {
    fn new(percent: i32) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            percent,
            stats: None,
        }
    }

    pub fn stats(
        self,
        mode: ::BufferingMode,
        avg_in: i32,
        avg_out: i32,
        buffering_left: i64,
    ) -> Self {
        skip_assert_initialized!();
        Self {
            stats: Some((mode, avg_in, avg_out, buffering_left)),
            ..self
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| {
        let msg = gst_sys::gst_message_new_buffering(src, s.percent);

        if let Some((mode, avg_in, avg_out, buffering_left)) = s.stats {
            gst_sys::gst_message_set_buffering_stats(
                msg,
                mode.to_glib(),
                avg_in,
                avg_out,
                buffering_left,
            );
        }

        msg
    });
}

pub struct StateChangedBuilder<'a> {
    builder: MessageBuilder<'a>,
    old: ::State,
    new: ::State,
    pending: ::State,
}
impl<'a> StateChangedBuilder<'a> {
    fn new(old: ::State, new: ::State, pending: ::State) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            old,
            new,
            pending,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_state_changed(
        src,
        s.old.to_glib(),
        s.new.to_glib(),
        s.pending.to_glib(),
    ));
}

pub struct StateDirtyBuilder<'a> {
    builder: MessageBuilder<'a>,
}
impl<'a> StateDirtyBuilder<'a> {
    fn new() -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
        }
    }

    message_builder_generic_impl!(|_, src| gst_sys::gst_message_new_state_dirty(src));
}

pub struct StepDoneBuilder<'a> {
    builder: MessageBuilder<'a>,
    amount: GenericFormattedValue,
    rate: f64,
    flush: bool,
    intermediate: bool,
    duration: GenericFormattedValue,
    eos: bool,
}
impl<'a> StepDoneBuilder<'a> {
    fn new(
        amount: GenericFormattedValue,
        rate: f64,
        flush: bool,
        intermediate: bool,
        duration: GenericFormattedValue,
        eos: bool,
    ) -> Self {
        skip_assert_initialized!();
        assert_eq!(amount.get_format(), duration.get_format());
        Self {
            builder: MessageBuilder::new(),
            amount,
            rate,
            flush,
            intermediate,
            duration,
            eos,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_step_done(
        src,
        s.amount.get_format().to_glib(),
        s.amount.get_value() as u64,
        s.rate,
        s.flush.to_glib(),
        s.intermediate.to_glib(),
        s.duration.get_value() as u64,
        s.eos.to_glib(),
    ));
}

pub struct ClockProvideBuilder<'a> {
    builder: MessageBuilder<'a>,
    clock: &'a ::Clock,
    ready: bool,
}
impl<'a> ClockProvideBuilder<'a> {
    fn new(clock: &'a ::Clock, ready: bool) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            clock,
            ready,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_clock_provide(
        src,
        s.clock.to_glib_none().0,
        s.ready.to_glib()
    ));
}

pub struct ClockLostBuilder<'a> {
    builder: MessageBuilder<'a>,
    clock: &'a ::Clock,
}
impl<'a> ClockLostBuilder<'a> {
    fn new(clock: &'a ::Clock) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            clock,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_clock_lost(
        src,
        s.clock.to_glib_none().0
    ));
}

pub struct NewClockBuilder<'a> {
    builder: MessageBuilder<'a>,
    clock: &'a ::Clock,
}
impl<'a> NewClockBuilder<'a> {
    fn new(clock: &'a ::Clock) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            clock,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_new_clock(
        src,
        s.clock.to_glib_none().0
    ));
}

pub struct StructureChangeBuilder<'a> {
    builder: MessageBuilder<'a>,
    type_: ::StructureChangeType,
    owner: &'a ::Element,
    busy: bool,
}
impl<'a> StructureChangeBuilder<'a> {
    fn new(type_: ::StructureChangeType, owner: &'a ::Element, busy: bool) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            type_,
            owner,
            busy,
        }
    }

    message_builder_generic_impl!(
        |s: &mut Self, src| gst_sys::gst_message_new_structure_change(
            src,
            s.type_.to_glib(),
            s.owner.to_glib_none().0,
            s.busy.to_glib(),
        )
    );
}

pub struct StreamStatusBuilder<'a> {
    builder: MessageBuilder<'a>,
    type_: ::StreamStatusType,
    owner: &'a ::Element,
    status_object: Option<&'a dyn glib::ToSendValue>,
}
impl<'a> StreamStatusBuilder<'a> {
    fn new(type_: ::StreamStatusType, owner: &'a ::Element) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            type_,
            owner,
            status_object: None,
        }
    }

    pub fn status_object(self, status_object: &'a dyn glib::ToSendValue) -> Self {
        Self {
            status_object: Some(status_object),
            ..self
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| {
        let msg = gst_sys::gst_message_new_stream_status(
            src,
            s.type_.to_glib(),
            s.owner.to_glib_none().0,
        );
        if let Some(status_object) = s.status_object {
            gst_sys::gst_message_set_stream_status_object(
                msg,
                status_object.to_send_value().to_glib_none().0,
            );
        }
        msg
    });
}

pub struct ApplicationBuilder<'a> {
    builder: MessageBuilder<'a>,
    structure: Option<::Structure>,
}
impl<'a> ApplicationBuilder<'a> {
    fn new(structure: ::Structure) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            structure: Some(structure),
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_application(
        src,
        s.structure.take().unwrap().into_ptr()
    ));
}

pub struct ElementBuilder<'a> {
    builder: MessageBuilder<'a>,
    structure: Option<::Structure>,
}
impl<'a> ElementBuilder<'a> {
    fn new(structure: ::Structure) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            structure: Some(structure),
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_element(
        src,
        s.structure.take().unwrap().into_ptr()
    ));
}

pub struct SegmentStartBuilder<'a> {
    builder: MessageBuilder<'a>,
    position: GenericFormattedValue,
}
impl<'a> SegmentStartBuilder<'a> {
    fn new(position: GenericFormattedValue) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            position,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_segment_start(
        src,
        s.position.get_format().to_glib(),
        s.position.get_value(),
    ));
}

pub struct SegmentDoneBuilder<'a> {
    builder: MessageBuilder<'a>,
    position: GenericFormattedValue,
}
impl<'a> SegmentDoneBuilder<'a> {
    fn new(position: GenericFormattedValue) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            position,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_segment_done(
        src,
        s.position.get_format().to_glib(),
        s.position.get_value(),
    ));
}

pub struct DurationChangedBuilder<'a> {
    builder: MessageBuilder<'a>,
}
impl<'a> DurationChangedBuilder<'a> {
    fn new() -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
        }
    }

    message_builder_generic_impl!(|_, src| gst_sys::gst_message_new_duration_changed(src));
}

pub struct LatencyBuilder<'a> {
    builder: MessageBuilder<'a>,
}
impl<'a> LatencyBuilder<'a> {
    fn new() -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
        }
    }

    message_builder_generic_impl!(|_, src| gst_sys::gst_message_new_latency(src));
}

pub struct AsyncStartBuilder<'a> {
    builder: MessageBuilder<'a>,
}
impl<'a> AsyncStartBuilder<'a> {
    fn new() -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
        }
    }

    message_builder_generic_impl!(|_, src| gst_sys::gst_message_new_async_start(src));
}

pub struct AsyncDoneBuilder<'a> {
    builder: MessageBuilder<'a>,
    running_time: ::ClockTime,
}
impl<'a> AsyncDoneBuilder<'a> {
    fn new(running_time: ::ClockTime) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            running_time,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_async_done(
        src,
        s.running_time.to_glib()
    ));
}

pub struct RequestStateBuilder<'a> {
    builder: MessageBuilder<'a>,
    state: ::State,
}
impl<'a> RequestStateBuilder<'a> {
    fn new(state: ::State) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            state,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_request_state(
        src,
        s.state.to_glib()
    ));
}

pub struct StepStartBuilder<'a> {
    builder: MessageBuilder<'a>,
    active: bool,
    amount: GenericFormattedValue,
    rate: f64,
    flush: bool,
    intermediate: bool,
}
impl<'a> StepStartBuilder<'a> {
    fn new(
        active: bool,
        amount: GenericFormattedValue,
        rate: f64,
        flush: bool,
        intermediate: bool,
    ) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            active,
            amount,
            rate,
            flush,
            intermediate,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_step_start(
        src,
        s.active.to_glib(),
        s.amount.get_format().to_glib(),
        s.amount.get_value() as u64,
        s.rate,
        s.flush.to_glib(),
        s.intermediate.to_glib(),
    ));
}

pub struct QosBuilder<'a> {
    builder: MessageBuilder<'a>,
    live: bool,
    running_time: ::ClockTime,
    stream_time: ::ClockTime,
    timestamp: ::ClockTime,
    duration: ::ClockTime,
    values: Option<(i64, f64, i32)>,
    stats: Option<(GenericFormattedValue, GenericFormattedValue)>,
}
impl<'a> QosBuilder<'a> {
    fn new(
        live: bool,
        running_time: ::ClockTime,
        stream_time: ::ClockTime,
        timestamp: ::ClockTime,
        duration: ::ClockTime,
    ) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            live,
            running_time,
            stream_time,
            timestamp,
            duration,
            values: None,
            stats: None,
        }
    }

    pub fn values(self, jitter: i64, proportion: f64, quality: i32) -> Self {
        Self {
            values: Some((jitter, proportion, quality)),
            ..self
        }
    }

    pub fn stats<V: Into<GenericFormattedValue>>(self, processed: V, dropped: V) -> Self {
        let processed = processed.into();
        let dropped = dropped.into();
        assert_eq!(processed.get_format(), dropped.get_format());
        Self {
            stats: Some((processed, dropped)),
            ..self
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| {
        let msg = gst_sys::gst_message_new_qos(
            src,
            s.live.to_glib(),
            s.running_time.to_glib(),
            s.stream_time.to_glib(),
            s.timestamp.to_glib(),
            s.duration.to_glib(),
        );
        if let Some((jitter, proportion, quality)) = s.values {
            gst_sys::gst_message_set_qos_values(msg, jitter, proportion, quality);
        }
        if let Some((processed, dropped)) = s.stats {
            gst_sys::gst_message_set_qos_stats(
                msg,
                processed.get_format().to_glib(),
                processed.get_value() as u64,
                dropped.get_value() as u64,
            );
        }
        msg
    });
}

pub struct ProgressBuilder<'a> {
    builder: MessageBuilder<'a>,
    type_: ::ProgressType,
    code: &'a str,
    text: &'a str,
}
impl<'a> ProgressBuilder<'a> {
    fn new(type_: ::ProgressType, code: &'a str, text: &'a str) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            type_,
            code,
            text,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_progress(
        src,
        s.type_.to_glib(),
        s.code.to_glib_none().0,
        s.text.to_glib_none().0,
    ));
}

pub struct TocBuilder<'a> {
    builder: MessageBuilder<'a>,
    toc: &'a ::Toc,
    updated: bool,
}
impl<'a> TocBuilder<'a> {
    fn new(toc: &'a ::Toc, updated: bool) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            toc,
            updated,
        }
    }

    message_builder_generic_impl!(|s: &Self, src| gst_sys::gst_message_new_toc(
        src,
        s.toc.to_glib_none().0,
        s.updated.to_glib()
    ));
}

pub struct ResetTimeBuilder<'a> {
    builder: MessageBuilder<'a>,
    running_time: ::ClockTime,
}
impl<'a> ResetTimeBuilder<'a> {
    fn new(running_time: ::ClockTime) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            running_time,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_reset_time(
        src,
        s.running_time.to_glib()
    ));
}

pub struct StreamStartBuilder<'a> {
    builder: MessageBuilder<'a>,
    group_id: Option<GroupId>,
}
impl<'a> StreamStartBuilder<'a> {
    fn new() -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            group_id: None,
        }
    }

    pub fn group_id(self, group_id: GroupId) -> Self {
        Self {
            group_id: Some(group_id),
            ..self
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| {
        let msg = gst_sys::gst_message_new_stream_start(src);
        if let Some(group_id) = s.group_id {
            gst_sys::gst_message_set_group_id(msg, group_id.to_glib());
        }
        msg
    });
}

pub struct NeedContextBuilder<'a> {
    builder: MessageBuilder<'a>,
    context_type: &'a str,
}
impl<'a> NeedContextBuilder<'a> {
    fn new(context_type: &'a str) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            context_type,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_need_context(
        src,
        s.context_type.to_glib_none().0
    ));
}

pub struct HaveContextBuilder<'a> {
    builder: MessageBuilder<'a>,
    context: Option<::Context>,
}
impl<'a> HaveContextBuilder<'a> {
    fn new(context: ::Context) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            context: Some(context),
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| {
        let context = s.context.take().unwrap();
        gst_sys::gst_message_new_have_context(src, context.into_ptr())
    });
}

pub struct DeviceAddedBuilder<'a> {
    builder: MessageBuilder<'a>,
    device: &'a ::Device,
}
impl<'a> DeviceAddedBuilder<'a> {
    fn new(device: &'a ::Device) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            device,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_device_added(
        src,
        s.device.to_glib_none().0
    ));
}

pub struct DeviceRemovedBuilder<'a> {
    builder: MessageBuilder<'a>,
    device: &'a ::Device,
}
impl<'a> DeviceRemovedBuilder<'a> {
    fn new(device: &'a ::Device) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            device,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_device_removed(
        src,
        s.device.to_glib_none().0
    ));
}

#[cfg(any(feature = "v1_10", feature = "dox"))]
pub struct PropertyNotifyBuilder<'a> {
    builder: MessageBuilder<'a>,
    property_name: &'a str,
    value: Option<&'a dyn glib::ToSendValue>,
}
#[cfg(any(feature = "v1_10", feature = "dox"))]
impl<'a> PropertyNotifyBuilder<'a> {
    fn new(property_name: &'a str) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            property_name,
            value: None,
        }
    }

    pub fn value(self, value: &'a dyn glib::ToSendValue) -> Self {
        Self {
            value: Some(value),
            ..self
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| {
        let val = s.value.map(|v| v.to_send_value());
        gst_sys::gst_message_new_property_notify(
            src,
            s.property_name.to_glib_none().0,
            mut_override(
                val.as_ref()
                    .map(|v| v.to_glib_none().0)
                    .unwrap_or(ptr::null()),
            ),
        )
    });
}

#[cfg(any(feature = "v1_10", feature = "dox"))]
pub struct StreamCollectionBuilder<'a> {
    builder: MessageBuilder<'a>,
    collection: &'a ::StreamCollection,
}
#[cfg(any(feature = "v1_10", feature = "dox"))]
impl<'a> StreamCollectionBuilder<'a> {
    fn new(collection: &'a ::StreamCollection) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            collection,
        }
    }

    message_builder_generic_impl!(
        |s: &mut Self, src| gst_sys::gst_message_new_stream_collection(
            src,
            s.collection.to_glib_none().0
        )
    );
}

#[cfg(any(feature = "v1_10", feature = "dox"))]
pub struct StreamsSelectedBuilder<'a> {
    builder: MessageBuilder<'a>,
    #[cfg(any(feature = "v1_10", feature = "dox"))]
    collection: &'a ::StreamCollection,
    #[cfg(any(feature = "v1_10", feature = "dox"))]
    streams: Option<&'a [&'a ::Stream]>,
}
#[cfg(any(feature = "v1_10", feature = "dox"))]
impl<'a> StreamsSelectedBuilder<'a> {
    fn new(collection: &'a ::StreamCollection) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            collection,
            streams: None,
        }
    }

    pub fn streams(self, streams: &'a [&'a ::Stream]) -> Self {
        Self {
            streams: Some(streams),
            ..self
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| {
        let msg = gst_sys::gst_message_new_streams_selected(src, s.collection.to_glib_none().0);
        if let Some(streams) = s.streams {
            for stream in streams {
                gst_sys::gst_message_streams_selected_add(msg, stream.to_glib_none().0);
            }
        }
        msg
    });
}

#[cfg(any(feature = "v1_10", feature = "dox"))]
pub struct RedirectBuilder<'a> {
    builder: MessageBuilder<'a>,
    location: &'a str,
    tag_list: Option<&'a TagList>,
    entry_struct: Option<Structure>,
    #[allow(clippy::type_complexity)]
    entries: Option<&'a [(&'a str, Option<&'a TagList>, Option<&'a Structure>)]>,
}
#[cfg(any(feature = "v1_10", feature = "dox"))]
impl<'a> RedirectBuilder<'a> {
    fn new(location: &'a str) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            location,
            tag_list: None,
            entry_struct: None,
            entries: None,
        }
    }

    pub fn tag_list(self, tag_list: &'a TagList) -> Self {
        Self {
            tag_list: Some(tag_list),
            ..self
        }
    }

    pub fn entry_struct(self, entry_struct: Structure) -> Self {
        Self {
            entry_struct: Some(entry_struct),
            ..self
        }
    }

    pub fn entries(
        self,
        entries: &'a [(&'a str, Option<&'a TagList>, Option<&'a Structure>)],
    ) -> Self {
        skip_assert_initialized!();
        Self {
            entries: Some(entries),
            ..self
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| {
        let entry_struct = s.entry_struct.take();
        let entry_struct_ptr = if let Some(entry_struct) = entry_struct {
            entry_struct.into_ptr()
        } else {
            ptr::null_mut()
        };

        let msg = gst_sys::gst_message_new_redirect(
            src,
            s.location.to_glib_none().0,
            s.tag_list.to_glib_full(),
            entry_struct_ptr,
        );
        if let Some(entries) = s.entries {
            for &(location, tag_list, entry_struct) in entries {
                let entry_struct = entry_struct.cloned();
                let entry_struct_ptr = if let Some(entry_struct) = entry_struct {
                    entry_struct.into_ptr()
                } else {
                    ptr::null_mut()
                };
                gst_sys::gst_message_add_redirect_entry(
                    msg,
                    location.to_glib_none().0,
                    tag_list.to_glib_full(),
                    entry_struct_ptr,
                );
            }
        }
        msg
    });
}

#[cfg(any(feature = "v1_16", feature = "dox"))]
pub struct DeviceChangedBuilder<'a> {
    builder: MessageBuilder<'a>,
    device: &'a ::Device,
    changed_device: &'a ::Device,
}
#[cfg(any(feature = "v1_16", feature = "dox"))]
impl<'a> DeviceChangedBuilder<'a> {
    fn new(device: &'a ::Device, changed_device: &'a ::Device) -> Self {
        skip_assert_initialized!();
        Self {
            builder: MessageBuilder::new(),
            device,
            changed_device,
        }
    }

    message_builder_generic_impl!(|s: &mut Self, src| gst_sys::gst_message_new_device_changed(
        src,
        s.device.to_glib_none().0,
        s.changed_device.to_glib_none().0,
    ));
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple() {
        ::init().unwrap();

        // Message without arguments
        let eos_msg = Message::new_eos().seqnum(Seqnum(1)).build();
        match eos_msg.view() {
            MessageView::Eos(eos_msg) => {
                assert_eq!(eos_msg.get_seqnum(), Seqnum(1));
                assert!(eos_msg.get_structure().is_none());
            }
            _ => panic!("eos_msg.view() is not a MessageView::Eos(_)"),
        }

        // Message with arguments
        let buffering_msg = Message::new_buffering(42).build();
        match buffering_msg.view() {
            MessageView::Buffering(buffering_msg) => {
                assert_eq!(buffering_msg.get_percent(), 42);
            }
            _ => panic!("buffering_msg.view() is not a MessageView::Buffering(_)"),
        }
    }

    #[cfg(feature = "v1_14")]
    #[test]
    fn test_other_fields() {
        ::init().unwrap();

        let eos_msg = Message::new_eos()
            .other_fields(&[("extra-field", &true)])
            .seqnum(Seqnum(1))
            .build();
        match eos_msg.view() {
            MessageView::Eos(eos_msg) => {
                assert_eq!(eos_msg.get_seqnum(), Seqnum(1));
                if let Some(other_fields) = eos_msg.get_structure() {
                    assert!(other_fields.has_field("extra-field"));
                }
            }
            _ => panic!("eos_msg.view() is not a MessageView::Eos(_)"),
        }

        let buffering_msg = Message::new_buffering(42)
            .other_fields(&[("extra-field", &true)])
            .build();
        match buffering_msg.view() {
            MessageView::Buffering(buffering_msg) => {
                assert_eq!(buffering_msg.get_percent(), 42);
                if let Some(other_fields) = buffering_msg.get_structure() {
                    assert!(other_fields.has_field("extra-field"));
                }
            }
            _ => panic!("buffering_msg.view() is not a MessageView::Buffering(_)"),
        }
    }
}