aboutsummaryrefslogtreecommitdiffstats
path: root/src/coding/gsm0503_coding.c
blob: 9c189cdd90eb4af8e90372bb67c929cb87573cc1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
/*
 * (C) 2013 by Andreas Eversberg <jolly@eversberg.eu>
 * (C) 2015 by Alexander Chemeris <Alexander.Chemeris@fairwaves.co>
 * (C) 2016 by Tom Tsou <tom.tsou@ettus.com>
 * (C) 2017 by Harald Welte <laforge@gnumonks.org>
 *
 * All Rights Reserved
 *
 * SPDX-License-Identifier: GPL-2.0+
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

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

#include <osmocom/core/bits.h>
#include <osmocom/core/conv.h>
#include <osmocom/core/utils.h>
#include <osmocom/core/crcgen.h>
#include <osmocom/core/endian.h>

#include <osmocom/gprs/protocol/gsm_04_60.h>
#include <osmocom/gprs/gprs_rlc.h>

#include <osmocom/gsm/protocol/gsm_04_08.h>
#include <osmocom/gsm/gsm0503.h>
#include <osmocom/codec/codec.h>

#include <osmocom/coding/gsm0503_interleaving.h>
#include <osmocom/coding/gsm0503_mapping.h>
#include <osmocom/coding/gsm0503_tables.h>
#include <osmocom/coding/gsm0503_coding.h>
#include <osmocom/coding/gsm0503_parity.h>
#include <osmocom/coding/gsm0503_amr_dtx.h>

/*! \mainpage libosmocoding Documentation
 *
 * \section sec_intro Introduction
 * This library is a collection of definitions, tables and functions
 * implementing the GSM/GPRS/EGPRS channel coding (and decoding) as
 * specified in 3GPP TS 05.03 / 45.003.
 *
 * libosmocoding is developed as part of the Osmocom (Open Source Mobile
 * Communications) project, a community-based, collaborative development
 * project to create Free and Open Source implementations of mobile
 * communications systems.  For more information about Osmocom, please
 * see https://osmocom.org/
 *
 * \section sec_copyright Copyright and License
 * Copyright © 2013 by Andreas Eversberg\n
 * Copyright © 2015 by Alexander Chemeris\n
 * Copyright © 2016 by Tom Tsou\n
 * Documentation Copyright © 2017 by Harald Welte\n
 * All rights reserved. \n\n
 * The source code of libosmocoding is licensed under the terms of the GNU
 * General Public License as published by the Free Software Foundation;
 * either version 2 of the License, or (at your option) any later
 * version.\n
 * See <http://www.gnu.org/licenses/> or COPYING included in the source
 * code package istelf.\n
 * The information detailed here is provided AS IS with NO WARRANTY OF
 * ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE.
 * \n\n
 *
 * \section sec_tracker Homepage + Issue Tracker
 * libosmocoding is distributed as part of libosmocore and shares its
 * project page at http://osmocom.org/projects/libosmocore
 *
 * An Issue Tracker can be found at
 * https://osmocom.org/projects/libosmocore/issues
 *
 * \section sec_contact Contact and Support
 * Community-based support is available at the OpenBSC mailing list
 * <http://lists.osmocom.org/mailman/listinfo/openbsc>\n
 * Commercial support options available upon request from
 * <http://sysmocom.de/>
 */


/*! \addtogroup coding
 *  @{
 *
 *  GSM TS 05.03 coding
 *
 *  This module is the "master module" of libosmocoding. It uses the
 *  various other modules (mapping, parity, interleaving) in order to
 *  implement the complete channel coding (and decoding) chain for the
 *  various channel types as defined in TS 05.03 / 45.003.
 *
 * \file gsm0503_coding.c */

/*
 * EGPRS coding limits
 */

/* Max header size with parity bits */
#define EGPRS_HDR_UPP_MAX	54

/* Max encoded header size */
#define EGPRS_HDR_C_MAX		162

/* Max punctured header size */
#define EGPRS_HDR_HC_MAX	160

/* Max data block size with parity bits */
#define EGPRS_DATA_U_MAX	612

/* Max encoded data block size */
#define EGPRS_DATA_C_MAX	1836

/* Max single block punctured data size */
#define EGPRS_DATA_DC_MAX	1248

/* Dual block punctured data size */
#define EGPRS_DATA_C1		612
#define EGPRS_DATA_C2		EGPRS_DATA_C1

/*! union across the three different EGPRS Uplink header types */
union gprs_rlc_ul_hdr_egprs {
	struct gprs_rlc_ul_header_egprs_1 type1;
	struct gprs_rlc_ul_header_egprs_2 type2;
	struct gprs_rlc_ul_header_egprs_3 type3;
};

/*! union across the three different EGPRS Downlink header types */
union gprs_rlc_dl_hdr_egprs {
	struct gprs_rlc_dl_header_egprs_1 type1;
	struct gprs_rlc_dl_header_egprs_2 type2;
	struct gprs_rlc_dl_header_egprs_3 type3;
};

/*! Structure describing a Modulation and Coding Scheme */
struct gsm0503_mcs_code {
	/*! Modulation and Coding Scheme (MSC) number */
	uint8_t mcs;
	/*! Length of Uplink Stealing Flag (USF) in bits */
	uint8_t usf_len;

	/* Header coding */
	/*! Length of header (bits) */
	uint8_t hdr_len;
	/*! Length of header convolutional code */
	uint8_t hdr_code_len;
	/*! Length of header code puncturing sequence */
	uint8_t hdr_punc_len;
	/*! header convolutional code */
	const struct osmo_conv_code *hdr_conv;
	/*! header puncturing sequence */
	const uint8_t *hdr_punc;

	/* Data coding */
	/*! length of data (bits) */
	uint16_t data_len;
	/*! length of data convolutional code */
	uint16_t data_code_len;
	/*! length of data code puncturing sequence */
	uint16_t data_punc_len;
	/*! data convolutional code */
	const struct osmo_conv_code *data_conv;
	/*! data puncturing sequences */
	const uint8_t *data_punc[3];
};

/*
 * EGPRS UL coding parameters
 */
const struct gsm0503_mcs_code gsm0503_mcs_ul_codes[EGPRS_NUM_MCS] = {
	{
		.mcs = EGPRS_MCS0,
	},
	{
		.mcs = EGPRS_MCS1,
		.hdr_len = 31,
		.hdr_code_len = 117,
		.hdr_punc_len = 80,
		.hdr_conv = &gsm0503_mcs1_ul_hdr,
		.hdr_punc = gsm0503_puncture_mcs1_ul_hdr,

		.data_len = 178,
		.data_code_len = 588,
		.data_punc_len = 372,
		.data_conv = &gsm0503_mcs1,
		.data_punc = {
			gsm0503_puncture_mcs1_p1,
			gsm0503_puncture_mcs1_p2,
			NULL,
		},
	},
	{
		.mcs = EGPRS_MCS2,
		.hdr_len = 31,
		.hdr_code_len = 117,
		.hdr_punc_len = 80,
		.hdr_conv = &gsm0503_mcs1_ul_hdr,
		.hdr_punc = gsm0503_puncture_mcs1_ul_hdr,

		.data_len = 226,
		.data_code_len = 732,
		.data_punc_len = 372,
		.data_conv = &gsm0503_mcs2,
		.data_punc = {
			gsm0503_puncture_mcs2_p1,
			gsm0503_puncture_mcs2_p2,
			NULL,
		},
	},
	{
		.mcs = EGPRS_MCS3,
		.hdr_len = 31,
		.hdr_code_len = 117,
		.hdr_punc_len = 80,
		.hdr_conv = &gsm0503_mcs1_ul_hdr,
		.hdr_punc = gsm0503_puncture_mcs1_ul_hdr,

		.data_len = 298,
		.data_code_len = 948,
		.data_punc_len = 372,
		.data_conv = &gsm0503_mcs3,
		.data_punc = {
			gsm0503_puncture_mcs3_p1,
			gsm0503_puncture_mcs3_p2,
			gsm0503_puncture_mcs3_p3,
		},
	},
	{
		.mcs = EGPRS_MCS4,
		.hdr_len = 31,
		.hdr_code_len = 117,
		.hdr_punc_len = 80,
		.hdr_conv = &gsm0503_mcs1_ul_hdr,
		.hdr_punc = gsm0503_puncture_mcs1_ul_hdr,

		.data_len = 354,
		.data_code_len = 1116,
		.data_punc_len = 372,
		.data_conv = &gsm0503_mcs4,
		.data_punc = {
			gsm0503_puncture_mcs4_p1,
			gsm0503_puncture_mcs4_p2,
			gsm0503_puncture_mcs4_p3,
		},
	},
	{
		.mcs = EGPRS_MCS5,
		.hdr_len = 37,
		.hdr_code_len = 135,
		.hdr_punc_len = 136,
		.hdr_conv = &gsm0503_mcs5_ul_hdr,
		.hdr_punc = NULL,

		.data_len = 450,
		.data_code_len = 1404,
		.data_punc_len = 1248,
		.data_conv = &gsm0503_mcs5,
		.data_punc = {
			gsm0503_puncture_mcs5_p1,
			gsm0503_puncture_mcs5_p2,
			NULL,
		},
	},
	{
		.mcs = EGPRS_MCS6,
		.hdr_len = 37,
		.hdr_code_len = 135,
		.hdr_punc_len = 136,
		.hdr_conv = &gsm0503_mcs5_ul_hdr,
		.hdr_punc = NULL,

		.data_len = 594,
		.data_code_len = 1836,
		.data_punc_len = 1248,
		.data_conv = &gsm0503_mcs6,
		.data_punc = {
			gsm0503_puncture_mcs6_p1,
			gsm0503_puncture_mcs6_p2,
			NULL,
		},
	},
	{
		.mcs = EGPRS_MCS7,
		.hdr_len = 46,
		.hdr_code_len = 162,
		.hdr_punc_len = 160,
		.hdr_conv = &gsm0503_mcs7_ul_hdr,
		.hdr_punc = gsm0503_puncture_mcs7_ul_hdr,

		.data_len = 900,
		.data_code_len = 1404,
		.data_punc_len = 612,
		.data_conv = &gsm0503_mcs7,
		.data_punc = {
			gsm0503_puncture_mcs7_p1,
			gsm0503_puncture_mcs7_p2,
			gsm0503_puncture_mcs7_p3,
		}
	},
	{
		.mcs = EGPRS_MCS8,
		.hdr_len = 46,
		.hdr_code_len = 162,
		.hdr_punc_len = 160,
		.hdr_conv = &gsm0503_mcs7_ul_hdr,
		.hdr_punc = gsm0503_puncture_mcs7_ul_hdr,

		.data_len = 1092,
		.data_code_len = 1692,
		.data_punc_len = 612,
		.data_conv = &gsm0503_mcs8,
		.data_punc = {
			gsm0503_puncture_mcs8_p1,
			gsm0503_puncture_mcs8_p2,
			gsm0503_puncture_mcs8_p3,
		}
	},
	{
		.mcs = EGPRS_MCS9,
		.hdr_len = 46,
		.hdr_code_len = 162,
		.hdr_punc_len = 160,
		.hdr_conv = &gsm0503_mcs7_ul_hdr,
		.hdr_punc = gsm0503_puncture_mcs7_ul_hdr,

		.data_len = 1188,
		.data_code_len = 1836,
		.data_punc_len = 612,
		.data_conv = &gsm0503_mcs9,
		.data_punc = {
			gsm0503_puncture_mcs9_p1,
			gsm0503_puncture_mcs9_p2,
			gsm0503_puncture_mcs9_p3,
		}
	},
};

/*
 * EGPRS DL coding parameters
 */
const struct gsm0503_mcs_code gsm0503_mcs_dl_codes[EGPRS_NUM_MCS] = {
	{
		.mcs = EGPRS_MCS0,
	},
	{
		.mcs = EGPRS_MCS1,
		.usf_len = 3,
		.hdr_len = 28,
		.hdr_code_len = 108,
		.hdr_punc_len = 68,
		.hdr_conv = &gsm0503_mcs1_dl_hdr,
		.hdr_punc = gsm0503_puncture_mcs1_dl_hdr,

		.data_len = 178,
		.data_code_len = 588,
		.data_punc_len = 372,
		.data_conv = &gsm0503_mcs1,
		.data_punc = {
			gsm0503_puncture_mcs1_p1,
			gsm0503_puncture_mcs1_p2,
			NULL,
		},
	},
	{
		.mcs = EGPRS_MCS2,
		.usf_len = 3,
		.hdr_len = 28,
		.hdr_code_len = 108,
		.hdr_punc_len = 68,
		.hdr_conv = &gsm0503_mcs1_dl_hdr,
		.hdr_punc = gsm0503_puncture_mcs1_dl_hdr,

		.data_len = 226,
		.data_code_len = 732,
		.data_punc_len = 372,
		.data_conv = &gsm0503_mcs2,
		.data_punc = {
			gsm0503_puncture_mcs2_p1,
			gsm0503_puncture_mcs2_p2,
			NULL,
		},
	},
	{
		.mcs = EGPRS_MCS3,
		.usf_len = 3,
		.hdr_len = 28,
		.hdr_code_len = 108,
		.hdr_punc_len = 68,
		.hdr_conv = &gsm0503_mcs1_dl_hdr,
		.hdr_punc = gsm0503_puncture_mcs1_dl_hdr,

		.data_len = 298,
		.data_code_len = 948,
		.data_punc_len = 372,
		.data_conv = &gsm0503_mcs3,
		.data_punc = {
			gsm0503_puncture_mcs3_p1,
			gsm0503_puncture_mcs3_p2,
			gsm0503_puncture_mcs3_p3,
		},
	},
	{
		.mcs = EGPRS_MCS4,
		.usf_len = 3,
		.hdr_len = 28,
		.hdr_code_len = 108,
		.hdr_punc_len = 68,
		.hdr_conv = &gsm0503_mcs1_dl_hdr,
		.hdr_punc = gsm0503_puncture_mcs1_dl_hdr,

		.data_len = 354,
		.data_code_len = 1116,
		.data_punc_len = 372,
		.data_conv = &gsm0503_mcs4,
		.data_punc = {
			gsm0503_puncture_mcs4_p1,
			gsm0503_puncture_mcs4_p2,
			gsm0503_puncture_mcs4_p3,
		},
	},
	{
		.mcs = EGPRS_MCS5,
		.usf_len = 3,
		.hdr_len = 25,
		.hdr_code_len = 99,
		.hdr_punc_len = 100,
		.hdr_conv = &gsm0503_mcs5_dl_hdr,
		.hdr_punc = NULL,

		.data_len = 450,
		.data_code_len = 1404,
		.data_punc_len = 1248,
		.data_conv = &gsm0503_mcs5,
		.data_punc = {
			gsm0503_puncture_mcs5_p1,
			gsm0503_puncture_mcs5_p2,
			NULL,
		},
	},
	{
		.mcs = EGPRS_MCS6,
		.usf_len = 3,
		.hdr_len = 25,
		.hdr_code_len = 99,
		.hdr_punc_len = 100,
		.hdr_conv = &gsm0503_mcs5_dl_hdr,
		.hdr_punc = NULL,

		.data_len = 594,
		.data_code_len = 1836,
		.data_punc_len = 1248,
		.data_conv = &gsm0503_mcs6,
		.data_punc = {
			gsm0503_puncture_mcs6_p1,
			gsm0503_puncture_mcs6_p2,
			NULL,
		},
	},
	{
		.mcs = EGPRS_MCS7,
		.usf_len = 3,
		.hdr_len = 37,
		.hdr_code_len = 135,
		.hdr_punc_len = 124,
		.hdr_conv = &gsm0503_mcs7_dl_hdr,
		.hdr_punc = gsm0503_puncture_mcs7_dl_hdr,

		.data_len = 900,
		.data_code_len = 1404,
		.data_punc_len = 612,
		.data_conv = &gsm0503_mcs7,
		.data_punc = {
			gsm0503_puncture_mcs7_p1,
			gsm0503_puncture_mcs7_p2,
			gsm0503_puncture_mcs7_p3,
		}
	},
	{
		.mcs = EGPRS_MCS8,
		.usf_len = 3,
		.hdr_len = 37,
		.hdr_code_len = 135,
		.hdr_punc_len = 124,
		.hdr_conv = &gsm0503_mcs7_dl_hdr,
		.hdr_punc = gsm0503_puncture_mcs7_dl_hdr,

		.data_len = 1092,
		.data_code_len = 1692,
		.data_punc_len = 612,
		.data_conv = &gsm0503_mcs8,
		.data_punc = {
			gsm0503_puncture_mcs8_p1,
			gsm0503_puncture_mcs8_p2,
			gsm0503_puncture_mcs8_p3,
		}
	},
	{
		.mcs = EGPRS_MCS9,
		.usf_len = 3,
		.hdr_len = 37,
		.hdr_code_len = 135,
		.hdr_punc_len = 124,
		.hdr_conv = &gsm0503_mcs7_dl_hdr,
		.hdr_punc = gsm0503_puncture_mcs7_dl_hdr,

		.data_len = 1188,
		.data_code_len = 1836,
		.data_punc_len = 612,
		.data_conv = &gsm0503_mcs9,
		.data_punc = {
			gsm0503_puncture_mcs9_p1,
			gsm0503_puncture_mcs9_p2,
			gsm0503_puncture_mcs9_p3,
		}
	},
};

/*! Convolutional Decode + compute BER for punctured codes
 *  \param[in] code Description of Convolutional Code
 *  \param[in] input Input soft-bits (-127...127)
 *  \param[out] output bits
 *  \param[out] n_errors Number of bit-errors
 *  \param[out] n_bits_total Number of bits
 *  \param[in] data_punc Puncturing mask array. Can be NULL.
 */
static int osmo_conv_decode_ber_punctured(const struct osmo_conv_code *code,
	const sbit_t *input, ubit_t *output,
	int *n_errors, int *n_bits_total,
	const uint8_t *data_punc)
{
	int res, i, coded_len;
	ubit_t recoded[EGPRS_DATA_C_MAX];

	res = osmo_conv_decode(code, input, output);

	if (n_bits_total || n_errors) {
		coded_len = osmo_conv_encode(code, output, recoded);
		OSMO_ASSERT(sizeof(recoded) / sizeof(recoded[0]) >= coded_len);
	}

	/* Count bit errors */
	if (n_errors) {
		*n_errors = 0;
		for (i = 0; i < coded_len; i++) {
			if (((!data_punc) || (data_punc && !data_punc[i])) &&
				!((recoded[i] && input[i] < 0) ||
					(!recoded[i] && input[i] > 0)) )
						*n_errors += 1;
		}
	}

	if (n_bits_total)
		*n_bits_total = coded_len;

	return res;
}

/*! Convolutional Decode + compute BER for non-punctured codes
 *  \param[in] code Description of Convolutional Code
 *  \param[in] input Input soft-bits (-127...127)
 *  \param[out] output bits
 *  \param[out] n_errors Number of bit-errors
 *  \param[out] n_bits_total Number of bits
 */
static int osmo_conv_decode_ber(const struct osmo_conv_code *code,
	const sbit_t *input, ubit_t *output,
	int *n_errors, int *n_bits_total)
{
	return osmo_conv_decode_ber_punctured(code, input, output,
		n_errors, n_bits_total, NULL);
}

/*! convenience wrapper for decoding coded bits
 *  \param[out] l2_data caller-allocated buffer for L2 Frame
 *  \param[in] cB 456 coded (soft) bits as per TS 05.03 4.1.3
 *  \param[out] n_errors Number of detected errors
 *  \param[out] n_bits_total Number of total coded bits
 *  \returns 0 on success; -1 on CRC error */
static int _xcch_decode_cB(uint8_t *l2_data, const sbit_t *cB,
	int *n_errors, int *n_bits_total)
{
	ubit_t conv[224];
	int rv;

	osmo_conv_decode_ber(&gsm0503_xcch, cB,
		conv, n_errors, n_bits_total);

	rv = osmo_crc64gen_check_bits(&gsm0503_fire_crc40,
		conv, 184, conv + 184);
	if (rv)
		return -1;

	osmo_ubit2pbit_ext(l2_data, 0, conv, 0, 184, 1);

	return 0;
}

/*! convenience wrapper for encoding to coded bits
 *  \param[out] cB caller-allocated buffer for 456 coded bits as per TS 05.03 4.1.3
 *  \param[out] l2_data to-be-encoded L2 Frame
 *  \returns 0 */
static int _xcch_encode_cB(ubit_t *cB, const uint8_t *l2_data)
{
	ubit_t conv[224];

	osmo_pbit2ubit_ext(conv, 0, l2_data, 0, 184, 1);

	osmo_crc64gen_set_bits(&gsm0503_fire_crc40, conv, 184, conv + 184);

	osmo_conv_encode(&gsm0503_xcch, conv, cB);

	return 0;
}

/*
 * GSM xCCH block transcoding
 */

/*! Decoding of xCCH data from bursts to L2 frame
 *  \param[out] l2_data caller-allocated output data buffer
 *  \param[in] bursts four GSM bursts in soft-bits
 *  \param[out] n_errors Number of detected errors
 *  \param[out] n_bits_total Number of total coded bits
 */
int gsm0503_xcch_decode(uint8_t *l2_data, const sbit_t *bursts,
	int *n_errors, int *n_bits_total)
{
	sbit_t iB[456], cB[456];
	int i;

	for (i = 0; i < 4; i++)
		gsm0503_xcch_burst_unmap(&iB[i * 114], &bursts[i * 116], NULL, NULL);

	gsm0503_xcch_deinterleave(cB, iB);

	return _xcch_decode_cB(l2_data, cB, n_errors, n_bits_total);
}

/*! Encoding of xCCH data from L2 frame to bursts
 *  \param[out] bursts caller-allocated burst data (unpacked bits)
 *  \param[in] l2_data L2 input data (MAC block)
 *  \returns 0
 */
int gsm0503_xcch_encode(ubit_t *bursts, const uint8_t *l2_data)
{
	ubit_t iB[456], cB[456], hl = 1, hn = 1;
	int i;

	_xcch_encode_cB(cB, l2_data);

	gsm0503_xcch_interleave(cB, iB);

	for (i = 0; i < 4; i++)
		gsm0503_xcch_burst_map(&iB[i * 114], &bursts[i * 116], &hl, &hn);

	return 0;
}

/*
 * EGPRS PDTCH UL block decoding
 */

/*
 * Type 3 - MCS-1,2,3,4
 * Unmapping and deinterleaving
 */
static int egprs_type3_unmap(const sbit_t *bursts, sbit_t *hc, sbit_t *dc)
{
	int i;
	sbit_t iB[456], q[8];

	for (i = 0; i < 4; i++) {
		gsm0503_xcch_burst_unmap(&iB[i * 114], &bursts[i * 116],
			q + i * 2, q + i * 2 + 1);
	}

	gsm0503_mcs1_ul_deinterleave(hc, dc, iB);

	return 0;
}

/*
 * Type 2 - MCS-5,6
 * Unmapping and deinterleaving
 */
static int egprs_type2_unmap(const sbit_t *bursts, sbit_t *hc, sbit_t *dc)
{
	int i;
	sbit_t burst[348];
	sbit_t hi[EGPRS_HDR_HC_MAX];
	sbit_t di[EGPRS_DATA_DC_MAX];

	for (i = 0; i < 4; i++) {
		memcpy(burst, &bursts[i * 348], 348);

		gsm0503_mcs5_burst_swap(burst);
		gsm0503_mcs5_ul_burst_unmap(di, burst, hi, i);
	}

	gsm0503_mcs5_ul_deinterleave(hc, dc, hi, di);

	return 0;
}

/*
 * Type 1 - MCS-7,8,9
 * Unmapping and deinterleaving - Note that MCS-7 interleaver is unique
 */
static int egprs_type1_unmap(const sbit_t *bursts, sbit_t *hc,
	sbit_t *c1, sbit_t *c2, int msc)
{
	int i;
	sbit_t burst[348];
	sbit_t hi[EGPRS_HDR_HC_MAX];
	sbit_t di[EGPRS_DATA_C1 * 2];

	for (i = 0; i < 4; i++) {
		memcpy(burst, &bursts[i * 348], 348);

		gsm0503_mcs5_burst_swap(burst);
		gsm0503_mcs7_ul_burst_unmap(di, burst, hi, i);
	}

	if (msc == EGPRS_MCS7)
		gsm0503_mcs7_ul_deinterleave(hc, c1, c2, hi, di);
	else
		gsm0503_mcs8_ul_deinterleave(hc, c1, c2, hi, di);

	return 0;
}

/*
 * Decode EGPRS UL header section
 *
 * 1. Depuncture
 * 2. Convolutional decoding
 * 3. CRC check
 */
static int _egprs_decode_hdr(const sbit_t *hc, int mcs,
	union gprs_rlc_ul_hdr_egprs *hdr)
{
	sbit_t C[EGPRS_HDR_C_MAX];
	ubit_t upp[EGPRS_HDR_UPP_MAX];
	int i, j, rc;
	const struct gsm0503_mcs_code *code;

	code = &gsm0503_mcs_ul_codes[mcs];

	/* Skip depuncturing on MCS-5,6 header */
	if ((mcs == EGPRS_MCS5) || (mcs == EGPRS_MCS6)) {
		memcpy(C, hc, code->hdr_code_len);
		goto hdr_conv_decode;
	}

	if (!code->hdr_punc) {
		/* Invalid MCS-X header puncture matrix */
		return -1;
	}

	i = code->hdr_code_len - 1;
	j = code->hdr_punc_len - 1;

	for (; i >= 0; i--) {
		if (!code->hdr_punc[i])
			C[i] = hc[j--];
		else
			C[i] = 0;
	}

hdr_conv_decode:
	osmo_conv_decode_ber(code->hdr_conv, C, upp, NULL, NULL);
	rc = osmo_crc8gen_check_bits(&gsm0503_mcs_crc8_hdr, upp,
		code->hdr_len, upp + code->hdr_len);
	if (rc)
		return -1;

	osmo_ubit2pbit_ext((pbit_t *) hdr, 0, upp, 0, code->hdr_len, 1);

	return 0;
}

/*
 * Blind MCS header decoding based on burst length and CRC validation.
 * Ignore 'q' value coding identification. This approach provides
 * the strongest chance of header recovery.
 */
static int egprs_decode_hdr(union gprs_rlc_ul_hdr_egprs *hdr,
	const sbit_t *bursts, uint16_t nbits)
{
	int rc;
	sbit_t hc[EGPRS_HDR_HC_MAX];

	if (nbits == GSM0503_GPRS_BURSTS_NBITS) {
		/* MCS-1,2,3,4 */
		egprs_type3_unmap(bursts, hc, NULL);
		rc = _egprs_decode_hdr(hc, EGPRS_MCS1, hdr);
		if (!rc)
			return EGPRS_HDR_TYPE3;
	} else if (nbits == GSM0503_EGPRS_BURSTS_NBITS) {
		/* MCS-5,6 */
		egprs_type2_unmap(bursts, hc, NULL);
		rc = _egprs_decode_hdr(hc, EGPRS_MCS5, hdr);
		if (!rc)
			return EGPRS_HDR_TYPE2;

		/* MCS-7,8,9 */
		egprs_type1_unmap(bursts, hc, NULL, NULL, EGPRS_MCS7);
		rc = _egprs_decode_hdr(hc, EGPRS_MCS7, hdr);
		if (!rc)
			return EGPRS_HDR_TYPE1;
	}

	return -1;
}

/*
 * Parse EGPRS UL header for coding and puncturing scheme (CPS)
 *
 * Type 1 - MCS-7,8,9
 * Type 2 - MCS-5,6
 * Type 3 - MCS-1,2,3,4
 */
static int egprs_parse_ul_cps(struct egprs_cps *cps,
	union gprs_rlc_ul_hdr_egprs *hdr, int type)
{
	uint8_t bits;

	switch (type) {
	case EGPRS_HDR_TYPE1:
		bits = hdr->type1.cps;
		break;
	case EGPRS_HDR_TYPE2:
		bits = (hdr->type2.cps_lo << 2) | hdr->type2.cps_hi;
		break;
	case EGPRS_HDR_TYPE3:
		bits = (hdr->type3.cps_lo << 2) | hdr->type3.cps_hi;
		break;
	default:
		return -1;
	}

	return egprs_get_cps(cps, type, bits);
}

/*
 * Decode EGPRS UL data section
 *
 * 1. Depuncture
 * 2. Convolutional decoding
 * 3. CRC check
 * 4. Block combining (MCS-7,8,9 only)
 */
static int egprs_decode_data(uint8_t *l2_data, const sbit_t *c,
	int mcs, int p, int blk, int *n_errors, int *n_bits_total)
{
	ubit_t u[EGPRS_DATA_U_MAX];
	sbit_t C[EGPRS_DATA_C_MAX];

	int i, j, rc, data_len;
	const struct gsm0503_mcs_code *code;

	if (blk && mcs < EGPRS_MCS7) {
		/* Invalid MCS-X block state */
		return -1;
	}

	code = &gsm0503_mcs_ul_codes[mcs];
	if (!code->data_punc[p]) {
		/* Invalid MCS-X data puncture matrix */
		return -1;
	}

	/*
	 * MCS-1,6 - single block processing
	 * MCS-7,9 - dual block processing
	 */
	if (mcs >= EGPRS_MCS7)
		data_len = code->data_len / 2;
	else
		data_len = code->data_len;

	i = code->data_code_len - 1;
	j = code->data_punc_len - 1;

	for (; i >= 0; i--) {
		if (!code->data_punc[p][i])
			C[i] = c[j--];
		else
			C[i] = 0;
	}

	osmo_conv_decode_ber_punctured(code->data_conv, C, u,
		n_errors, n_bits_total, code->data_punc[p]);
	rc = osmo_crc16gen_check_bits(&gsm0503_mcs_crc12, u,
		data_len, u + data_len);
	if (rc)
		return -1;

	/* Offsets output pointer on the second block of Type 1 MCS */
	osmo_ubit2pbit_ext(l2_data, code->hdr_len + blk * data_len,
		u, 0, data_len, 1);

	/* Return the number of bytes required for the bit message */
	return OSMO_BYTES_FOR_BITS(code->hdr_len + code->data_len);
}

/*! Decode EGPRS UL message
 * 	1. Header section decoding
 * 	2. Extract CPS settings
 * 	3. Burst unmapping and deinterleaving
 * 	4. Data section decoding
 *  \param[out] l2_data caller-allocated buffer for L2 Frame
 *  \param[in] bursts burst input data as soft unpacked bits
 *  \param[in] nbits number of bits in \a bursts
 *  \param usf_p unused argument ?!?
 *  \param[out] n_errors number of detected bit-errors
 *  \param[out] n_bits_total total number of decoded bits
 *  \returns 0 on success; negative on error */
int gsm0503_pdtch_egprs_decode(uint8_t *l2_data, const sbit_t *bursts, uint16_t nbits,
	uint8_t *usf_p, int *n_errors, int *n_bits_total)
{
	sbit_t dc[EGPRS_DATA_DC_MAX];
	sbit_t c1[EGPRS_DATA_C1], c2[EGPRS_DATA_C2];
	int type, rc;
	struct egprs_cps cps;
	union gprs_rlc_ul_hdr_egprs *hdr;

	if (n_errors)
		*n_errors = 0;
	if (n_bits_total)
		*n_bits_total = 0;

	if ((nbits != GSM0503_GPRS_BURSTS_NBITS) &&
		(nbits != GSM0503_EGPRS_BURSTS_NBITS)) {
		/* Invalid EGPRS bit length */
		return -EOVERFLOW;
	}

	hdr = (union gprs_rlc_ul_hdr_egprs *) l2_data;
	type = egprs_decode_hdr(hdr, bursts, nbits);
	if (egprs_parse_ul_cps(&cps, hdr, type) < 0)
		return -EIO;

	switch (cps.mcs) {
	case EGPRS_MCS0:
		return -ENOTSUP;
	case EGPRS_MCS1:
	case EGPRS_MCS2:
	case EGPRS_MCS3:
	case EGPRS_MCS4:
		egprs_type3_unmap(bursts, NULL, dc);
		break;
	case EGPRS_MCS5:
	case EGPRS_MCS6:
		egprs_type2_unmap(bursts, NULL, dc);
		break;
	case EGPRS_MCS7:
	case EGPRS_MCS8:
	case EGPRS_MCS9:
		egprs_type1_unmap(bursts, NULL, c1, c2, cps.mcs);
		break;
	default:
		/* Invalid MCS-X */
		return -EINVAL;
	}

	/* Decode MCS-X block, where X = cps.mcs */
	if (cps.mcs < EGPRS_MCS7) {
		rc = egprs_decode_data(l2_data, dc, cps.mcs, cps.p[0],
			0, n_errors, n_bits_total);
		if (rc < 0)
			return -EFAULT;
	} else {
		/* Bit counters for the second block */
		int n_errors2, n_bits_total2;

		/* MCS-7,8,9 block 1 */
		rc = egprs_decode_data(l2_data, c1, cps.mcs, cps.p[0],
			0, n_errors, n_bits_total);
		if (rc < 0)
			return -EFAULT;

		/* MCS-7,8,9 block 2 */
		rc = egprs_decode_data(l2_data, c2, cps.mcs, cps.p[1],
			1, &n_errors2, &n_bits_total2);
		if (n_errors)
			*n_errors += n_errors2;
		if (n_bits_total)
			*n_bits_total += n_bits_total2;
		if (rc < 0)
			return -EFAULT;
	}

	return rc;
}

/*
 * GSM PDTCH block transcoding
 */

/*! Decode GPRS PDTCH
 *  \param[out] l2_data caller-allocated buffer for L2 Frame
 *  \param[in] bursts burst input data as soft unpacked bits
 *  \param[out] usf_p uplink stealing flag
 *  \param[out] n_errors number of detected bit-errors
 *  \param[out] n_bits_total total number of dcoded bits
 *  \returns 0 on success; negative on error */
int gsm0503_pdtch_decode(uint8_t *l2_data, const sbit_t *bursts, uint8_t *usf_p,
	int *n_errors, int *n_bits_total)
{
	sbit_t iB[456], cB[676], hl_hn[8];
	ubit_t conv[456];
	int i, j, k, rv, best = 0, cs = 0, usf = 0; /* make GCC happy */

	for (i = 0; i < 4; i++)
		gsm0503_xcch_burst_unmap(&iB[i * 114], &bursts[i * 116],
			hl_hn + i * 2, hl_hn + i * 2 + 1);

	for (i = 0; i < 4; i++) {
		for (j = 0, k = 0; j < 8; j++)
			k += abs(((int)gsm0503_pdtch_hl_hn_sbit[i][j]) - ((int)hl_hn[j]));

		if (i == 0 || k < best) {
			best = k;
			cs = i + 1;
		}
	}

	gsm0503_xcch_deinterleave(cB, iB);

	switch (cs) {
	case 1:
		osmo_conv_decode_ber(&gsm0503_xcch, cB,
			conv, n_errors, n_bits_total);

		rv = osmo_crc64gen_check_bits(&gsm0503_fire_crc40,
			conv, 184, conv + 184);
		if (rv)
			return -1;

		osmo_ubit2pbit_ext(l2_data, 0, conv, 0, 184, 1);

		return 23;
	case 2:
		for (i = 587, j = 455; i >= 0; i--) {
			if (!gsm0503_puncture_cs2[i])
				cB[i] = cB[j--];
			else
				cB[i] = 0;
		}

		osmo_conv_decode_ber(&gsm0503_cs2_np, cB,
			conv, n_errors, n_bits_total);

		for (i = 0; i < 8; i++) {
			for (j = 0, k = 0; j < 6; j++)
				k += abs(((int)gsm0503_usf2six[i][j]) - ((int)conv[j]));

			if (i == 0 || k < best) {
				best = k;
				usf = i;
			}
		}

		conv[3] = usf & 1;
		conv[4] = (usf >> 1) & 1;
		conv[5] = (usf >> 2) & 1;
		if (usf_p)
			*usf_p = usf;

		rv = osmo_crc16gen_check_bits(&gsm0503_cs234_crc16,
			conv + 3, 271, conv + 3 + 271);
		if (rv)
			return -1;

		osmo_ubit2pbit_ext(l2_data, 0, conv, 3, 271, 1);

		return 34;
	case 3:
		for (i = 675, j = 455; i >= 0; i--) {
			if (!gsm0503_puncture_cs3[i])
				cB[i] = cB[j--];
			else
				cB[i] = 0;
		}

		osmo_conv_decode_ber(&gsm0503_cs3_np, cB,
			conv, n_errors, n_bits_total);

		for (i = 0; i < 8; i++) {
			for (j = 0, k = 0; j < 6; j++)
				k += abs(((int)gsm0503_usf2six[i][j]) - ((int)conv[j]));

			if (i == 0 || k < best) {
				best = k;
				usf = i;
			}
		}

		conv[3] = usf & 1;
		conv[4] = (usf >> 1) & 1;
		conv[5] = (usf >> 2) & 1;
		if (usf_p)
			*usf_p = usf;

		rv = osmo_crc16gen_check_bits(&gsm0503_cs234_crc16,
			conv + 3, 315, conv + 3 + 315);
		if (rv)
			return -1;

		osmo_ubit2pbit_ext(l2_data, 0, conv, 3, 315, 1);

		return 40;
	case 4:
		for (i = 12; i < 456; i++)
			conv[i] = (cB[i] < 0) ? 1 : 0;

		for (i = 0; i < 8; i++) {
			for (j = 0, k = 0; j < 12; j++)
				k += abs(((int)gsm0503_usf2twelve_sbit[i][j]) - ((int)cB[j]));

			if (i == 0 || k < best) {
				best = k;
				usf = i;
			}
		}

		conv[9] = usf & 1;
		conv[10] = (usf >> 1) & 1;
		conv[11] = (usf >> 2) & 1;
		if (usf_p)
			*usf_p = usf;

		rv = osmo_crc16gen_check_bits(&gsm0503_cs234_crc16,
			conv + 9, 431, conv + 9 + 431);
		if (rv) {
			*n_bits_total = 456 - 12;
			*n_errors = *n_bits_total;
			return -1;
		}

		*n_bits_total = 456 - 12;
		*n_errors = 0;

		osmo_ubit2pbit_ext(l2_data, 0, conv, 9, 431, 1);

		return 54;
	default:
		*n_bits_total = 0;
		*n_errors = 0;
		break;
	}

	return -1;
}

/*
 * EGPRS PDTCH DL block encoding
 */
static int egprs_type3_map(ubit_t *bursts, const ubit_t *hc, const ubit_t *dc, int usf)
{
	int i;
	ubit_t iB[456];
	const ubit_t *hl_hn = gsm0503_pdtch_hl_hn_ubit[3];

	gsm0503_mcs1_dl_interleave(gsm0503_usf2twelve_ubit[usf], hc, dc, iB);

	for (i = 0; i < 4; i++) {
		gsm0503_xcch_burst_map(&iB[i * 114], &bursts[i * 116],
			hl_hn + i * 2, hl_hn + i * 2 + 1);
	}

	return 0;
}

static int egprs_type2_map(ubit_t *bursts, const ubit_t *hc, const ubit_t *dc, int usf)
{
	int i;
	const ubit_t *up;
	ubit_t hi[EGPRS_HDR_HC_MAX];
	ubit_t di[EGPRS_DATA_DC_MAX];

	gsm0503_mcs5_dl_interleave(hc, dc, hi, di);
	up = gsm0503_mcs5_usf_precode_table[usf];

	for (i = 0; i < 4; i++) {
		gsm0503_mcs5_dl_burst_map(di, &bursts[i * 348], hi, up, i);
		gsm0503_mcs5_burst_swap((sbit_t *) &bursts[i * 348]);
	}

	return 0;
}

static int egprs_type1_map(ubit_t *bursts, const ubit_t *hc,
	const ubit_t *c1, const ubit_t *c2, int usf, int mcs)
{
	int i;
	const ubit_t *up;
	ubit_t hi[EGPRS_HDR_HC_MAX];
	ubit_t di[EGPRS_DATA_C1 * 2];

	if (mcs == EGPRS_MCS7)
		gsm0503_mcs7_dl_interleave(hc, c1, c2, hi, di);
	else
		gsm0503_mcs8_dl_interleave(hc, c1, c2, hi, di);

	up = gsm0503_mcs5_usf_precode_table[usf];

	for (i = 0; i < 4; i++) {
		gsm0503_mcs7_dl_burst_map(di, &bursts[i * 348], hi, up, i);
		gsm0503_mcs5_burst_swap((sbit_t *) &bursts[i * 348]);
	}

	return 0;
}

static int egprs_encode_hdr(ubit_t *hc, const uint8_t *l2_data, int mcs)
{
	int i, j;
	ubit_t upp[EGPRS_HDR_UPP_MAX], C[EGPRS_HDR_C_MAX];
	const struct gsm0503_mcs_code *code;

	code = &gsm0503_mcs_dl_codes[mcs];

	osmo_pbit2ubit_ext(upp, 0, l2_data, code->usf_len, code->hdr_len, 1);
	osmo_crc8gen_set_bits(&gsm0503_mcs_crc8_hdr, upp,
		code->hdr_len, upp + code->hdr_len);

	osmo_conv_encode(code->hdr_conv, upp, C);

	/* MCS-5,6 header direct puncture instead of table */
	if ((mcs == EGPRS_MCS5) || (mcs == EGPRS_MCS6)) {
		memcpy(hc, C, code->hdr_code_len);
		hc[99] = hc[98];
		return 0;
	}

	if (!code->hdr_punc) {
		/* Invalid MCS-X header puncture matrix */
		return -1;
	}

	for (i = 0, j = 0; i < code->hdr_code_len; i++) {
		if (!code->hdr_punc[i])
			hc[j++] = C[i];
	}

	return 0;
}

static int egprs_encode_data(ubit_t *c, const uint8_t *l2_data,
	int mcs, int p, int blk)
{
	int i, j, data_len;
	ubit_t u[EGPRS_DATA_U_MAX], C[EGPRS_DATA_C_MAX];
	const struct gsm0503_mcs_code *code;

	code = &gsm0503_mcs_dl_codes[mcs];

	/*
	 * Dual block   - MCS-7,8,9
	 * Single block - MCS-1,2,3,4,5,6
	 */
	if (mcs >= EGPRS_MCS7)
		data_len = code->data_len / 2;
	else
		data_len = code->data_len;

	osmo_pbit2ubit_ext(u, 0, l2_data,
		code->usf_len + code->hdr_len + blk * data_len, data_len, 1);

	osmo_crc16gen_set_bits(&gsm0503_mcs_crc12, u, data_len, u + data_len);

	osmo_conv_encode(code->data_conv, u, C);

	if (!code->data_punc[p]) {
		/* Invalid MCS-X data puncture matrix */
		return -1;
	}

	for (i = 0, j = 0; i < code->data_code_len; i++) {
		if (!code->data_punc[p][i])
			c[j++] = C[i];
	}

	return 0;
}

/*
 * Parse EGPRS DL header for coding and puncturing scheme (CPS)
 *
 * Type 1 - MCS-7,8,9
 * Type 2 - MCS-5,6
 * Type 3 - MCS-1,2,3,4
 */
static int egprs_parse_dl_cps(struct egprs_cps *cps,
	const union gprs_rlc_dl_hdr_egprs *hdr, int type)
{
	uint8_t bits;

	switch (type) {
	case EGPRS_HDR_TYPE1:
		bits = hdr->type1.cps;
		break;
	case EGPRS_HDR_TYPE2:
		bits = hdr->type2.cps;
		break;
	case EGPRS_HDR_TYPE3:
		bits = hdr->type3.cps;
		break;
	default:
		return -1;
	}

	return egprs_get_cps(cps, type, bits);
}

/*! EGPRS DL message encoding
 *  \param[out] bursts caller-allocated buffer for unpacked burst bits
 *  \param[in] l2_data L2 (MAC) block to be encoded
 *  \param[in] l2_len length of l2_data in bytes, used to determine MCS
 *  \returns number of bits encoded; negative on error */
int gsm0503_pdtch_egprs_encode(ubit_t *bursts,
	const uint8_t *l2_data, uint8_t l2_len)
{
	ubit_t hc[EGPRS_DATA_C_MAX], dc[EGPRS_DATA_DC_MAX];
	ubit_t c1[EGPRS_DATA_C1], c2[EGPRS_DATA_C2];
	uint8_t mcs;
	struct egprs_cps cps;
	union gprs_rlc_dl_hdr_egprs *hdr;

	switch (l2_len) {
	case 27:
		mcs = EGPRS_MCS1;
		break;
	case 33:
		mcs = EGPRS_MCS2;
		break;
	case 42:
		mcs = EGPRS_MCS3;
		break;
	case 49:
		mcs = EGPRS_MCS4;
		break;
	case 60:
		mcs = EGPRS_MCS5;
		break;
	case 78:
		mcs = EGPRS_MCS6;
		break;
	case 118:
		mcs = EGPRS_MCS7;
		break;
	case 142:
		mcs = EGPRS_MCS8;
		break;
	case 154:
		mcs = EGPRS_MCS9;
		break;
	default:
		return -1;
	}

	/* Read header for USF and puncturing matrix selection. */
	hdr = (union gprs_rlc_dl_hdr_egprs *) l2_data;

	switch (mcs) {
	case EGPRS_MCS1:
	case EGPRS_MCS2:
	case EGPRS_MCS3:
	case EGPRS_MCS4:
		/* Check for valid CPS and matching MCS to message size */
		if ((egprs_parse_dl_cps(&cps, hdr, EGPRS_HDR_TYPE3) < 0) ||
			(cps.mcs != mcs))
			goto bad_header;

		egprs_encode_hdr(hc, l2_data, mcs);
		egprs_encode_data(dc, l2_data, mcs, cps.p[0], 0);
		egprs_type3_map(bursts, hc, dc, hdr->type3.usf);
		break;
	case EGPRS_MCS5:
	case EGPRS_MCS6:
		if ((egprs_parse_dl_cps(&cps, hdr, EGPRS_HDR_TYPE2) < 0) ||
			(cps.mcs != mcs))
			goto bad_header;

		egprs_encode_hdr(hc, l2_data, mcs);
		egprs_encode_data(dc, l2_data, mcs, cps.p[0], 0);
		egprs_type2_map(bursts, hc, dc, hdr->type2.usf);
		break;
	case EGPRS_MCS7:
	case EGPRS_MCS8:
	case EGPRS_MCS9:
		if ((egprs_parse_dl_cps(&cps, hdr, EGPRS_HDR_TYPE1) < 0) ||
			(cps.mcs != mcs))
			goto bad_header;

		egprs_encode_hdr(hc, l2_data, mcs);
		egprs_encode_data(c1, l2_data, mcs, cps.p[0], 0);
		egprs_encode_data(c2, l2_data, mcs, cps.p[1], 1);
		egprs_type1_map(bursts, hc, c1, c2, hdr->type1.usf, mcs);
		break;
	}

	return mcs >= EGPRS_MCS5 ?
		GSM0503_EGPRS_BURSTS_NBITS : GSM0503_GPRS_BURSTS_NBITS;

bad_header:
	/* Invalid EGPRS MCS-X header */
	return -1;
}

/*! GPRS DL message encoding
 *  \param[out] bursts caller-allocated buffer for unpacked burst bits
 *  \param[in] l2_data L2 (MAC) block to be encoded
 *  \param[in] l2_len length of l2_data in bytes, used to determine CS
 *  \returns number of bits encoded; negative on error */
int gsm0503_pdtch_encode(ubit_t *bursts, const uint8_t *l2_data, uint8_t l2_len)
{
	ubit_t iB[456], cB[676];
	const ubit_t *hl_hn;
	ubit_t conv[334];
	int i, j, usf;

	switch (l2_len) {
	case 23:
		osmo_pbit2ubit_ext(conv, 0, l2_data, 0, 184, 1);

		osmo_crc64gen_set_bits(&gsm0503_fire_crc40, conv, 184, conv + 184);

		osmo_conv_encode(&gsm0503_xcch, conv, cB);

		hl_hn = gsm0503_pdtch_hl_hn_ubit[0];

		break;
	case 34:
		osmo_pbit2ubit_ext(conv, 3, l2_data, 0, 271, 1);
		usf = l2_data[0] & 0x7;

		osmo_crc16gen_set_bits(&gsm0503_cs234_crc16, conv + 3,
			271, conv + 3 + 271);

		memcpy(conv, gsm0503_usf2six[usf], 6);

		osmo_conv_encode(&gsm0503_cs2_np, conv, cB);

		for (i = 0, j = 0; i < 588; i++)
			if (!gsm0503_puncture_cs2[i])
				cB[j++] = cB[i];

		hl_hn = gsm0503_pdtch_hl_hn_ubit[1];

		break;
	case 40:
		osmo_pbit2ubit_ext(conv, 3, l2_data, 0, 315, 1);
		usf = l2_data[0] & 0x7;

		osmo_crc16gen_set_bits(&gsm0503_cs234_crc16, conv + 3,
			315, conv + 3 + 315);

		memcpy(conv, gsm0503_usf2six[usf], 6);

		osmo_conv_encode(&gsm0503_cs3_np, conv, cB);

		for (i = 0, j = 0; i < 676; i++)
			if (!gsm0503_puncture_cs3[i])
				cB[j++] = cB[i];

		hl_hn = gsm0503_pdtch_hl_hn_ubit[2];

		break;
	case 54:
		osmo_pbit2ubit_ext(cB, 9, l2_data, 0, 431, 1);
		usf = l2_data[0] & 0x7;

		osmo_crc16gen_set_bits(&gsm0503_cs234_crc16, cB + 9,
			431, cB + 9 + 431);

		memcpy(cB, gsm0503_usf2twelve_ubit[usf], 12);

		hl_hn = gsm0503_pdtch_hl_hn_ubit[3];

		break;
	default:
		return -1;
	}

	gsm0503_xcch_interleave(cB, iB);

	for (i = 0; i < 4; i++) {
		gsm0503_xcch_burst_map(&iB[i * 114], &bursts[i * 116],
			hl_hn + i * 2, hl_hn + i * 2 + 1);
	}

	return GSM0503_GPRS_BURSTS_NBITS;
}

/*
 * GSM TCH/F FR/EFR transcoding
 */

/*! assemble a FR codec frame in format as used inside RTP
 *  \param[out] tch_data Codec frame in RTP format
 *  \param[in] b_bits Codec frame in 'native' format
 *  \param[in] net_order FIXME */
static void tch_fr_reassemble(uint8_t *tch_data,
	const ubit_t *b_bits, int net_order)
{
	int i, j, k, l, o;

	tch_data[0] = 0xd << 4;
	memset(tch_data + 1, 0, 32);

	if (net_order) {
		for (i = 0, j = 4; i < 260; i++, j++)
			tch_data[j >> 3] |= (b_bits[i] << (7 - (j & 7)));

		return;
	}

	/* reassemble d-bits */
	i = 0; /* counts bits */
	j = 4; /* counts output bits */
	k = gsm0503_gsm_fr_map[0]-1; /* current number bit in element */
	l = 0; /* counts element bits */
	o = 0; /* offset input bits */
	while (i < 260) {
		tch_data[j >> 3] |= (b_bits[k + o] << (7 - (j & 7)));
		if (--k < 0) {
			o += gsm0503_gsm_fr_map[l];
			k = gsm0503_gsm_fr_map[++l]-1;
		}
		i++;
		j++;
	}
}

static void tch_fr_disassemble(ubit_t *b_bits,
	const uint8_t *tch_data, int net_order)
{
	int i, j, k, l, o;

	if (net_order) {
		for (i = 0, j = 4; i < 260; i++, j++)
			b_bits[i] = (tch_data[j >> 3] >> (7 - (j & 7))) & 1;

		return;
	}

	i = 0; /* counts bits */
	j = 4; /* counts input bits */
	k = gsm0503_gsm_fr_map[0] - 1; /* current number bit in element */
	l = 0; /* counts element bits */
	o = 0; /* offset output bits */
	while (i < 260) {
		b_bits[k + o] = (tch_data[j >> 3] >> (7 - (j & 7))) & 1;
		if (--k < 0) {
			o += gsm0503_gsm_fr_map[l];
			k = gsm0503_gsm_fr_map[++l] - 1;
		}
		i++;
		j++;
	}
}

/* assemble a HR codec frame in format as used inside RTP */
static void tch_hr_reassemble(uint8_t *tch_data, const ubit_t *b_bits)
{
	int i, j;

	tch_data[0] = 0x00; /* F = 0, FT = 000 */
	memset(tch_data + 1, 0, 14);

	for (i = 0, j = 8; i < 112; i++, j++)
		tch_data[j >> 3] |= (b_bits[i] << (7 - (j & 7)));
}

static void tch_hr_disassemble(ubit_t *b_bits, const uint8_t *tch_data)
{
	int i, j;

	for (i = 0, j = 8; i < 112; i++, j++)
		b_bits[i] = (tch_data[j >> 3] >> (7 - (j & 7))) & 1;
}

/* assemble a EFR codec frame in format as used inside RTP */
static void tch_efr_reassemble(uint8_t *tch_data, const ubit_t *b_bits)
{
	int i, j;

	tch_data[0] = 0xc << 4;
	memset(tch_data + 1, 0, 30);

	for (i = 0, j = 4; i < 244; i++, j++)
		tch_data[j >> 3] |= (b_bits[i] << (7 - (j & 7)));
}

static void tch_efr_disassemble(ubit_t *b_bits, const uint8_t *tch_data)
{
	int i, j;

	for (i = 0, j = 4; i < 244; i++, j++)
		b_bits[i] = (tch_data[j >> 3] >> (7 - (j & 7))) & 1;
}

/* assemble a AMR codec frame in format as used inside RTP */
static void tch_amr_reassemble(uint8_t *tch_data, const ubit_t *d_bits, int len)
{
	int i, j;

	memset(tch_data, 0, (len + 7) >> 3);

	for (i = 0, j = 0; i < len; i++, j++)
		tch_data[j >> 3] |= (d_bits[i] << (7 - (j & 7)));
}

static void tch_amr_disassemble(ubit_t *d_bits, const uint8_t *tch_data, int len)
{
	int i, j;

	for (i = 0, j = 0; i < len; i++, j++)
		d_bits[i] = (tch_data[j >> 3] >> (7 - (j & 7))) & 1;
}

/* Append STI and MI bits to the SID_UPDATE frame, see also
 * 3GPP TS 26.101, chapter 4.2.3 AMR Core Frame with comfort noise bits */
static void tch_amr_sid_update_append(ubit_t *sid_update, uint8_t sti, uint8_t mi)
{
	/* Zero out the space that had been used by the CRC14 */
	memset(sid_update + 35, 0, 14);

	/* Append STI and MI parameters */
	sid_update[35] = sti & 1;
	sid_update[36] = mi & 1;
	sid_update[37] = mi >> 1 & 1;
	sid_update[38] = mi >> 2 & 1;
}

/* Extract a SID UPDATE fram the sbits of an FR AMR frame */
static void extract_afs_sid_update(sbit_t *sid_update, const sbit_t *sbits)
{

	unsigned int i;

	sbits += 32;

	for (i = 0; i < 53; i++) {
		sid_update[0] = sbits[0];
		sid_update[1] = sbits[1];
		sid_update[2] = sbits[2];
		sid_update[3] = sbits[3];
		sid_update += 4;
		sbits += 8;
	}

}

/* re-arrange according to TS 05.03 Table 2 (receiver) */
static void tch_fr_d_to_b(ubit_t *b_bits, const ubit_t *d_bits)
{
	int i;

	for (i = 0; i < 260; i++)
		b_bits[gsm610_bitorder[i]] = d_bits[i];
}

/* re-arrange according to TS 05.03 Table 2 (transmitter) */
static void tch_fr_b_to_d(ubit_t *d_bits, const ubit_t *b_bits)
{
	int i;

	for (i = 0; i < 260; i++)
		d_bits[i] = b_bits[gsm610_bitorder[i]];
}

/* re-arrange according to TS 05.03 Table 3a (receiver) */
static void tch_hr_d_to_b(ubit_t *b_bits, const ubit_t *d_bits)
{
	int i;

	const uint16_t *map;

	if (!d_bits[93] && !d_bits[94])
		map = gsm620_unvoiced_bitorder;
	else
		map = gsm620_voiced_bitorder;

	for (i = 0; i < 112; i++)
		b_bits[map[i]] = d_bits[i];
}

/* re-arrange according to TS 05.03 Table 3a (transmitter) */
static void tch_hr_b_to_d(ubit_t *d_bits, const ubit_t *b_bits)
{
	int i;
	const uint16_t *map;

	if (!b_bits[34] && !b_bits[35])
		map = gsm620_unvoiced_bitorder;
	else
		map = gsm620_voiced_bitorder;

	for (i = 0; i < 112; i++)
		d_bits[i] = b_bits[map[i]];
}

/* re-arrange according to TS 05.03 Table 6 (receiver) */
static void tch_efr_d_to_w(ubit_t *b_bits, const ubit_t *d_bits)
{
	int i;

	for (i = 0; i < 260; i++)
		b_bits[gsm660_bitorder[i]] = d_bits[i];
}

/* re-arrange according to TS 05.03 Table 6 (transmitter) */
static void tch_efr_w_to_d(ubit_t *d_bits, const ubit_t *b_bits)
{
	int i;

	for (i = 0; i < 260; i++)
		d_bits[i] = b_bits[gsm660_bitorder[i]];
}

/* extract the 65 protected class1a+1b bits */
static void tch_efr_protected(const ubit_t *s_bits, ubit_t *b_bits)
{
	int i;

	for (i = 0; i < 65; i++)
		b_bits[i] = s_bits[gsm0503_gsm_efr_protected_bits[i] - 1];
}

static void tch_fr_unreorder(ubit_t *d, ubit_t *p, const ubit_t *u)
{
	int i;

	for (i = 0; i < 91; i++) {
		d[i << 1] = u[i];
		d[(i << 1) + 1] = u[184 - i];
	}

	for (i = 0; i < 3; i++)
		p[i] = u[91 + i];
}

static void tch_fr_reorder(ubit_t *u, const ubit_t *d, const ubit_t *p)
{
	int i;

	for (i = 0; i < 91; i++) {
		u[i] = d[i << 1];
		u[184 - i] = d[(i << 1) + 1];
	}

	for (i = 0; i < 3; i++)
		u[91 + i] = p[i];
}

static void tch_hr_unreorder(ubit_t *d, ubit_t *p, const ubit_t *u)
{
	memcpy(d, u, 95);
	memcpy(p, u + 95, 3);
}

static void tch_hr_reorder(ubit_t *u, const ubit_t *d, const ubit_t *p)
{
	memcpy(u, d, 95);
	memcpy(u + 95, p, 3);
}

static void tch_efr_reorder(ubit_t *w, const ubit_t *s, const ubit_t *p)
{
	memcpy(w, s, 71);
	w[71] = w[72] = s[69];
	memcpy(w + 73, s + 71, 50);
	w[123] = w[124] = s[119];
	memcpy(w + 125, s + 121, 53);
	w[178] = w[179] = s[172];
	memcpy(w + 180, s + 174, 50);
	w[230] = w[231] = s[222];
	memcpy(w + 232, s + 224, 20);
	memcpy(w + 252, p, 8);
}

static void tch_efr_unreorder(ubit_t *s, ubit_t *p, const ubit_t *w)
{
	int sum;

	memcpy(s, w, 71);
	sum = s[69] + w[71] + w[72];
	s[69] = (sum >= 2);
	memcpy(s + 71, w + 73, 50);
	sum = s[119] + w[123] + w[124];
	s[119] = (sum >= 2);
	memcpy(s + 121, w + 125, 53);
	sum = s[172] + w[178] + w[179];
	s[172] = (sum > 2);
	memcpy(s + 174, w + 180, 50);
	sum = s[222] + w[230] + w[231];
	s[222] = (sum >= 2);
	memcpy(s + 224, w + 232, 20);
	memcpy(p, w + 252, 8);
}

static void tch_amr_merge(ubit_t *u, const ubit_t *d, const ubit_t *p, int len, int prot)
{
	memcpy(u, d, prot);
	memcpy(u + prot, p, 6);
	memcpy(u + prot + 6, d + prot, len - prot);
}

static void tch_amr_unmerge(ubit_t *d, ubit_t *p, const ubit_t *u, int len, int prot)
{
	memcpy(d, u, prot);
	memcpy(p, u + prot, 6);
	memcpy(d + prot, u + prot + 6, len - prot);
}

/*! Perform channel decoding of a FR/EFR channel according TS 05.03
 *  \param[out] tch_data Codec frame in RTP payload format
 *  \param[in] bursts buffer containing the symbols of 8 bursts
 *  \param[in] net_order FIXME
 *  \param[in] efr Is this channel using EFR (1) or FR (0)
 *  \param[out] n_errors Number of detected bit errors
 *  \param[out] n_bits_total Total number of bits
 *  \returns length of bytes used in \a tch_data output buffer; negative on error */
int gsm0503_tch_fr_decode(uint8_t *tch_data, const sbit_t *bursts,
	int net_order, int efr, int *n_errors, int *n_bits_total)
{
	sbit_t iB[912], cB[456], h;
	ubit_t conv[185], s[244], w[260], b[65], d[260], p[8];
	int i, rv, len, steal = 0;

	/* map from 8 bursts to interleaved data bits (iB) */
	for (i = 0; i < 8; i++) {
		gsm0503_tch_burst_unmap(&iB[i * 114],
			&bursts[i * 116], &h, i >> 2);
		steal -= h;
	}
	/* we now have the bits of the four bursts (interface 4 in
	 * Figure 1a of TS 05.03 */

	gsm0503_tch_fr_deinterleave(cB, iB);
	/* we now have the coded bits c(B): interface 3 in Fig. 1a */

	if (steal > 0) {
		rv = _xcch_decode_cB(tch_data, cB, n_errors, n_bits_total);
		if (rv) {
			/* Error decoding FACCH frame */
			return -1;
		}

		return 23;
	}

	osmo_conv_decode_ber(&gsm0503_tch_fr, cB, conv, n_errors, n_bits_total);
	/* we now have the data bits 'u': interface 2 in Fig. 1a */

	/* input: 'conv', output: d[ata] + p[arity] */
	tch_fr_unreorder(d, p, conv);

	for (i = 0; i < 78; i++)
		d[i + 182] = (cB[i + 378] < 0) ? 1 : 0;

	/* check if parity of first 50 (class 1) 'd'-bits match 'p' */
	rv = osmo_crc8gen_check_bits(&gsm0503_tch_fr_crc3, d, 50, p);
	if (rv) {
		/* Error checking CRC8 for the FR part of an EFR/FR frame */
		return -1;
	}

	if (efr) {
		tch_efr_d_to_w(w, d);
		/* we now have the preliminary-coded bits w(k) */

		tch_efr_unreorder(s, p, w);
		/* we now have the data delivered to the preliminary
		 * channel encoding unit s(k) */

		/* extract the 65 most important bits according TS 05.03 3.1.1.1 */
		tch_efr_protected(s, b);

		/* perform CRC-8 on 65 most important bits (50 bits of
		 * class 1a + 15 bits of class 1b) */
		rv = osmo_crc8gen_check_bits(&gsm0503_tch_efr_crc8, b, 65, p);
		if (rv) {
			/* Error checking CRC8 for the EFR part of an EFR frame */
			return -1;
		}

		tch_efr_reassemble(tch_data, s);

		len = GSM_EFR_BYTES;
	} else {
		tch_fr_d_to_b(w, d);

		tch_fr_reassemble(tch_data, w, net_order);

		len = GSM_FR_BYTES;
	}

	return len;
}

/*! Perform channel encoding on a TCH/FS channel according to TS 05.03
 *  \param[out] bursts caller-allocated output buffer for bursts bits
 *  \param[in] tch_data Codec input data in RTP payload format
 *  \param[in] len Length of \a tch_data in bytes
 *  \param[in] net_order FIXME
 *  \returns 0 in case of success; negative on error */
int gsm0503_tch_fr_encode(ubit_t *bursts, const uint8_t *tch_data,
	int len, int net_order)
{
	ubit_t iB[912], cB[456], h;
	ubit_t conv[185], w[260], b[65], s[244], d[260], p[8];
	int i;

	switch (len) {
	case GSM_EFR_BYTES: /* TCH EFR */

		tch_efr_disassemble(s, tch_data);

		tch_efr_protected(s, b);

		osmo_crc8gen_set_bits(&gsm0503_tch_efr_crc8, b, 65, p);

		tch_efr_reorder(w, s, p);

		tch_efr_w_to_d(d, w);

		goto coding_efr_fr;
	case GSM_FR_BYTES: /* TCH FR */
		tch_fr_disassemble(w, tch_data, net_order);

		tch_fr_b_to_d(d, w);

coding_efr_fr:
		osmo_crc8gen_set_bits(&gsm0503_tch_fr_crc3, d, 50, p);

		tch_fr_reorder(conv, d, p);

		memcpy(cB + 378, d + 182, 78);

		osmo_conv_encode(&gsm0503_tch_fr, conv, cB);

		h = 0;

		break;
	case GSM_MACBLOCK_LEN: /* FACCH */
		_xcch_encode_cB(cB, tch_data);

		h = 1;

		break;
	default:
		return -1;
	}

	gsm0503_tch_fr_interleave(cB, iB);

	for (i = 0; i < 8; i++) {
		gsm0503_tch_burst_map(&iB[i * 114],
			&bursts[i * 116], &h, i >> 2);
	}

	return 0;
}

/*! Perform channel decoding of a HR(v1) channel according TS 05.03
 *  \param[out] tch_data Codec frame in RTP payload format
 *  \param[in] bursts buffer containing the symbols of 8 bursts
 *  \param[in] odd Odd (1) or even (0) frame number
 *  \param[out] n_errors Number of detected bit errors
 *  \param[out] n_bits_total Total number of bits
 *  \returns length of bytes used in \a tch_data output buffer; negative on error */
int gsm0503_tch_hr_decode(uint8_t *tch_data, const sbit_t *bursts, int odd,
	int *n_errors, int *n_bits_total)
{
	sbit_t iB[912], cB[456], h;
	ubit_t conv[98], b[112], d[112], p[3];
	int i, rv, steal = 0;

	/* Only unmap the stealing bits */
	if (!odd) {
		for (i = 0; i < 4; i++) {
			gsm0503_tch_burst_unmap(NULL, &bursts[i * 116], &h, 0);
			steal -= h;
		}

		for (i = 2; i < 5; i++) {
			gsm0503_tch_burst_unmap(NULL, &bursts[i * 116], &h, 1);
			steal -= h;
		}
	}

	/* If we found a stole FACCH, but only at correct alignment */
	if (steal > 0) {
		for (i = 0; i < 6; i++) {
			gsm0503_tch_burst_unmap(&iB[i * 114],
				&bursts[i * 116], NULL, i >> 2);
		}

		for (i = 2; i < 4; i++) {
			gsm0503_tch_burst_unmap(&iB[i * 114 + 456],
				&bursts[i * 116], NULL, 1);
		}

		gsm0503_tch_fr_deinterleave(cB, iB);

		rv = _xcch_decode_cB(tch_data, cB, n_errors, n_bits_total);
		if (rv) {
			/* Error decoding FACCH frame */
			return -1;
		}

		return GSM_MACBLOCK_LEN;
	}

	for (i = 0; i < 4; i++) {
		gsm0503_tch_burst_unmap(&iB[i * 114],
			&bursts[i * 116], NULL, i >> 1);
	}

	gsm0503_tch_hr_deinterleave(cB, iB);

	osmo_conv_decode_ber(&gsm0503_tch_hr, cB, conv, n_errors, n_bits_total);

	tch_hr_unreorder(d, p, conv);

	for (i = 0; i < 17; i++)
		d[i + 95] = (cB[i + 211] < 0) ? 1 : 0;

	rv = osmo_crc8gen_check_bits(&gsm0503_tch_fr_crc3, d + 73, 22, p);
	if (rv) {
		/* Error checking CRC8 for an HR frame */
		return -1;
	}

	tch_hr_d_to_b(b, d);

	tch_hr_reassemble(tch_data, b);

	return 15;
}

/*! Perform channel encoding on a TCH/HS channel according to TS 05.03
 *  \param[out] bursts caller-allocated output buffer for bursts bits
 *  \param[in] tch_data Codec input data in RTP payload format
 *  \param[in] len Length of \a tch_data in bytes
 *  \returns 0 in case of success; negative on error */
int gsm0503_tch_hr_encode(ubit_t *bursts, const uint8_t *tch_data, int len)
{
	ubit_t iB[912], cB[456], h;
	ubit_t conv[98], b[112], d[112], p[3];
	int i;

	switch (len) {
	case 15: /* TCH HR */
		tch_hr_disassemble(b, tch_data);

		tch_hr_b_to_d(d, b);

		osmo_crc8gen_set_bits(&gsm0503_tch_fr_crc3, d + 73, 22, p);

		tch_hr_reorder(conv, d, p);

		osmo_conv_encode(&gsm0503_tch_hr, conv, cB);

		memcpy(cB + 211, d + 95, 17);

		h = 0;

		gsm0503_tch_hr_interleave(cB, iB);

		for (i = 0; i < 4; i++) {
			gsm0503_tch_burst_map(&iB[i * 114],
				&bursts[i * 116], &h, i >> 1);
		}

		break;
	case GSM_MACBLOCK_LEN: /* FACCH */
		_xcch_encode_cB(cB, tch_data);

		h = 1;

		gsm0503_tch_fr_interleave(cB, iB);

		for (i = 0; i < 6; i++) {
			gsm0503_tch_burst_map(&iB[i * 114],
				&bursts[i * 116], &h, i >> 2);
		}

		for (i = 2; i < 4; i++) {
			gsm0503_tch_burst_map(&iB[i * 114 + 456],
				&bursts[i * 116], &h, 1);
		}

		break;
	default:
		return -1;
	}

	return 0;
}

/*! Perform channel decoding of a TCH/AFS channel according TS 05.03
 *  \param[out] tch_data Codec frame in RTP payload format
 *  \param[in] bursts buffer containing the symbols of 8 bursts
 *  \param[in] codec_mode_req is this CMR (1) or CMC (0)
 *  \param[in] codec array of active codecs (active codec set)
 *  \param[in] codecs number of codecs in \a codec
 *  \param ft Frame Type; Input if \a codec_mode_req = 1, Output *  otherwise
 *  \param[out] cmr Output in \a codec_mode_req = 1
 *  \param[out] n_errors Number of detected bit errors
 *  \param[out] n_bits_total Total number of bits
 *  \returns (>=4) length of bytes used in \a tch_data output buffer; ([0,3])
 *  	     codec out of range; negative on error
 */
int gsm0503_tch_afs_decode(uint8_t *tch_data, const sbit_t *bursts,
	int codec_mode_req, uint8_t *codec, int codecs, uint8_t *ft,
	uint8_t *cmr, int *n_errors, int *n_bits_total)
{
	return gsm0503_tch_afs_decode_dtx(tch_data, bursts, codec_mode_req,
					  codec, codecs, ft, cmr, n_errors,
					  n_bits_total, NULL);
}

/*! Perform channel decoding of a TCH/AFS channel according TS 05.03
 *  \param[out] tch_data Codec frame in RTP payload format
 *  \param[in] bursts buffer containing the symbols of 8 bursts
 *  \param[in] codec_mode_req is this CMR (1) or CMC (0)
 *  \param[in] codec array of active codecs (active codec set)
 *  \param[in] codecs number of codecs in \a codec
 *  \param ft Frame Type; Input if \a codec_mode_req = 1, Output *  otherwise
 *  \param[out] cmr Output in \a codec_mode_req = 1
 *  \param[out] n_errors Number of detected bit errors
 *  \param[out] n_bits_total Total number of bits
 *  \param[inout] dtx DTX frame type output, previous DTX frame type input
 *  \returns (>=4) length of bytes used in \a tch_data output buffer; ([0,3])
 *  	     codec out of range; negative on error
 */
int gsm0503_tch_afs_decode_dtx(uint8_t *tch_data, const sbit_t *bursts,
	int codec_mode_req, uint8_t *codec, int codecs, uint8_t *ft,
	uint8_t *cmr, int *n_errors, int *n_bits_total, uint8_t *dtx)
{
	sbit_t iB[912], cB[456], h;
	ubit_t d[244], p[6], conv[250];
	int i, j, k, best = 0, rv, len, steal = 0, id = 0;
	ubit_t cBd[456];
	*n_errors = 0; *n_bits_total = 0;
	static ubit_t sid_first_dummy[64] = { 0 };
	sbit_t sid_update_enc[256];
	uint8_t dtx_prev;

	for (i=0; i<8; i++) {
		gsm0503_tch_burst_unmap(&iB[i * 114], &bursts[i * 116], &h, i >> 2);
		steal -= h;
	}

	gsm0503_tch_fr_deinterleave(cB, iB);

	if (steal > 0) {
		rv = _xcch_decode_cB(tch_data, cB, n_errors, n_bits_total);
		if (rv) {
			/* Error decoding FACCH frame */
			return -1;
		}

		return GSM_MACBLOCK_LEN;
	}

	/* Determine the DTX frame type (SID_UPDATE, ONSET etc...) */
	if (dtx) {
		osmo_sbit2ubit(cBd, cB, 456);
		dtx_prev = *dtx;
		*dtx = gsm0503_detect_afs_dtx_frame(n_errors, n_bits_total, cBd);

		if (dtx_prev == AFS_SID_UPDATE && *dtx == AMR_OTHER) {
			/* NOTE: The AFS_SID_UPDATE frame is splitted into
			 * two half rate frames. If the id marker frame
			 * (AFS_SID_UPDATE) is detected the following frame
			 * contains the actual comfort noised data part of
			 * (AFS_SID_UPDATE_CN). */
			*dtx = AFS_SID_UPDATE_CN;

			extract_afs_sid_update(sid_update_enc, cB);
			osmo_conv_decode_ber(&gsm0503_tch_axs_sid_update,
					     sid_update_enc, conv, n_errors,
					     n_bits_total);
			rv = osmo_crc16gen_check_bits(&gsm0503_amr_crc14, conv,
						      35, conv + 35);
			if (rv != 0) {
				/* Error checking CRC14 for an AMR SID_UPDATE frame */
				return -1;
			}

			tch_amr_sid_update_append(conv, 1,
						  (codec_mode_req) ? codec[*ft]
						  : codec[id]);
			tch_amr_reassemble(tch_data, conv, 39);
			len = 5;
			goto out;
		} else if (*dtx == AFS_SID_FIRST) {
			tch_amr_sid_update_append(sid_first_dummy, 0,
						  (codec_mode_req) ? codec[*ft]
						  : codec[id]);
			tch_amr_reassemble(tch_data, conv, 39);
			len = 5;
			goto out;
		} else if (*dtx == AFS_ONSET) {
			len = 0;
			goto out;
		}
	}

	for (i = 0; i < 4; i++) {
		for (j = 0, k = 0; j < 8; j++)
			k += abs(((int)gsm0503_afs_ic_sbit[i][j]) - ((int)cB[j]));

		if (i == 0 || k < best) {
			best = k;
			id = i;
		}
	}

	/* Check if indicated codec fits into range of codecs */
	if (id >= codecs) {
		/* Codec mode out of range, return id */
		return id;
	}

	switch ((codec_mode_req) ? codec[*ft] : codec[id]) {
	case 7: /* TCH/AFS12.2 */
		osmo_conv_decode_ber(&gsm0503_tch_afs_12_2, cB + 8,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 244, 81);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 81, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 12.2 frame */
			return -1;
		}

		tch_amr_reassemble(tch_data, d, 244);

		len = 31;

		break;
	case 6: /* TCH/AFS10.2 */
		osmo_conv_decode_ber(&gsm0503_tch_afs_10_2, cB + 8,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 204, 65);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 65, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 10.2 frame */
			return -1;
		}

		tch_amr_reassemble(tch_data, d, 204);

		len = 26;

		break;
	case 5: /* TCH/AFS7.95 */
		osmo_conv_decode_ber(&gsm0503_tch_afs_7_95, cB + 8,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 159, 75);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 75, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 7.95 frame */
			return -1;
		}

		tch_amr_reassemble(tch_data, d, 159);

		len = 20;

		break;
	case 4: /* TCH/AFS7.4 */
		osmo_conv_decode_ber(&gsm0503_tch_afs_7_4, cB + 8,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 148, 61);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 61, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 7.4 frame */
			return -1;
		}

		tch_amr_reassemble(tch_data, d, 148);

		len = 19;

		break;
	case 3: /* TCH/AFS6.7 */
		osmo_conv_decode_ber(&gsm0503_tch_afs_6_7, cB + 8,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 134, 55);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 55, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 6.7 frame */
			return -1;
		}

		tch_amr_reassemble(tch_data, d, 134);

		len = 17;

		break;
	case 2: /* TCH/AFS5.9 */
		osmo_conv_decode_ber(&gsm0503_tch_afs_5_9, cB + 8,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 118, 55);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 55, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 5.9 frame */
			return -1;
		}

		tch_amr_reassemble(tch_data, d, 118);

		len = 15;

		break;
	case 1: /* TCH/AFS5.15 */
		osmo_conv_decode_ber(&gsm0503_tch_afs_5_15, cB + 8,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 103, 49);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 49, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 5.15 frame */
			return -1;
		}

		tch_amr_reassemble(tch_data, d, 103);

		len = 13;

		break;
	case 0: /* TCH/AFS4.75 */
		osmo_conv_decode_ber(&gsm0503_tch_afs_4_75, cB + 8,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 95, 39);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 39, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 4.75 frame */
			return -1;
		}

		tch_amr_reassemble(tch_data, d, 95);

		len = 12;

		break;
	default:
		/* Unknown frame type */
		*n_bits_total = 448;
		*n_errors = *n_bits_total;
		return -1;
	}

out:
	/* Change codec request / indication, if frame is valid */
	if (codec_mode_req)
		*cmr = id;
	else
		*ft = id;

	return len;
}

/*! Perform channel encoding on a TCH/AFS channel according to TS 05.03
 *  \param[out] bursts caller-allocated output buffer for bursts bits
 *  \param[in] tch_data Codec input data in RTP payload format
 *  \param[in] len Length of \a tch_data in bytes
 *  \param[in] codec_mode_req Use CMR (1) or FT (0)
 *  \param[in] codec Array of codecs (active codec set)
 *  \param[in] codecs Number of entries in \a codec
 *  \param[in] ft Frame Type to be used for encoding (index to \a codec)
 *  \param[in] cmr Codec Mode Request (used in codec_mode_req = 1 only)
 *  \returns 0 in case of success; negative on error */
int gsm0503_tch_afs_encode(ubit_t *bursts, const uint8_t *tch_data, int len,
	int codec_mode_req, uint8_t *codec, int codecs, uint8_t ft,
	uint8_t cmr)
{
	ubit_t iB[912], cB[456], h;
	ubit_t d[244], p[6], conv[250];
	int i;
	uint8_t id;

	if (len == GSM_MACBLOCK_LEN) { /* FACCH */
		_xcch_encode_cB(cB, tch_data);

		h = 1;

		goto facch;
	}

	h = 0;

	if (codec_mode_req) {
		if (cmr >= codecs) {
			/* FIXME: CMR ID is not in codec list! */
			return -1;
		}
		id = cmr;
	} else {
		if (ft >= codecs) {
			/* FIXME: FT ID is not in codec list! */
			return -1;
		}
		id = ft;
	}

	switch (codec[ft]) {
	case 7: /* TCH/AFS12.2 */
		if (len != 31)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 244);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 81, p);

		tch_amr_merge(conv, d, p, 244, 81);

		osmo_conv_encode(&gsm0503_tch_afs_12_2, conv, cB + 8);

		break;
	case 6: /* TCH/AFS10.2 */
		if (len != 26)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 204);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 65, p);

		tch_amr_merge(conv, d, p, 204, 65);

		osmo_conv_encode(&gsm0503_tch_afs_10_2, conv, cB + 8);

		break;
	case 5: /* TCH/AFS7.95 */
		if (len != 20)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 159);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 75, p);

		tch_amr_merge(conv, d, p, 159, 75);

		osmo_conv_encode(&gsm0503_tch_afs_7_95, conv, cB + 8);

		break;
	case 4: /* TCH/AFS7.4 */
		if (len != 19)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 148);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 61, p);

		tch_amr_merge(conv, d, p, 148, 61);

		osmo_conv_encode(&gsm0503_tch_afs_7_4, conv, cB + 8);

		break;
	case 3: /* TCH/AFS6.7 */
		if (len != 17)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 134);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 55, p);

		tch_amr_merge(conv, d, p, 134, 55);

		osmo_conv_encode(&gsm0503_tch_afs_6_7, conv, cB + 8);

		break;
	case 2: /* TCH/AFS5.9 */
		if (len != 15)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 118);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 55, p);

		tch_amr_merge(conv, d, p, 118, 55);

		osmo_conv_encode(&gsm0503_tch_afs_5_9, conv, cB + 8);

		break;
	case 1: /* TCH/AFS5.15 */
		if (len != 13)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 103);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 49, p);

		tch_amr_merge(conv, d, p, 103, 49);

		osmo_conv_encode(&gsm0503_tch_afs_5_15, conv, cB + 8);

		break;
	case 0: /* TCH/AFS4.75 */
		if (len != 12)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 95);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 39, p);

		tch_amr_merge(conv, d, p, 95, 39);

		osmo_conv_encode(&gsm0503_tch_afs_4_75, conv, cB + 8);

		break;
	default:
		/* FIXME: FT %ft is not supported */
		return -1;
	}

	memcpy(cB, gsm0503_afs_ic_ubit[id], 8);

facch:
	gsm0503_tch_fr_interleave(cB, iB);

	for (i = 0; i < 8; i++) {
		gsm0503_tch_burst_map(&iB[i * 114],
			&bursts[i * 116], &h, i >> 2);
	}

	return 0;

invalid_length:
	/* FIXME: payload length %len does not comply with codec type %ft */
	return -1;
}

/*! Perform channel decoding of a TCH/AFS channel according TS 05.03
 *  \param[out] tch_data Codec frame in RTP payload format
 *  \param[in] bursts buffer containing the symbols of 8 bursts
 *  \param[in] odd Is this an odd (1) or even (0) frame number?
 *  \param[in] codec_mode_req is this CMR (1) or CMC (0)
 *  \param[in] codec array of active codecs (active codec set)
 *  \param[in] codecs number of codecs in \a codec
 *  \param ft Frame Type; Input if \a codec_mode_req = 1, Output *  otherwise
 *  \param[out] cmr Output in \a codec_mode_req = 1
 *  \param[out] n_errors Number of detected bit errors
 *  \param[out] n_bits_total Total number of bits
 *  \returns (>=4) length of bytes used in \a tch_data output buffer; ([0,3])
 *  	     codec out of range; negative on error
 */
int gsm0503_tch_ahs_decode(uint8_t *tch_data, const sbit_t *bursts, int odd,
	int codec_mode_req, uint8_t *codec, int codecs, uint8_t *ft,
	uint8_t *cmr, int *n_errors, int *n_bits_total)
{
	return gsm0503_tch_ahs_decode_dtx(tch_data, bursts, odd, codec_mode_req,
					  codec, codecs, ft, cmr, n_errors,
					  n_bits_total, NULL);
}

/*! Perform channel decoding of a TCH/AFS channel according TS 05.03
 *  \param[out] tch_data Codec frame in RTP payload format
 *  \param[in] bursts buffer containing the symbols of 8 bursts
 *  \param[in] odd Is this an odd (1) or even (0) frame number?
 *  \param[in] codec_mode_req is this CMR (1) or CMC (0)
 *  \param[in] codec array of active codecs (active codec set)
 *  \param[in] codecs number of codecs in \a codec
 *  \param ft Frame Type; Input if \a codec_mode_req = 1, Output *  otherwise
 *  \param[out] cmr Output in \a codec_mode_req = 1
 *  \param[out] n_errors Number of detected bit errors
 *  \param[out] n_bits_total Total number of bits
 *  \param[inout] dtx DTX frame type output, previous DTX frame type input
 *  \returns (>=4) length of bytes used in \a tch_data output buffer; ([0,3])
 *  	     codec out of range; negative on error
 */
int gsm0503_tch_ahs_decode_dtx(uint8_t *tch_data, const sbit_t *bursts, int odd,
	int codec_mode_req, uint8_t *codec, int codecs, uint8_t *ft,
	uint8_t *cmr, int *n_errors, int *n_bits_total, uint8_t *dtx)
{
	sbit_t iB[912], cB[456], h;
	ubit_t d[244], p[6], conv[135];
	int i, j, k, best = 0, rv, len, steal = 0, id = 0;
	ubit_t cBd[456];
	static ubit_t sid_first_dummy[64] = { 0 };
	uint8_t dtx_prev;

	/* only unmap the stealing bits */
	if (!odd) {
		for (i = 0; i < 4; i++) {
			gsm0503_tch_burst_unmap(NULL, &bursts[i * 116], &h, 0);
			steal -= h;
		}
		for (i = 2; i < 5; i++) {
			gsm0503_tch_burst_unmap(NULL, &bursts[i * 116], &h, 1);
			steal -= h;
		}
	}

	/* if we found a stole FACCH, but only at correct alignment */
	if (steal > 0) {
		for (i = 0; i < 6; i++) {
			gsm0503_tch_burst_unmap(&iB[i * 114],
				&bursts[i * 116], NULL, i >> 2);
		}

		for (i = 2; i < 4; i++) {
			gsm0503_tch_burst_unmap(&iB[i * 114 + 456],
				&bursts[i * 116], NULL, 1);
		}

		gsm0503_tch_fr_deinterleave(cB, iB);

		rv = _xcch_decode_cB(tch_data, cB, n_errors, n_bits_total);
		if (rv) {
			/* Error decoding FACCH frame */
			return -1;
		}

		return GSM_MACBLOCK_LEN;
	}

	for (i = 0; i < 4; i++) {
		gsm0503_tch_burst_unmap(&iB[i * 114],
			&bursts[i * 116], NULL, i >> 1);
	}

	gsm0503_tch_hr_deinterleave(cB, iB);

	/* Determine the DTX frame type (SID_UPDATE, ONSET etc...) */
	if (dtx) {
		osmo_sbit2ubit(cBd, cB, 456);
		dtx_prev = *dtx;
		*dtx = gsm0503_detect_ahs_dtx_frame(n_errors, n_bits_total, cBd);

		if (dtx_prev == AHS_SID_UPDATE && *dtx == AMR_OTHER) {
			/* NOTE: The AHS_SID_UPDATE frame is splitted into
			 * two half rate frames. If the id marker frame
			 * (AHS_SID_UPDATE) is detected the following frame
			 * contains the actual comfort noised data part of
			 * (AHS_SID_UPDATE_CN). */
			*dtx = AHS_SID_UPDATE_CN;

			osmo_conv_decode_ber(&gsm0503_tch_axs_sid_update,
					     cB + 16, conv, n_errors,
					     n_bits_total);
			rv = osmo_crc16gen_check_bits(&gsm0503_amr_crc14, conv,
						      35, conv + 35);
			if (rv != 0) {
				/* Error checking CRC14 for an AMR SID_UPDATE frame */
				return -1;
			}

			tch_amr_sid_update_append(conv, 1,
						  (codec_mode_req) ? codec[*ft]
						  : codec[id]);
			tch_amr_reassemble(tch_data, conv, 39);
			len = 5;
			goto out;
		} else if (*dtx == AHS_SID_FIRST_P2) {
			tch_amr_sid_update_append(sid_first_dummy, 0,
						  (codec_mode_req) ? codec[*ft]
						  : codec[id]);
			tch_amr_reassemble(tch_data, sid_first_dummy, 39);
			len = 5;
			goto out;
		} else if (*dtx == AHS_SID_UPDATE || *dtx == AHS_ONSET
			   || *dtx == AHS_SID_FIRST_INH
			   || *dtx == AHS_SID_UPDATE_INH
			   || *dtx == AHS_SID_FIRST_P1) {
			len = 0;
			goto out;
		}
	}

	for (i = 0; i < 4; i++) {
		for (j = 0, k = 0; j < 4; j++)
			k += abs(((int)gsm0503_ahs_ic_sbit[i][j]) - ((int)cB[j]));

		if (i == 0 || k < best) {
			best = k;
			id = i;
		}
	}

	/* Check if indicated codec fits into range of codecs */
	if (id >= codecs) {
		/* Codec mode out of range, return id */
		return id;
	}

	switch ((codec_mode_req) ? codec[*ft] : codec[id]) {
	case 5: /* TCH/AHS7.95 */
		osmo_conv_decode_ber(&gsm0503_tch_ahs_7_95, cB + 4,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 123, 67);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 67, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 7.95 frame */
			return -1;
		}

		for (i = 0; i < 36; i++)
			d[i + 123] = (cB[i + 192] < 0) ? 1 : 0;

		tch_amr_reassemble(tch_data, d, 159);

		len = 20;

		break;
	case 4: /* TCH/AHS7.4 */
		osmo_conv_decode_ber(&gsm0503_tch_ahs_7_4, cB + 4,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 120, 61);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 61, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 7.4 frame */
			return -1;
		}

		for (i = 0; i < 28; i++)
			d[i + 120] = (cB[i + 200] < 0) ? 1 : 0;

		tch_amr_reassemble(tch_data, d, 148);

		len = 19;

		break;
	case 3: /* TCH/AHS6.7 */
		osmo_conv_decode_ber(&gsm0503_tch_ahs_6_7, cB + 4,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 110, 55);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 55, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 6.7 frame */
			return -1;
		}

		for (i = 0; i < 24; i++)
			d[i + 110] = (cB[i + 204] < 0) ? 1 : 0;

		tch_amr_reassemble(tch_data, d, 134);

		len = 17;

		break;
	case 2: /* TCH/AHS5.9 */
		osmo_conv_decode_ber(&gsm0503_tch_ahs_5_9, cB + 4,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 102, 55);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 55, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 5.9 frame */
			return -1;
		}

		for (i = 0; i < 16; i++)
			d[i + 102] = (cB[i + 212] < 0) ? 1 : 0;

		tch_amr_reassemble(tch_data, d, 118);

		len = 15;

		break;
	case 1: /* TCH/AHS5.15 */
		osmo_conv_decode_ber(&gsm0503_tch_ahs_5_15, cB + 4,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 91, 49);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 49, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 5.15 frame */
			return -1;
		}

		for (i = 0; i < 12; i++)
			d[i + 91] = (cB[i + 216] < 0) ? 1 : 0;

		tch_amr_reassemble(tch_data, d, 103);

		len = 13;

		break;
	case 0: /* TCH/AHS4.75 */
		osmo_conv_decode_ber(&gsm0503_tch_ahs_4_75, cB + 4,
			conv, n_errors, n_bits_total);

		tch_amr_unmerge(d, p, conv, 83, 39);

		rv = osmo_crc8gen_check_bits(&gsm0503_amr_crc6, d, 39, p);
		if (rv) {
			/* Error checking CRC8 for an AMR 4.75 frame */
			return -1;
		}

		for (i = 0; i < 12; i++)
			d[i + 83] = (cB[i + 216] < 0) ? 1 : 0;

		tch_amr_reassemble(tch_data, d, 95);

		len = 12;

		break;
	default:
		/* Unknown frame type */
		*n_bits_total = 159;
		*n_errors = *n_bits_total;
		return -1;
	}

out:
	/* Change codec request / indication, if frame is valid */
	if (codec_mode_req)
		*cmr = id;
	else
		*ft = id;

	return len;
}

/*! Perform channel encoding on a TCH/AHS channel according to TS 05.03
 *  \param[out] bursts caller-allocated output buffer for bursts bits
 *  \param[in] tch_data Codec input data in RTP payload format
 *  \param[in] len Length of \a tch_data in bytes
 *  \param[in] codec_mode_req Use CMR (1) or FT (0)
 *  \param[in] codec Array of codecs (active codec set)
 *  \param[in] codecs Number of entries in \a codec
 *  \param[in] ft Frame Type to be used for encoding (index to \a codec)
 *  \param[in] cmr Codec Mode Request (used in codec_mode_req = 1 only)
 *  \returns 0 in case of success; negative on error */
int gsm0503_tch_ahs_encode(ubit_t *bursts, const uint8_t *tch_data, int len,
	int codec_mode_req, uint8_t *codec, int codecs, uint8_t ft,
	uint8_t cmr)
{
	ubit_t iB[912], cB[456], h;
	ubit_t d[244], p[6], conv[135];
	int i;
	uint8_t id;

	if (len == GSM_MACBLOCK_LEN) { /* FACCH */
		_xcch_encode_cB(cB, tch_data);

		h = 1;

		gsm0503_tch_fr_interleave(cB, iB);

		for (i = 0; i < 6; i++)
			gsm0503_tch_burst_map(&iB[i * 114], &bursts[i * 116],
				&h, i >> 2);
		for (i = 2; i < 4; i++)
			gsm0503_tch_burst_map(&iB[i * 114 + 456],
				&bursts[i * 116], &h, 1);

		return 0;
	}

	h = 0;

	if (codec_mode_req) {
		if (cmr >= codecs) {
			/* FIXME: CMR ID %d not in codec list */
			return -1;
		}
		id = cmr;
	} else {
		if (ft >= codecs) {
			/* FIXME: FT ID %d not in codec list */
			return -1;
		}
		id = ft;
	}

	switch (codec[ft]) {
	case 5: /* TCH/AHS7.95 */
		if (len != 20)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 159);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 67, p);

		tch_amr_merge(conv, d, p, 123, 67);

		osmo_conv_encode(&gsm0503_tch_ahs_7_95, conv, cB + 4);

		memcpy(cB + 192, d + 123, 36);

		break;
	case 4: /* TCH/AHS7.4 */
		if (len != 19)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 148);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 61, p);

		tch_amr_merge(conv, d, p, 120, 61);

		osmo_conv_encode(&gsm0503_tch_ahs_7_4, conv, cB + 4);

		memcpy(cB + 200, d + 120, 28);

		break;
	case 3: /* TCH/AHS6.7 */
		if (len != 17)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 134);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 55, p);

		tch_amr_merge(conv, d, p, 110, 55);

		osmo_conv_encode(&gsm0503_tch_ahs_6_7, conv, cB + 4);

		memcpy(cB + 204, d + 110, 24);

		break;
	case 2: /* TCH/AHS5.9 */
		if (len != 15)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 118);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 55, p);

		tch_amr_merge(conv, d, p, 102, 55);

		osmo_conv_encode(&gsm0503_tch_ahs_5_9, conv, cB + 4);

		memcpy(cB + 212, d + 102, 16);

		break;
	case 1: /* TCH/AHS5.15 */
		if (len != 13)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 103);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 49, p);

		tch_amr_merge(conv, d, p, 91, 49);

		osmo_conv_encode(&gsm0503_tch_ahs_5_15, conv, cB + 4);

		memcpy(cB + 216, d + 91, 12);

		break;
	case 0: /* TCH/AHS4.75 */
		if (len != 12)
			goto invalid_length;

		tch_amr_disassemble(d, tch_data, 95);

		osmo_crc8gen_set_bits(&gsm0503_amr_crc6, d, 39, p);

		tch_amr_merge(conv, d, p, 83, 39);

		osmo_conv_encode(&gsm0503_tch_ahs_4_75, conv, cB + 4);

		memcpy(cB + 216, d + 83, 12);

		break;
	default:
		/* FIXME: FT %ft is not supported */
		return -1;
	}

	memcpy(cB, gsm0503_ahs_ic_ubit[id], 4);

	gsm0503_tch_hr_interleave(cB, iB);

	for (i = 0; i < 4; i++)
		gsm0503_tch_burst_map(&iB[i * 114], &bursts[i * 116], &h, i >> 1);

	return 0;

invalid_length:
	/* FIXME: payload length %len does not comply with codec type %ft */
	return -1;
}

/*
 * GSM RACH transcoding
 */

/*
 * GSM RACH apply BSIC to parity
 *
 * p(j) = p(j) xor b(j)     j = 0, ..., 5
 * b(0) = MSB of PLMN colour code
 * b(5) = LSB of BS colour code
 */
static inline void rach_apply_bsic(ubit_t *d, uint8_t bsic, uint8_t start)
{
	int i;

	/* Apply it */
	for (i = 0; i < 6; i++)
		d[start + i] ^= ((bsic >> (5 - i)) & 1);
}

static inline int16_t rach_decode_ber(const sbit_t *burst, uint8_t bsic, bool is_11bit,
				      int *n_errors, int *n_bits_total)
{
	ubit_t conv[17];
	uint8_t ra[2] = { 0 }, nbits = is_11bit ? 11 : 8;
	int rv;

	osmo_conv_decode_ber(is_11bit ? &gsm0503_rach_ext : &gsm0503_rach, burst, conv,
			     n_errors, n_bits_total);

	rach_apply_bsic(conv, bsic, nbits);

	rv = osmo_crc8gen_check_bits(&gsm0503_rach_crc6, conv, nbits, conv + nbits);
	if (rv)
		return -1;

	osmo_ubit2pbit_ext(ra, 0, conv, 0, nbits, 1);

	return is_11bit ? ((ra[0] << 3) | (ra[1] & 0x07)) : ra[0];
}

/*! Decode the Extended (11-bit) RACH according to 3GPP TS 45.003
 *  \param[out] ra output buffer for RACH data
 *  \param[in] burst Input burst data
 *  \param[in] bsic BSIC used in this cell
 *  \returns 0 on success; negative on error (e.g. CRC error) */
int gsm0503_rach_ext_decode(uint16_t *ra, const sbit_t *burst, uint8_t bsic)
{
	int16_t r = rach_decode_ber(burst, bsic, true, NULL, NULL);

	if (r < 0)
		return r;

	*ra = r;

	return 0;
}

/*! Decode the (8-bit) RACH according to TS 05.03
 *  \param[out] ra output buffer for RACH data
 *  \param[in] burst Input burst data
 *  \param[in] bsic BSIC used in this cell
 *  \returns 0 on success; negative on error (e.g. CRC error) */
int gsm0503_rach_decode(uint8_t *ra, const sbit_t *burst, uint8_t bsic)
{
	int16_t r = rach_decode_ber(burst, bsic, false, NULL, NULL);
	if (r < 0)
		return r;

	*ra = r;
	return 0;
}

/*! Decode the Extended (11-bit) RACH according to 3GPP TS 45.003
 *  \param[out] ra output buffer for RACH data
 *  \param[in] burst Input burst data
 *  \param[in] bsic BSIC used in this cell
 *  \param[out] n_errors Number of detected bit errors
 *  \param[out] n_bits_total Total number of bits
 *  \returns 0 on success; negative on error (e.g. CRC error) */
int gsm0503_rach_ext_decode_ber(uint16_t *ra, const sbit_t *burst, uint8_t bsic,
				int *n_errors, int *n_bits_total)
{
	int16_t r = rach_decode_ber(burst, bsic, true, n_errors, n_bits_total);
	if (r < 0)
		return r;

	*ra = r;
	return 0;
}

/*! Decode the (8-bit) RACH according to TS 05.03
 *  \param[out] ra output buffer for RACH data
 *  \param[in] burst Input burst data
 *  \param[in] bsic BSIC used in this cell
 *  \param[out] n_errors Number of detected bit errors
 *  \param[out] n_bits_total Total number of bits
 *  \returns 0 on success; negative on error (e.g. CRC error) */
int gsm0503_rach_decode_ber(uint8_t *ra, const sbit_t *burst, uint8_t bsic,
			    int *n_errors, int *n_bits_total)
{
	int16_t r = rach_decode_ber(burst, bsic, false, n_errors, n_bits_total);

	if (r < 0)
		return r;

	*ra = r;

	return 0;
}

/*! Encode the (8-bit) RACH according to TS 05.03
 *  \param[out] burst Caller-allocated output burst buffer
 *  \param[in] ra Input RACH data
 *  \param[in] bsic BSIC used in this cell
 *  \returns 0 on success; negative on error */
int gsm0503_rach_encode(ubit_t *burst, const uint8_t *ra, uint8_t bsic)
{
	return gsm0503_rach_ext_encode(burst, *ra, bsic, false);
}

/*! Encode the Extended (11-bit) or regular (8-bit) RACH according to 3GPP TS 45.003
 *  \param[out] burst Caller-allocated output burst buffer
 *  \param[in] ra11 Input RACH data
 *  \param[in] bsic BSIC used in this cell
 *  \param[in] is_11bit whether given RA is 11 bit or not
 *  \returns 0 on success; negative on error */
int gsm0503_rach_ext_encode(ubit_t *burst, uint16_t ra11, uint8_t bsic, bool is_11bit)
{
	ubit_t conv[17];
	uint8_t ra[2] = { 0 }, nbits = 8;

	if (is_11bit) {
		ra[0] = (uint8_t) (ra11 >> 3);
		ra[1] = (uint8_t) (ra11 & 0x07);
		nbits = 11;
	} else
		ra[0] = (uint8_t)ra11;

	osmo_pbit2ubit_ext(conv, 0, ra, 0, nbits, 1);

	osmo_crc8gen_set_bits(&gsm0503_rach_crc6, conv, nbits, conv + nbits);

	rach_apply_bsic(conv, bsic, nbits);

	osmo_conv_encode(is_11bit ? &gsm0503_rach_ext : &gsm0503_rach, conv, burst);

	return 0;
}

/*
 * GSM SCH transcoding
 */

/*! Decode the SCH according to TS 05.03
 *  \param[out] sb_info output buffer for SCH data
 *  \param[in] burst Input burst data
 *  \returns 0 on success; negative on error (e.g. CRC error) */
int gsm0503_sch_decode(uint8_t *sb_info, const sbit_t *burst)
{
	ubit_t conv[35];
	int rv;

	osmo_conv_decode(&gsm0503_sch, burst, conv);

	rv = osmo_crc16gen_check_bits(&gsm0503_sch_crc10, conv, 25, conv + 25);
	if (rv)
		return -1;

	osmo_ubit2pbit_ext(sb_info, 0, conv, 0, 25, 1);

	return 0;
}

/*! Encode the SCH according to TS 05.03
 *  \param[out] burst Caller-allocated output burst buffer
 *  \param[in] sb_info Input SCH data
 *  \returns 0 on success; negative on error */
int gsm0503_sch_encode(ubit_t *burst, const uint8_t *sb_info)
{
	ubit_t conv[35];

	osmo_pbit2ubit_ext(conv, 0, sb_info, 0, 25, 1);

	osmo_crc16gen_set_bits(&gsm0503_sch_crc10, conv, 25, conv + 25);

	osmo_conv_encode(&gsm0503_sch, conv, burst);

	return 0;
}

/*! @} */