summaryrefslogtreecommitdiff
path: root/web/manual.md
blob: a2afb7d48255ec628b2820c34591ee8656fd4e16 (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
**Paraslash user manual**

This document describes how to install, configure and use the paraslash
network audio streaming system.  Most chapters start with a chapter
overview and conclude with an example section. We try to focus on
general concepts and on the interaction of the various pieces of the
paraslash package. Hence this user manual is not meant as a replacement
for the manual pages that describe all command line options of each
paraslash executable.

============
Introduction
============

In this chapter we give an [overview](#Overview) of the interactions
of the programs contained in the paraslash package, followed by
[brief descriptions](#The-paraslash-executables) of all executables.

Overview
--------

The core functionality of the para suite is provided by two main
applications, para_server and para_audiod. para_server maintains
the audio file database and acts as the streaming source, while
para_audiod is the streaming client. Usually, both run in the
background on different hosts but a local setup is also possible.

A simplified picture of a typical setup is as follows


	                                        .____________________.
	                                        |       ______       |
	.-----------------------.               |    .d########b.    |
	|.---------------------.|               |  .d############b   |
	||                     ||               | .d######""####//b. |
	||                     ||               | 9######(  )######P |
	||                     ||               | 'b######++######d' |
	||       Screen        ||               |  "9############P"  |
	||                     ||               |   "9a########P"    |
	||                     ||               |      `""""''       |
	|`---------------------'|               |  ________________  |
	`-----------------------'               | |________________| |
	      ___)     (___                     |____________________|
	      `-._______.-'                           loudspeaker
	            |                                     |
	            |                                     |
	            |                                     |
	      .____/ \___.     ._____________.     ._____/ \_____.
	      |          |     |             |     |             |
	      | para_gui |-----| para_audioc |-----| para_audiod |
	      |____   ___|     |_____________|     |_____   _____|
	           \ /                                   \ /
	            |                                     |
	            |                                     |
	            |                                     |
	     ._____/ \_____.                       ._____/ \_____.
	     |             |                       |             |
	     | para_client |-----------------------| para_server |
	     |_____________|                       |_____   _____|
	                                                 \ /
	                                                  |
	                                                  |
	                                              .-'"""`-.
	                                             (         )
	                                             |`-.___.-'|
	                                             |         |
	                                             |. ' " ` .|
	                                             |         |
	                                              `-.___.-'
	                                               Database

The two client programs, para_client and para_audioc communicate with
para_server and para_audiod, respectively.

para_gui controls para_server and para_audiod by executing para_client
and para_audioc. In particular, it runs a command to obtain the state
of para_audiod and para_server, and the metadata of the current audio
file. This information is pretty-printed in a curses window.

The paraslash executables
-------------------------

<h3> para_server </h3>

para_server streams binary audio data (MP3, ...) over local and/or
remote networks. It listens on a TCP port and accepts commands such
as play, stop, pause, next from authenticated clients. The components
of para_server are illustrated in the following diagram:

	______________________________________________________________________ network
	      |                                  |      |      |         |
	      |           .-'""""`-.             |      |      |         |
	      |          (          )            |      |      |         |
	.____/ \_____.   |`-.____.-'|      .____/ \____/ \____/ \____.   |
	|            |   |          |      |                         |   |
	| dispatcher |   | database |      |    senders (http/udp)   |   |
	|____   _____|   |          |      |___________   ___________|   |
	     \ /         |. ' "" ` .|                  \ /               |
	      |          |          |                   |                |
	      |           `-.____.-'                    |                |
	      |               |                         |                |
	      |               |                         |                |
	      |               |                         |                |
	      |        ._____/ \_____.        .________/ \________.      |
	      |        |             |        |                   |      |
	      |        | audio  file |________| virtual streaming |      |
	      |        |  selector   |        |      system       |      |
	      |        |_____   _____|        |________   ________|      |
	      |              \ /                       \ /               |
	      |               |                         |                |
	      |               |                         |                |
	      |               |   ._________________.   |                |
	      |               |   |                 |   |                |
	      |               `---| command handler |---'                |
	      |                   |____   ___   ____|                    |
	      |                        \ /   \ /                         |
	      |                         |     |                          |
	      |                         |     |                          |
	      |                         |     |                          |
	      `-------------------------'     `--------------------------'


Incoming connections arrive at the dispatcher which creates a process
dedicated to the connection. Its task is to authenticate the client
and to run the command handler which forwards the client request to
either the audio file selector or the virtual streaming system. Results
(if any) are sent back to the client.

The audio file selector manages audio files using various database
tables. It maintains statistics on the usage of all audio files such as
last-played time and the number of times each file was selected. It
is also responsible for selecting and loading audio files for
streaming. Additional information may be added to the database to allow
fine-grained selection based on various properties of the audio file,
including information found in (ID3) tags. Simple playlists are also
supported. It is possible to store images (album covers) and lyrics
in the database and associate these to the corresponding audio files.
The section on the [audio file selector](#The-audio-file-selector)
discusses this topic in more detail.

Another component of para_server is the virtual streaming system,
which controls the paraslash senders. During streaming it requests
small chunks of data (e.g., mp3 frames) from the audio file selector
and feeds them to the senders which forward the chunks to connected
clients.

The two senders of para_server correspond to network streaming protocols based
on HTTP or UDP. This is explained in the section on [networking](#Networking).

<h3> para_client </h3>

The client program to connect to para_server. paraslash commands
are sent to para_server and the response is dumped to STDOUT. This
can be used by any scripting language to produce user interfaces with
little programming effort.

All connections between para_server and para_client are encrypted
with a symmetric session key. For each user of paraslash you must
create a public/secret RSA key pair for authentication.

If para_client is started without non-option arguments, an interactive
session (shell) is started. Command history and command completion are
supported through libreadline.

<h3> para_audiod </h3>

The purpose of para_audiod is to download, decode and play an audio
stream received from para_server. A typical setup looks as follows.


	       .----------------------------.
	       |                            |
	       |                            |
	._____/ \_____.                .___/ \____.
	|             |     .----------|          |
	| para_server |     |   .______| receiver |
	|_____    ____|     |   |      |___   ____|
	      \ /           |   |          \ /
	       |            |   |           |
	       |            |   |           |
	       |            |   |           |
	._____/ \_____.     |   |      .___/ \____.
	|             |     |   |      |          |
	| status task |-----+   |      | filter 1 |
	|_____________|         |      |___   ____|
	                        |          \ /
	                        |           |            .____________________.
	                        |           |            |       ______       |
	.____________.          |      .___/ \____.      |    .d########b.    |
	|            |          |      |          |      |  .d############b   |
	| dispatcher |----------'      | filter 2 |      | .d######""####//b. |
	|_____   ____|                 |___   ____|      | 9######(  )######P |
	      \ /                          \ /           | 'b######++######d' |
	       |                            |            |  "9############P"  |
	       |                            |            |   "9a########P"    |
	._____/ \_____.                .___/ \____.      |      `""""''       |
	|             |                |          |      |  ________________  |
	| para_audioc |                |  writer  |------| |________________| |
	|_____________|                |__________|      |____________________|


The status task of para_audiod connects to para_server and runs the
"stat" command to retrieve the current server status. If an audio
stream is available, para_audiod starts a so-called buffer tree to
play the stream.

The buffer tree consists of a receiver, any number of filters and a
writer. The receiver downloads the audio stream from para_server and
the filters decode or modify the received data. The writer plays the
decoded stream.

The dispatcher of para_audiod listens on a local socket and runs
audiod commands on behalf of para_audioc. For example, para_gui runs
para_audioc to obtain status information about para_audiod and the
current audio file. Access to the local socket may be restricted by
means of Unix socket credentials.

<h3> para_audioc </h3>

The client program which talks to para_audiod. Used to control
para_audiod, to receive status info, or to grab the stream at any
point of the decoding process. Like para_client, para_audioc supports
interactive sessions on systems with libreadline.

<h3> para_recv </h3>

A command line HTTP/UDP stream grabber. The http mode is compatible with
arbitrary HTTP streaming sources (e.g. icecast). In addition to the three
network streaming modes, para_recv can also operate in local (afh) mode. In
this mode it writes the content of an audio file on the local file system in
complete chunks to stdout, optionally 'just in time'. This allows cutting
audio files without decoding, and it enables third-party software which is
unaware of the particular audio format to send complete frames in real time.

<h3> para_filter </h3>

A filter program that reads from STDIN and writes to STDOUT.
Like para_recv, this is an atomic building block which can be used to
assemble higher-level audio receiving facilities. It combines several
different functionalities in one tool: decoders for multiple audio
formats and a number of processing filters, among these a normalizer
for audio volume.

<h3> para_afh </h3>

A small stand-alone program that prints tech info about the given
audio file to STDOUT. It can be instructed to print a "chunk table",
an array of offsets within the audio file.

<h3> para_write </h3>

A modular audio stream writer. It supports a simple file writer
output plug-in and optional WAV/raw players for ALSA (Linux) and OSS.
para_write can also be used as a stand-alone WAV or raw audio player.

<h3> para_play </h3>

A command line audio player which supports the same audio formats as
para_server. It differs from other players in that it has an insert
and a command mode, like the vi editor. Line editing is based on
libreadline, and tab completion and command history are supported.

<h3> para_gui </h3>

Curses-based gui that presents status information obtained in a curses
window. Appearance can be customized via themes. para_gui provides
key-bindings for the most common server commands and new key-bindings
can be added easily.

<h3> para_mixer </h3>

An alarm clock and volume-fader for OSS and ALSA.

===========
Quick start
===========

This chapter lists the [necessary software](#Requirements)
that must be installed to compile the paraslash package, describes
how to [compile and install](#Installation) the paraslash
source code and the steps that have to be performed in order to
[set up](#Configuration) a typical server and client.

Requirements
------------
<h3> For the impatient </h3>
		sudo apt-get install autoconf libssl-dev m4 \
			libmad0-dev libid3tag0-dev libasound2-dev libvorbis-dev \
			libfaad-dev libspeex-dev libflac-dev libasound2-dev libao-dev \
			libreadline-dev libncurses-dev libopus-dev
		git clone https://git.tuebingen.mpg.de/lopsub
		cd lopsub && make && sudo make install && sudo ldconfig && cd ..
		git clone https://git.tuebingen.mpg.de/osl
		cd osl && make && sudo make install && sudo ldconfig && cd ..
<h3> Detailed description </h3>

In any case you will need

- [git](https://git-scm.com/). As described in more detail
[below](#Git-branches), the git source code management tool is used for
paraslash development. It is necessary for cloning the git repository
and for getting updates.

- [autoconf](ftp://ftp.gnu.org/pub/gnu/autoconf/) GNU autoconf creates
the configure file.

- [lopsub](https://people.tuebingen.mpg.de/maan/lopsub/). The long
option parser for subcommands generates the command line and config
file parsers for all paraslash executables.

- [gcc](ftp://ftp.gnu.org/pub/gnu/gcc) or [clang](http://clang.llvm.org). Any
moderately recent version of either compiler should work.

- [gnu make](ftp://ftp.gnu.org/pub/gnu/make) is also shipped with the
distribution. On BSD systems the gnu make executable is often called gmake.

- [bash](ftp://ftp.gnu.org/pub/gnu/bash). Some scripts which run
during compilation require the _Bourne again shell_.  It is most
likely already installed.

- [m4](ftp://ftp.gnu.org/pub/gnu/m4/). Some source files are generated
from templates by the m4 macro processor.

Optional:

- [libosl](https://people.tuebingen.mpg.de/maan/osl/). The _object
storage layer_ library is used by para_server. To clone the source
code repository, execute

		git clone https://git.tuebingen.mpg.de/osl

- [openssl](https://www.openssl.org/) or
[libgcrypt](https://directory.fsf.org/project/libgcrypt/). At least one
of these two libraries is needed as the backend for cryptographic
routines on both the server and the client side. Both openssl and
libgcrypt are usually shipped with the distro, but you might have
to install the development package (`libssl-dev` or `libgcrypt-dev`
on debian systems) as well.

- [flex](https://github.com/westes/flex) and
[bison](https://www.gnu.org/software/bison/) are needed to build the
mood parser of para_server. The build system will skip para_server
if these tools are not installed.

- [libmad and libid3tag](http://www.underbit.com/products/mad/). To compile in
mp3 support, the development package of both packages must be installed. They
are called `libmad0-dev` and `libid3tag0-dev` on debian-based systems.

- [ogg vorbis](https://www.xiph.org/downloads/). For ogg vorbis streams
you need libogg, libvorbis, libvorbisfile. The corresponding Debian
packages are called `libogg-dev` and `libvorbis-dev`.

- [libfaad](https://sourceforge.net/projects/faac/). For aac files
(m4a) you need libfaad (package: `libfaad-dev`).

- [speex](https://www.speex.org/). In order to stream or decode speex
files, libspeex (`libspeex-dev`) is required.

- [flac](https://xiph.org/flac/). To stream or decode files
encoded with the _Free Lossless Audio Codec_, libFLAC (`libFLAC-dev`)
must be installed.

- [alsa-lib](ftp://ftp.alsa-project.org/pub/lib/). On Linux, you will
need to have the ALSA development package `libasound2-dev` installed.

- [libao](https://ftp.osuosl.org/pub/xiph/releases/ao/). Needed to build
the ao writer (ESD, PulseAudio,...).  Debian package: `libao-dev`.

- [curses](ftp://ftp.gnu.org/pub/gnu/ncurses). Needed for
para_gui. Debian package: `libncurses-dev`.

- [GNU Readline](https://www.gnu.org/software/readline/). Only if
this library (`libreadline-dev`) is installed, para_play is built,
Without it, para_client(1) and para_audioc(1) still work, but lack
support for interactive sessions.

- [figlet](https://www.figlet.org/). The figlet theme of para_gui depends
on this utility. If it is not installed, para_gui still gets built, but the
figlet theme won't work.

To generate the web pages, the following additional tools must be installed:

- [discount](http://www.pell.portland.or.us/~orc/Code/discount/). The
HTML version of this manual and some of the paraslash web pages are
written in the Markdown markup language and are translated into html
with the converter of the *Discount* package.

- [doxygen](https://www.doxygen.nl/). The documentation
of paraslash's C sources uses the doxygen documentation system. The
conventions for documenting the source code is described in the
[Doxygen section](#Doxygen).

Installation
------------
To build the sources from git or a gitweb snapshot, run

	./autogen.sh && ./configure && make

There should be no errors but probably some warnings about missing
packages which usually implies that not all audio formats will be
supported. If headers or libs are installed at unusual locations you
might need to tell the configure script where to find them. Try

	./configure --help

to see a list of options. If the paraslash package was compiled
successfully, execute (optionally)

	make test

to run the paraslash test suite. If all tests pass, execute as root

	make install

to install executables under /usr/local/bin and the man pages under
/usr/local/man.

Configuration
-------------

<h3> Create a paraslash user </h3>

In order to control para_server at runtime you must create a paraslash
user. As authentication is based on the RSA crypto system you'll have
to create an RSA key pair. If you already have a user and an RSA key
pair, you may skip this step.

In this section we'll assume a typical setup: You would like to run
para_server on some host called server_host as user foo, and you want
to connect to para_server from another machine called client_host as
user bar.

As foo@server_host, create ~/.paraslash/server.users by typing the
following commands:

	user=bar
	target=~/.paraslash/server.users
	key=~/.paraslash/id_rsa.pub.$user
	perms=AFS_READ,AFS_WRITE,VSS_READ,VSS_WRITE
	mkdir -p ~/.paraslash
	echo "user $user $key $perms" >> $target

Next, change to the "bar" account on client_host and generate the
key pair with the commands

	ssh-keygen -q -t rsa -b 2048 -N '' -m RFC4716

This generates the two files id_rsa and id_rsa.pub in ~/.ssh.  Note
that para_server won't accept keys shorter than 2048 bits. Moreover,
para_client rejects private keys which are world-readable.

para_server only needs to know the public key of the key pair just
created. Copy this public key to server_host:

	src=~/.ssh/id_rsa.pub
	dest=.paraslash/id_rsa.pub.$LOGNAME
	scp $src foo@server_host:$dest

Finally, tell para_client to connect to server_host:

	conf=~/.paraslash/client.conf
	echo 'hostname server_host' > $conf


<h3> Start para_server </h3>

If you start para_server for the first time, the database of the audio file
selector does not exist yet. So you have to pass --init to create an empty
database. The info loglevel instructs the server to print what it is doing.

	para_server --init --loglevel info

This creates a couple of empty tables below ~/.paraslash/afs_database-0.7. You
normally don't need to look at these tables, but it's good to know that you
can start from scratch with

	rm -rf ~/.paraslash/afs_database-0.7

if something went wrong.

After the database has been created, para_server waits for incoming
connections. To connect, open a new shell as bar@client_host and try

	para_client help

This hould print the list of available subcommands. Don't proceed if this
doesn't work.

<h3> Populate the database </h3>

Next, you need to add some audio files so that para_server knows about
them. Choose an absolute path to a directory containing some audio files
and add them to the audio file table:

	para_client add /my/mp3/dir

This might take a while, so it is a good idea to start with a directory
containing not too many files. Note that the table only contains data
about the audio files found, not the files themselves.

You may print the list of all known audio files with

	para_client ls

<h3> Configure para_audiod </h3>

We will have to tell para_audiod that it should receive the audio
stream from server_host via http:

	para_audiod -l info -r '.:http -i server_host'

You should now be able to listen to the audio stream once para_server
starts streaming. To activate streaming, execute

	para_client play

Since no playlist has been specified yet, the "dummy" mode which
selects all known audio files is activated automatically. See the
section on the [audio file selector](#The-audio-file-selector) for how
to use playlists and moods to specify which files should be streamed
in which order.

Troubleshooting
---------------

To identify streaming problems try to receive, decode and play the
stream manually using para_recv, para_filter and para_write as follows.
For simplicity we assume that you're running Linux/ALSA and that only
MP3 files have been added to the database.

	para_recv -r 'http -i server_host' > file.mp3
	# (interrupt with CTRL+C after a few seconds)
	ls -l file.mp3 # should not be empty
	para_filter -f mp3dec -f wav < file.mp3 > file.wav
	ls -l file.wav # should be much bigger than file.mp3
	para_write -w alsa < file.wav

Double check what is logged by para_server and use the --loglevel
option of para_recv, para_filter and para_write to increase verbosity.

===============
User management
===============

para_server uses a challenge-response mechanism to authenticate
requests from incoming connections, similar to ssh's public key
authentication method. Authenticated connections are encrypted using
the AES stream cipher in integer counter mode.

In this chapter we briefly describe RSA and AES, and sketch the
[authentication handshake](#Client-2d-server-authentication)
between para_client and para_server. User management is discussed
in the section on [the user_list file](#The-user_list-file).
These sections are all about communication between the client and the
server. Connecting para_audiod is a different matter and is described
in a [separate section](#Connecting-para_audiod).

RSA and AES
-----------

A block cipher is a transformation which operates on fixed-length
blocks. For symmetric block ciphers the transformation is determined
by a single key for both encryption and decryption. For asymmetric
block ciphers, on the other hand, the key consists of two parts,
called the public key and the private key. A message can be encrypted
with either key and only the counterpart of that key can decrypt the
message. Asymmetric block ciphers can be used for both signing and
encrypting a message.

RSA is an asymmetric block cipher which is used in many applications,
including ssh and gpg. The RSA public key encryption and signatures
algorithms are defined in detail in RFC 2437. Paraslash relies on
RSA for authentication.

Stream ciphers XOR the input with a pseudo-random key stream to produce
the output. Decryption uses the same function calls as encryption.
Any block cipher can be turned into a stream cipher by generating the
pseudo-random key stream by encrypting successive values of a counter
(counter mode).

AES, the advanced encryption standard, is a well-known symmetric block
cipher. Paraslash employs AES in counter mode as described above to
encrypt communications. Since a stream cipher key must not be used
twice, a random key is generated for every new connection.

Client-server authentication
----------------------------

The authentication handshake between para_client and para_server goes
as follows:

- para_client connects to para_server and sends an authentication
request for a user. It does so by connecting to TCP port 2990 of the
server host. This port is called the para_server _control port_.

- para_server accepts the connection and forks a child process which
handles the incoming request. The parent process keeps listening on the
control port while the child process (also called para_server below)
continues as follows.

- para_server loads the RSA public key of that user, fills a
fixed-length buffer with random bytes, encrypts that buffer using the
public key and sends the encrypted buffer to the client. The first
part of the buffer is the challenge which is used for authentication
while the second part is the session key.

- para_client receives the encrypted buffer and decrypts it with the
user's private key, thereby obtaining the challenge buffer and the
session key. It hashes the challenge buffer with a crytographic hash
function, sends the hash value back to para_server and stores the
session key for further use.

- para_server also computes the hash value of the challenge and compares
it against what was sent back by the client.

- If the two hashes do not match, the authentication has failed and
para_server closes the connection.

- Otherwise the user is considered authenticated and the client is
allowed to proceed by sending a command to be executed. From this
point on the communication is encrypted using the stream cipher with
the session key known to both peers.

paraslash relies on the quality of the pseudo-random bytes provided
by the crypto library (openssl or libgcrypt), on the security of
the implementation of the RSA and AES crypto routines and on the
infeasibility to invert the hash function.

Neither para_server or para_client create RSA keys on their
own. This has to be done once for each user as sketched in
[Quick start](#Quick-start) and discussed in more detail
[below](#The-user_list-file).

The user_list file
------------------

At startup para_server reads the user list file which contains one
line per user. The default location of the user list file may be
changed with the --user-list option.

There should be at least one user in this file. Each user must have
an RSA key pair. The public part of the key is needed by para_server
while the private key is needed by para_client. Each line of the
user list file must be of the form

	user <username> <key> <perms>

where _username_ is an arbitrary string (usually the user's login
name), _key_ is the full path to that user's public RSA key, and
_perms_ is a comma-separated list of zero or more of the following
permission bits:

	+---------------------------------------------------------+
	| AFS_READ  | read the contents of the databases          |
	+-----------+---------------------------------------------+
	| AFS_WRITE | change database contents                    |
	+-----------+---------------------------------------------+
	| VSS_READ  | obtain information about the current stream |
	+-----------+---------------------------------------------+
	| VSS_WRITE | change the current stream                   |
	+---------------------------------------------------------+

The permission bits specify which commands the user is allowed to
execute. The output of

	para_client help

contains the permissions needed to execute the command.

It is possible to make para_server reread the user_list file by
executing the paraslash "hup" command or by sending SIGHUP to the
PID of para_server.

Connecting para_audiod
----------------------

para_audiod listens on a Unix domain socket. Those sockets are
for local communication only, so only local users can connect to
para_audiod. The default is to let any user connect but this can be
restricted on platforms that support UNIX socket credentials which
allow para_audiod to obtain the Unix credentials of the connecting
process.

Use para_audiod's --user-allow option to allow connections only for
a limited set of users.

=======================
The audio file selector
=======================

paraslash comes with a sophisticated audio file selector (AFS),
whose main task is to determine which file to stream next, based on
information on the audio files stored in a database. It communicates
also with para_client via the command handler whenever an AFS command
is executed, for example to answer a database query.

Besides the simple playlists, AFS supports audio file selection
based on _moods_ which act as a filter that limits the set of all
known audio files to those which satisfy certain criteria. It also
maintains tables containing images (e.g. album cover art) and lyrics
that can be associated with one or more audio files.

In this chapter we sketch the setup of the [AFS
process](#The-AFS-process) during server startup and proceed with the
description of the [layout](#Database-layout) of the various database
tables. The section on [playlists and moods](#Playlists-and-moods)
explains these two audio file selection mechanisms in detail
and contains practical examples. The way [file renames and content
changes](#File-renames-and-content-changes) are detected is discussed
briefly before the [Troubleshooting](#Common-problems) section
concludes the chapter.

The AFS process
---------------

On startup, para_server forks to create the AFS process which opens
the database tables. The AFS process accepts incoming connections
which arrive either on a socket shared with para_server or on the
local socket. The setup is as follows.

	          .___________________.  .______________.
	          |                   |  |              |
	          | virtual streaming |  | audio format |
	          |      system       |  |   handler    |
	          |_________   _______|  |_____   ______|
	                    \ /                \ /
	                     |                  |
	  .-'""""`-.         |                  |          .-'""""`-.
	 (          )        |                  |         (          )
	 |`-.____.-'|    .__/ \________________/ \___.    |`-.____.-'|
	 |          |    |                           |    |          |
	 |   file   |----| AFS (audio file selector) |----|    OSL   |
	 |  system  |    |         process           |    | database |
	 |          |    |___________________________|    |          |
	 |. ' "" ` .|                 |                   |. ' "" ` .|
	 |          |                 |                   |          |
	  `-.____.-'                  |                    `-.____.-'
	                     ._______/ \_______.
	                     |                 |
	                     | command handler |
	                     |_______   _______|
	                             \ /
	                              |
	                              |
	                              |
	                       ._____/ \_____.
	                       |             |
	                       | para_client |
	                       |_____________|

The virtual streaming system, which is part of the server process,
sends a notification to the shared socket whenever the current audio
file changes. The AFS process queries the database to determine the
next audio file, opens it, verifies that it has not been changed since
it was added to the database and passes the open file descriptor back
to the virtual streaming system, along with audio file meta-data such
as file name, duration, audio format and so on. The virtual streaming
system then starts to stream the file.

The command handlers of all AFS server commands use the local socket
to query or update the database. For example, the command handler of
the add command sends the path of an audio file to the local socket.
The AFS process opens the file and tries to find an audio format
handler which recognizes the file. If all goes well, a new database
entry with metadata obtained from the audio format handler is added
to the database.

Note that AFS employs
[libosl](https://people.tuebingen.mpg.de/maan/osl/), the object
storage layer library, as the database backend. This library offers
functionality similar to a relational database, but is much more
lightweight than a full featured database management system.

Database layout
---------------

Metadata about the known audio files is stored in an OSL database. This
database consists of the following tables:

- The audio file table contains path, hash and metadata of each
known file.

- The "attributes" table maps each of the 64 possible attributes to a
string.

- The "blob" tables store images, lyrics, moods, playlists. All of
these are optional.

- The "score" table describes the subset of admissible files for the
current playlist or mood.

All tables are described in more detail below.

<h3> The audio file table </h3>

This is the most important and usually also the largest table of the
AFS database. It contains the information needed to stream each audio
file. In particular the following data is stored for each audio file.

- The cryptographic hash value of the audio file contents. This is
computed once when the file is added to the database. Whenever AFS
selects this audio file for streaming the hash value is recomputed
and checked against the value stored in the database to detect
content changes.

- The time when this audio file was last played.

- The number of times the file has been played so far.

- The attribute bitmask.

- The image id which describes the image associated with this audio
file.

- The lyrics id which describes the lyrics associated with this
audio file.

- The audio format id (MP3, OGG, ...).

- An amplification value that can be used by the amplification filter
to pre-amplify the decoded audio stream.

- The chunk table. It describes the location and the timing of the
building blocks of the audio file. This is used by para_server to
send chunks of the file at appropriate times.

- The duration of the audio file.

- Tag information contained in the audio file (ID3 tags, Vorbis
comments, ...).

- The number of channels

- The encoding bitrate.

- The sampling frequency.

To add or refresh the data contained in the audio file table, the _add_
command is used. It takes the full path of either an audio file or a
directory. In the latter case, the directory is traversed recursively
and all files which are recognized as valid audio files are added to
the database.

<h3> The attribute table </h3>

The attribute table contains two columns, _name_ and _bitnum_. An
attribute is simply a name for a certain bit number in the attribute
bitmask of the audio file table.

Each of the 64 bits of the attribute bitmask can be set for each
audio file individually. Hence up to 64  different attributes may be
defined. For example, "pop", "rock", "blues", "jazz", "instrumental",
"german_lyrics", "speech", whatever. You are free to choose as
many attributes as you like and there are no naming restrictions
for attributes.

A new attribute "test" is created by

	para_client addatt test
and
	para_client lsatt

lists all available attributes. You can set the "test" attribute for
an audio file by executing

	para_client -- touch --set-attribute=test /path/to/the/audio/file

Similarly, the "test" bit can be removed from an audio file with

	para_client -- touch --unset-attribute=test /path/to/the/audio/file

Instead of a path you may use a shell wildcard pattern. The attribute
is applied to all audio files matching this pattern:

	para_client -- touch --set-attribute=test '/test/directory/*'

The command

	para_client -- ls -l=v

gives you a verbose listing of your audio files also showing which
attributes are set.

In case you wonder why the double-dash in the above commands is needed:
It tells para_client to not interpret the options after the dashes. If
you find this annoying, just say

	alias para='para_client --'

and be happy. In what follows we shall use this alias.

The "test" attribute can be dropped from the database with

	para rmatt test

Read the output of

	para help ls
	para help touch

for more information and a complete list of command line options to
these commands.

<h3> Blob tables </h3>

The image, lyrics, moods and playlists tables are all blob tables.
Blob tables consist of three columns each: The identifier which is
a positive number that is auto-incremented, the name (an arbitrary
string) and the content (the blob).

All blob tables support the same set of actions: cat, ls, mv, rm
and add. Of course, _add_ is used for adding new blobs to the table
while the other actions have the same meaning as the corresponding
Unix commands. The paraslash commands to perform these actions are
constructed as the concatenation of the table name and the action. For
example addimg, catimg, lsimg, mvimg, rmimg are the commands that
manipulate or query the image table.

The add variant of these commands is special as these commands read
the blob contents from stdin. To add an image to the image table the
command

	para addimg image_name < file.jpg

can be used.

Note that the images and lyrics are not interpreted at all, and also
the playlist and the mood blobs are only investigated when the mood
or playlist is activated with the select command.

<h3> The score table </h3>

The score table describes those audio files which are admissible for
the current mood or playlist (see below). The table has two columns:
a pointer to a row of the audio file table and a score value.

Unlike all other tables of the database, the score table remains in
memory and is never stored on disk. It is initialized at startup and
recomputed when the select command loads a new mood or playlist.

When the audio file selector is asked to open the next audio file,
it picks the row with the highest score, opens the corresponding
file and passes the file descriptor to the virtual streaming system.
At this point the last_played and the num_played fields of the selected
file are updated and the score is recomputed.

Playlists and moods
-------------------

Playlists and moods offer two different ways of specifying the set of
admissible files. A playlist in itself describes a set of admissible
files. A mood, in contrast, describes the set of admissible files in
terms of attributes and other type of information available in the
audio file table. As an example, a mood can define a filename pattern,
which is then matched against the names of audio files in the table.

<h3> Playlists </h3>

Playlists are accommodated in the playlist table of the afs database,
using the aforementioned blob format for tables. A new playlist is
created with the addpl command by specifying the full (absolute)
paths of all desired audio files, separated by newlines. Example:

	find /my/mp3/dir -name "*.mp3" | para addpl my_playlist

If _my_playlist_ already exists it is overwritten. To activate the
new playlist, execute

	para select p/my_playlist

The audio file selector will assign scores to each entry of the list,
in descending order so that files will be selected in order. If a
file could not be opened for streaming, its entry is removed from
the score table (but not from the playlist).

<h3> Moods </h3>

A mood consists of a unique name and a definition. The definition
is an expression which describes which audio files are considered
admissible. At any time at most one mood can be active, meaning
that para_server will only stream files which are admissible for the
active mood.

The expression may refer to attributes and other metadata stored in
the database. Expressions may be combined by means of logical and
arithmetical operators in a natural way. Moreover, string matching
based on regular expression or wildcard patterns is supported.

The set of admissible files is determined by applying the expression
to each audio file in turn. For a mood definition to be valid, its
expression must evaluate to a number, a string or a boolean value
("true" or "false"). For numbers, any value other than zero means the
file is admissible. For strings, any non-empty string indicates an
admissible file. For boolean values, true means admissible and false
means not admissible.  As a special case, the empty expression treats
all files as admissible.

<h3> Mood grammar </h3>

Expressions are based on a context-free grammar which distinguishes
between several types for syntactic units or groupings. The grammar
defines a set of keywords which have a type and a corresponding
semantic value, as shown in the following table.

Keyword              |    Type | Semantic value
:--------------------|--------:|:----------------------------------
`path`               |  string | Full path of the current audio file
`artist`             |  string | Content of the artist meta tag
`title`              |  string | Content of the title meta tag
`album`              |  string | Content of the album meta tag
`comment`            |  string | Content of the somment meta tag
`num_attributes_set` | integer | Number of attributes which are set
`year`               | integer | Content of the year meta tag [\*]
`num_played`         | integer | How many times the file has been streamed
`image_id`           | integer | The identifier of the (cover art) image
`lyrics_id`          | integer | The identifier of the lyrics blob
`bitrate`            | integer | The average bitrate
`frequency`          | integer | The output sample rate
`channels`           | integer | The number of channels
`duration`           | integer | The number of milliseconds
`is_set("foo")`      | boolean | True if attribute "foo" is set.

[\*] For most audio formats, the year tag is stored as a string. It
is converted to an integer by the mood parser. If the audio file
has no year tag or the content of the year tag is not a number, the
semantic value is zero. A special convention applies if the year tag
is a one-digit or a two-digit number. In this case 1900 is added to
the tag value.

Expressions may be grouped using parentheses, logical and
arithmetical operators or string matching operators. The following
table lists the available operators.

Token  | Meaning
:------|:-------
`\|\|` | Logical Or
`&&`   | Logical And
`!`    | Logical Not
`==`   | Equal (can be applied to all types)
`!=`   | Not equal. Likewise
`<`    | Less than
`<=`   | Less or equal
`>=`   | Greater or equal
`+`    | Arithmetical minus
`-`    | Binary/unary minus
`*`    | Multiplication
`/`    | Division
`=~`   | Regular expression match
`=\|`  | Filename match

Besides integers, strings and booleans there is an additional type
which describes regular expression or wildcard patterns. Patterns
are not just strings because they also include a list of flags which
modify matching behaviour.

Regular expression patterns are of the form `/pattern/[flags]`. That
is, the pattern is delimited by slashes, and is followed by zero or
more characters, each specifying a flag according to the following
table

Flag |    POSIX name | Meaning
:----|--------------:|--------
`i`  |   `REG_ICASE` | Ignore case in match
`n`  | `REG_NEWLINE` | Treat newline as an ordinary character

Note that only extended regular expression patterns are supported. See
regex(3) for details.

Wildcard patterns are similar, but the pattern must be delimited by
`'|'` characters rather than slashes. For wildcard patterns different
flags exist, as shown below.

Flag |             POSIX name | Meaning
:----|-----------------------:|--------
`n`  | `FNM_NOESCAPE`         | Treat backslash as an ordinary character
`p`  | `FNM_PATHNAME`         | Match a slash only with a slash in pattern
`P`  | `FNM_PERIOD`           | Leading period has to be matched exactly
`l`  | `FNM_LEADING_DIR` [\*] | Ignore "/\*" rest after successful matching
`i`  | `FNM_CASEFOLD` [\*]    | Ignore case in match
`e`  | `FNM_EXTMATCH` [\*\*]  | Enable extended pattern matching

[\*] Not in POSIX, but both FreeBSD and NetBSD have it.

[\*\*] GNU extension, silently ignored on non GNU systems.

See fnmatch(3) for details.

Mood definitions may contain arbitrary whitespace and comments.
A comment is a word beginning with #. This word and all remaining
characters of the line are ignored.

<h3> Example moods </h3>

* Files with no/invalid year tag: `year == 0`

* Only oldies: `year != 0 && year < 1980`

* Only 80's Rock or Metal: `(year >= 1980 && year < 1990) &&
  (is_set("rock") || is_set("metal"))`

* Files with incomplete tags: `artist == "" || title == "" || album =
"" || comment == "" || year == 0`

* Files with no attributes defined so far: `num_attributes_set == 0`

* Only newly added files: `num_played == 0`

* Only poor quality files: `bitrate < 96`

* Cope with different spellings of Motörhead: `artist =~ /mot(ö|oe{0,1})rhead/i`

* The same with extended wildcard patterns: `artist =| |mot+(o\|oe\|ö)rhead|ie`

<h3> Mood usage </h3>

To create a new mood called "my_mood", write its definition into
some temporary file, say "tmpfile", and add it to the mood table
by executing

	para addmood my_mood < tmpfile

If the mood definition is really short, you may just pipe it to the
client instead of using temporary files. Like this:

	echo "$MOOD_DEFINITION" | para addmood my_mood

There is no need to keep the temporary file since you can always use
the catmood command to get it back:

	para catmood my_mood

A mood can be activated by executing

	para select m/my_mood

Once active, the list of admissible files is shown by the ls command
if the "-a" switch is given:

	para ls -a

File renames and content changes
--------------------------------

Since the audio file selector knows the hash of each audio file that
has been added to the afs database, it recognizes if the content of
a file has changed, e.g. because an ID3 tag was added or modified.
Also, if a file has been renamed or moved to a different location,
afs will detect that an entry with the same hash value already exists
in the audio file table.

In both cases it is enough to just re-add the new file. In the
first case (file content changed), the audio table is updated, while
metadata such as the num_played and last_played fields, as well as
the attributes, remain unchanged. In the other case, when the file
is moved or renamed, only the path information is updated, all other
data remains as before.

It is possible to change the behaviour of the add command by using the
"-l" (lazy add) or the "-f" (force add) option.

Common problems
---------------

Use the debug loglevel (-l debug) to show debugging info. All paraslash
executables have a brief online help which is displayed when -h is
given. The --detailed-help option prints the full help text.

If para_server crashed or was killed by SIGKILL (signal 9), it
may refuse to start again because of "dirty osl tables". In this
case you'll have to run the oslfsck program of libosl to fix your
database:

	oslfsck -fd ~/.paraslash/afs_database-0.7

However, make sure para_server isn't running before executing oslfsck.

If you don't mind to recreate your database you can start
from scratch by removing the entire database directory, i.e.

	rm -rf ~/.paraslash/afs_database-0.7

Be aware that this removes all attribute definitions, all playlists
and all mood definitions and requires to re-initialize the tables.

Although oslfsck fixes inconsistencies in database tables it doesn't
care about the table contents. To check for invalid table contents, use

	para_client check

This prints out references to missing audio files as well as invalid
playlists and mood definitions.

Similarly, para_audiod refuses to start if its socket file exists, since
this indicates that another instance of para_audiod is running. After
a crash a stale socket file might remain and you must run

	para_audiod --force

once to fix it up.

=======================================
Audio formats and audio format handlers
=======================================

Audio formats
-------------

The following audio formats are supported by paraslash:

<h3> MP3 </h3>

Mp3, MPEG-1 Audio Layer 3, is a common audio format for audio storage,
designed as part of its MPEG-1 standard.  An MP3 file is made up of
multiple MP3 frames, which consist of a header and a data block. The
size of an MP3 frame depends on the bit rate and on the number
of channels. For a typical CD-audio file (sample rate of 44.1 kHz
stereo), encoded with a bit rate of 128 kbit, an MP3 frame is about
400 bytes large.

<h3> OGG/Vorbis </h3>

OGG is a standardized audio container format, while Vorbis is an
open source codec for lossy audio compression. Since Vorbis is most
commonly made available via the OGG container format, it is often
referred to as OGG/Vorbis. The OGG container format divides data into
chunks called OGG pages. A typical OGG page is about 4KB large. The
Vorbis codec creates variable-bitrate (VBR) data, where the bitrate
may vary considerably.

<h3> OGG/Speex </h3>

Speex is an open-source speech codec that is based on CELP (Code
Excited Linear Prediction) coding. It is designed for voice
over IP applications, has modest complexity and a small memory
footprint. Wideband and narrowband (telephone quality) speech are
supported. As for Vorbis audio, Speex bit-streams are often stored
in OGG files. As of 2012 this codec is considered obsolete since the
Oppus codec, described below, surpasses its performance in all areas.

<h3> OGG/Opus </h3>

Opus is a lossy audio compression format standardized through RFC
6716 in 2012. It combines the speech-oriented SILK codec and the
low-latency CELT (Constrained Energy Lapped Transform) codec. Like
OGG/Vorbis and OGG/Speex, Opus data is usually encapsulated in OGG
containers. All known software patents which cover Opus are licensed
under royalty-free terms.

<h3> AAC </h3>

Advanced Audio Coding (AAC) is a standardized, lossy compression
and encoding scheme for digital audio which is the default audio
format for Apple's iPhone, iPod, iTunes. Usually MPEG-4 is used as
the container format and audio files encoded with AAC have the .m4a
extension. A typical AAC frame is about 700 bytes large.

<h3> WMA </h3>

Windows Media Audio (WMA) is an audio data compression technology
developed by Microsoft. A WMA file is usually encapsulated in the
Advanced Systems Format (ASF) container format, which also specifies
how meta data about the file is to be encoded. The bit stream of WMA
is composed of superframes, each containing one or more frames of
2048 samples. For 16 bit stereo a WMA superframe is about 8K large.

<h3> FLAC </h3>

The Free Lossless Audio Codec (FLAC) compresses audio without quality
loss. It gives better compression ratios than a general purpose
compressor like zip or bzip2 because FLAC is designed specifically
for audio. A FLAC-encoded file consists of frames of varying size, up
to 16K. Each frame starts with a header that contains all information
necessary to decode the frame.

Meta data
---------

Unfortunately, each audio format has its own conventions how meta
data is added as tags to the audio file.

For MP3 files, ID3, version 1 and 2 are widely used. ID3 version 1
is rather simple but also very limited as it supports only artist,
title, album, year and comment tags. Each of these can only be at most
32 characters long. ID3, version 2 is much more flexible but requires
a separate library being installed for paraslash to support it.

Ogg vorbis, ogg speex and flac files contain meta data as Vorbis
comments, which are typically implemented as strings of the form
"[TAG]=[VALUE]". Unlike ID3 version 1 tags, one may use whichever
tags are appropriate for the content.

AAC files usually use the MPEG-4 container format for storing meta
data while WMA files wrap meta data as special objects within the
ASF container format.

paraslash only tracks the most common tags that are supported by
all tag variants: artist, title, year, album, comment. When a file
is added to the AFS database, the meta data of the file is extracted
and stored in the audio file table.

Chunks and chunk tables
-----------------------

paraslash uses the word "chunk" as common term for the building blocks
of an audio file. For MP3 files, a chunk is the same as an MP3 frame,
while for OGG files a chunk is an OGG page, etc.  Therefore the chunk
size varies considerably between audio formats, from a few hundred
bytes (MP3) up to 16K (FLAC).

The chunk table contains the offsets within the audio file that
correspond to the chunk boundaries of the file. Like the meta data,
the chunk table is computed and stored in the database whenever an
audio file is added.

The paraslash senders (see below) always send complete chunks. The
granularity for seeking is therefore determined by the chunk size.

Audio format handlers
---------------------

For each audio format paraslash contains an audio format handler whose
first task is to tell whether a given file is a valid audio file of
this type. If so, the audio file handler extracts some technical data
(duration, sampling rate, number of channels etc.), computes the
chunk table and reads the meta data.

The audio format handler code is linked into para_server and executed
via the _add_ command. The same code is also available as a stand-alone
tool, para_afh, which prints the technical data, the chunk table
and the meta data of a file. Moreover, all audio format handlers are
combined in the afh receiver which is part of para_recv and para_play.

==========
Networking
==========

Paraslash uses different network connections for control and data. para_client
communicates with para_server over a dedicated TCP control connection. To
transport audio data, separate data connections are used. For these data
connections, the UDP or HTTP transports can be chosen.

The chapter starts with the [control
service](#The-paraslash-control-service), followed by a section
on the various [streaming protocols](#Streaming-protocols)
in which the data connections are described. The way
audio file headers are embedded into the stream is discussed
[briefly](#Streams-with-headers-and-headerless-streams) before the
[example section](#Networking-examples) which illustrates typical
commands for real-life scenarios.

Both IPv4 and IPv6 are supported.

The paraslash control service
-----------------------------

para_server is controlled at runtime via the paraslash control
connection. This connection is used for server commands (play, stop,
...) as well as for afs commands (ls, select, ...).

The server listens on a TCP port and accepts connections from clients
that connect the open port. Each connection causes the server to fork
off a client process which inherits the connection and deals with that
client only. In this classical accept/fork approach the server process
is unaffected if the child dies or goes crazy for whatever reason. In
fact, the child process can not change address space of server process.

The section on [client-server
authentication](#Client-2d-server-authentication) above described the
early connection establishment from the crypto point of view. Here
it is described what happens after the connection (including crypto
setup) has been established.  There are four processes involved during
command dispatch as sketched in the following diagram.

	server_host                                   client_host
	~~~~~~~~~~~                                   ~~~~~~~~~~~

	+-----------+             connect            +-----------+
	|para_server|<------------------------------ |para_client|
	+-----------+                                +-----------+
	     |                                             ^
	     |     fork   +---+                            |
	     +----------> |AFS|                            |
	     |            +---+                            |
	     |              ^                              |
	     |              |                              |
	     |              | connect                      |
	     |              |                              |
	     |              |                              |
	     |    fork   +-----+    inherited connection   |
	     +---------->|child|<--------------------------+
	                 +-----+

There are two different kinds of commands: First there are commands
that cause the server to respond with some answer such as the list
of all audio files. All but the addblob commands (addimg, addlyr,
addpl, addmood) are of this kind. The addblob commands add contents
to the database, so they need to transfer data the other way round,
from the client to the server.

There is no knowledge about the server commands built into para_client,
so it does not know about addblob commands. Instead, the server sends
a special "awaiting data" packet for these commands. If the client
receives this packet, it sends STDIN to the server, otherwise it
dumps data from the server to STDOUT.

Streaming protocols
-------------------

A network (audio) stream usually consists of one streaming source,
the _sender_, and one or more _receivers_ which read data over the
network from the streaming source.

Senders are thus part of para_server while receivers are part of
para_audiod. Moreover, there is the stand-alone tool para_recv which
can be used to manually download a stream, either from para_server
or from a web-based audio streaming service.

The following three streaming protocols are supported by paraslash:

- HTTP. Recommended for public streams that can be played by any
player like mpg123, xmms, itunes, winamp, etc. The HTTP sender is
supported on all operating systems and all platforms.

- UDP. Recommended for multicast LAN streaming.

See the Appendix on [network protocols](#Network-protocols)
for brief descriptions of the various protocols relevant for network
audio streaming with paraslash.

It is possible to activate more than one sender simultaneously.
Senders can be controlled at run time and via config file and command
line options.

Note that audio connections are _not_ encrypted. Transport or Internet
layer encryption should be used if encrypted data connections are
needed.

UDP is the most lightweight option, since in contrast to TCP it is
connectionless. It is also the only protocol supporting IP multicast.

The HTTP sender listens on a TCP port waiting for clients to connect and
establish a connection via some protocol-defined handshake mechanism. Both
senders maintain two linked lists each: The list of all clients which are
currently connected, and the list of access control entries which determines
who is allowed to connect. IP-based access control may be configured
through config file and command line options and via the "allow" and "deny"
sender subcommands.

Upon receiving a GET request from the client, the HTTP sender sends
back a status line and a message. The body of this message is the
audio stream. This is common practice and is supported by many popular
clients which can thus be used to play a stream offered by para_server.

Unlike the HTTP sender, the UDP sender maintains only a single list, the
_target list_. This list describes the set of clients to which the stream is
sent. There is no list for access control and no "allow" and "deny" commands
for the UDP sender. Instead, the "add" and "delete" commands can be used to
modify the target list.

Since UDP only offers an unreliable datagram-based transport, additional
measures are necessary to guard against disruptions over networks that are
lossy or which may be subject to interference (as is for instance the case
with WiFi). Paraslash uses FEC (Forward Error Correction) to guard against
packet losses and reordering. The stream is FEC-encoded before it is sent
through the UDP socket and must be decoded accordingly on the receiver side.

The packet size and the amount of redundancy introduced by FEC can
be configured via the FEC parameters which are dictated by server
and may also be configured through the "sender" command.  The FEC
parameters are encoded in the header of each network packet, so no
configuration is necessary on the receiver side. See the section on
[FEC](#Forward-error-correction) below.

Streams with headers and headerless streams
-------------------------------------------

For OGG/Vorbis, OGG/Speex and wma streams, some of the information
needed to decode the stream is only contained in the audio file
header of the container format but not in each data chunk. Clients
must be able to obtain this information in case streaming starts in
the middle of the file or if para_audiod is started while para_server
is already sending a stream.

This is accomplished in different ways, depending on the streaming
protocol. For the connection-oriented HTTP stream, the audio file header is
sent prior to audio file data. This technique however does not work for the
connectionless UDP transport. Hence the audio file header is periodically
being embedded into the UDP audio data stream. By default, the header is
resent after five seconds. The receiver has to wait until the next header
arrives before it can start decoding the stream.

Networking examples
-------------------

The "si" (server info) command lists some information about the
currently running server process.

-> Show PIDs, number of connected clients, uptime, and more:

	para_client si

By default para_server activates the HTTP sender on startup. This can be
changed via command line options or para_server's config file.

-> List config file options for senders:

	para_server -h

-> Receive FEC-encoded multicast stream and write the output into a file:

	filename=foo
	para_recv -r udp > $filename

-> Receive this (FEC-encoded) unicast stream:

	filename=foo
	para_recv -r 'udp -i 0.0.0.0' > $filename

-> Create a minimal config for para_audiod for HTTP streams:

	c=$HOME/.paraslash/audiod.conf.min; s=server.foo.com
	echo receiver \".:http -i $s\" > $c
	para_audiod --config $c

=======
Filters
=======

A paraslash filter is a module which transforms an input stream into
an output stream. Filters are included in the para_audiod executable
and in the stand-alone tool para_filter which usually contains the
same modules.

While para_filter reads its input stream from STDIN and writes
the output to STDOUT, the filter modules of para_audiod are always
connected to a receiver which produces the input stream and a writer
which absorbs the output stream.

Some filters depend on a specific library and are not compiled in
if this library was not found at compile time. To see the list of
supported filters, run para_filter and para_audiod with the --help
option. The output looks similar to the following:

	Available filters:
	        compress wav amp fecdec wmadec prebuffer oggdec aacdec mp3dec

Out of these filter modules, a chain of filters can be constructed,
much in the way Unix pipes can be chained, and analogous to the use
of modules in gstreamer: The output of the first filter becomes the
input of the second filter. There is no limitation on the number of
filters and the same filter may occur more than once.

Like receivers, each filter has its own command line options which
must be quoted to protect them from the command line options of
the driving application (para_audiod or para_filter). Example:

	para_filter -f 'mp3dec --ignore-crc' -f 'compress --damp 1'

For para_audiod, each audio format has its own set of filters. The
name of the audio format for which the filter should be applied can
be used as the prefix for the filter option. Example:

	para_audiod -f 'mp3:prebuffer --duration 300'

The "mp3" prefix above is actually interpreted as a POSIX extended
regular expression. Therefore

	para_audiod -f '.:prebuffer --duration 300'

activates the prebuffer filter for all supported audio formats (because
"." matches all audio formats) while

	para_audiod -f 'wma|ogg:prebuffer --duration 300'

activates it only for wma and ogg streams.

Decoders
--------

For each supported audio format there is a corresponding filter
which decodes audio data in this format to 16 bit PCM data which
can be directly sent to the sound device or any other software that
operates on undecoded PCM data (visualizers, equalizers etc.). Such
filters are called _decoders_ in general, and xxxdec is the name of
the paraslash decoder for the audio format xxx. For example, the mp3
decoder is called mp3dec.

Note that the output of the decoder is about 10 times larger than
its input. This means that filters that operate on the decoded audio
stream have to deal with much more data than filters that transform
the audio stream before it is fed to the decoder.

Paraslash relies on external libraries for most decoders, so these
libraries must be installed for the decoder to be included in the
executables. For example, the mp3dec filter depends on the mad library.

Forward error correction
------------------------

As already mentioned [earlier](#Streaming-protocols), paraslash uses forward
error correction (FEC) for the unreliable UDP transport. FEC is a technique
which was invented already in 1960 by Reed and Solomon and which is widely
used for the parity calculations of storage devices (RAID arrays). It is
based on the algebraic concept of finite fields, today called Galois fields,
in honour of the mathematician Galois (1811-1832). The FEC implementation
of paraslash is based on code by Luigi Rizzo.

Although the details require a sound knowledge of the underlying
mathematics, the basic idea is not hard to understand: For positive
integers k and n with k < n it is possible to compute for any k given
data bytes d_1, ..., d_k the corresponding r := n -k parity bytes p_1,
..., p_r such that all data bytes can be reconstructed from *any*
k bytes of the set

	{d_1, ..., d_k, p_1, ..., p_r}.

FEC-encoding for unreliable network transports boils down to slicing
the audio stream into groups of k suitably sized pieces called _slices_
and computing the r corresponding parity slices. This step is performed
in para_server which then sends both the data and the parity slices
over the unreliable network connection. If the client was able
to receive at least k of the n = k + r slices, it can reconstruct
(FEC-decode) the original audio stream.

From these observations it is clear that there are three different
FEC parameters: The slice size, the number of data slices k, and the
total number of slices n. It is crucial to choose the slice size
such that no fragmentation of network packets takes place because
FEC only guards against losses and reordering but fails if slices are
received partially.

FEC decoding in paralash is performed through the fecdec filter which
usually is the first filter (there can be other filters before fecdec
if these do not alter the audio stream).

Volume adjustment (amp and compress)
------------------------------------

The amp and the compress filter both adjust the volume of the audio
stream. These filters operate on uncompressed audio samples. Hence
they are usually placed directly after the decoding filter. Each
sample is multiplied with a scaling factor (>= 1) which makes amp
and compress quite expensive in terms of computing power.

<h3> amp </h3>

The amp filter amplifies the audio stream by a fixed scaling factor
that must be known in advance. For para_audiod this factor is derived
from the amplification field of the audio file's entry in the audio
file table while para_filter uses the value given at the command line.

The optimal scaling factor F for an audio file is the largest real
number F >= 1 such that after multiplication with F all samples still
fit into the sample interval [-32768, 32767]. One can use para_filter
in combination with the sox utility to compute F:

	para_filter -f mp3dec -f wav < file.mp3 | sox -t wav - -e stat -v

The amplification value V which is stored in the audio file table,
however, is an integer between 0 and 255 which is connected to F
through the formula

	V = (F - 1) * 64.

To store V in the audio file table, the command

	para_client -- touch -a=V file.mp3

is used. The reader is encouraged to write a script that performs
these computations :)

<h3> compress </h3>

Unlike the amplification filter, the compress filter adjusts the volume
of the audio stream dynamically without prior knowledge about the peak
value. It maintains the maximal volume of the last n samples of the
audio stream and computes a suitable amplification factor based on that
value and the various configuration options. It tries to chose this
factor such that the adjusted volume meets the desired target level.

Note that it makes sense to combine amp and compress.

Misc filters (wav and prebuffer)
--------------------------------

These filters are rather simple and do not modify the audio stream at
all. The wav filter is only useful with para_filter and in connection
with a decoder. It asks the decoder for the number of channels and the
sample rate of the stream and adds a Microsoft wave header containing
this information at the beginning. This allows writing wav files
rather than raw PCM files (which do not contain any information about
the number of channels and the sample rate).

The prebuffer filter simply delays the output until the given time has
passed (starting from the time the first byte was available in its
input queue) or until the given amount of data has accumulated. It
is mainly useful for para_audiod if the standard parameters result
in buffer underruns.

Both filters require almost no additional computing time, even when
operating on uncompressed audio streams, since data buffers are simply
"pushed down" rather than copied.

======
Output
======

Once an audio stream has been received and decoded to PCM format,
it can be sent to a sound device for playback. This part is performed
by paraslash _writers_ which are described in this chapter.

Writers
-------

A paraslash writer acts as a data sink that consumes but does not
produce audio data. Paraslash writers operate on the client side and
are contained in para_audiod and in the stand-alone tool para_write.

The para_write program reads uncompressed audio data from STDIN. If
this data starts with a wav header, sample rate, sample format and
channel count are read from the header. Otherwise CD audio (44.1KHz
16 bit little endian, stereo) is assumed but this can be overridden
by command line options. para_audiod, on the other hand, obtains
the sample rate and the number of channels from the decoder.

Like receivers and filters, each writer has an individual set of
command line options, and for para_audiod writers can be configured
per audio format separately. It is possible to activate more than
one writer for the same stream simultaneously.

OS-dependent APIs
-----------------

Unfortunately, the various flavours of Unix on which paraslash
runs on have different APIs for opening a sound device and starting
playback. Hence for each such API there is a paraslash writer that
can play the audio stream via this API.

- *ALSA*. The _Advanced Linux Sound Architecture_ is only available on
Linux systems. Although there are several mid-layer APIs in use by
the various Linux distributions (ESD, Jack, PulseAudio), paraslash
currently supports only the low-level ALSA API which is not supposed
to be change. ALSA is very feature-rich, in particular it supports
software mixing via its DMIX plugin. ALSA is the default writer on
Linux systems.

- *OSS*. The _Open Sound System_ is the only API on \*BSD Unixes and
is also available on Linux systems, usually provided by ALSA as an
emulation for backwards compatibility. This API is rather simple but
also limited. For example only one application can open the device
at any time. The OSS writer is activated by default on BSD Systems.

- *FILE*. The file writer allows capturing the audio stream and
writing the PCM data to a file on the file system rather than playing
it through a sound device. It is supported on all platforms and is
always compiled in.

- *AO*. _Libao_ is a cross-platform audio library which supports a wide
variety of platforms including PulseAudio (gnome), ESD (Enlightened
Sound Daemon), AIX, Solaris and IRIX.  The ao writer plays audio
through an output plugin of libao.

Examples
--------

-> Use the OSS writer to play a wav file:

	para_write --writer oss < file.wav

-> Enable ALSA software mixing for mp3 streams:

	para_audiod --writer 'mp3:alsa -d plug:swmix'


===
Gui
===

para_gui receives status information from para_audiod and displays this
information in the upper part of a terminal window. The lower part shows
log messages or command output.

Key bindings
------------

It is possible to bind keys to arbitrary commands via custom
key-bindings. Besides the internal keys which can not be changed (help,
quit, loglevel, version...), the following flavours of key-bindings
are supported:

- external: Shutdown curses before launching the given command. Useful for
starting other ncurses programs from within para_gui.

- display: Launch the command and display its stdout in para_gui's
bottom window.

- para: Like display, but start "para_client <specified command>"
instead of "<specified command>".

The general form of a key binding is

	key_map k:m:c

which maps key k to command c using mode m. Mode may be x, d or p
for external, display and paraslash commands, respectively.

Themes
------

Currently there are three themes for para_gui. Each implements a different
design for the upper window. The "." and "," keys are bound to internal
commands which cycle through the available themes.

Gui examples
------------

-> Show server info:

	key_map "i:p:si"

-> Jump to the middle of the current audio file by pressing F5:

	key_map "<F5>:p:jmp 50"

-> vi-like bindings for jumping around:

	key_map "l:p:ff 10"
	key_map "h:p:ff 10-"
	key_map "w:p:ff 60"
	key_map "b:p:ff 60-"

-> Print the current date and time:

	key_map "D:d:date"

-> Call other curses programs:

	key_map "U:x:aumix"
	key_map "!:x:/bin/bash"
	key_map "^E:x:/bin/sh -c 'vi ~/.paraslash/gui.conf'"

===========
Development
===========

Contributing
------------

Paraslash is an open source project and contributions are
welcome. Here's a list of things you can do to help the project:

- Report problems with building, installing or running the software.
  In particular, test the experimental git branches ("next" and "pu").
  This helps to identify and fix problems before the code gets merged
  and thus keeps the master branch as stable as possible.
- Proofread the documentation (manual, web pages, man pages, source
  code documentation) and point out unclear or poorly written parts. If
  you are a native English speaker you will easily find a lot of text
  that could be improved.
- Run analysis tools (coverity, afl, sparse, etc.) and report issues
  found by those tools.
- Suggest new features you would like to see implemented.
- Compile and test on your favorite architecture or operating
  system. The code is tested only on a limited set of systems, so you
  will probably encounter problems when building on different systems.
- Post about paraslash on your blog or on social networks.
- Build and maintain Debian/RPM packages for your favorite distribution.

Note that there is no mailing list, no bug tracker and no discussion
forum for paraslash. If you'd like to contribute, or have questions
about contributing, send email to Andre Noll <maan@tuebingen.mpg.de>.
New releases are announced by email. If you would like to receive
these announcements, contact the author through the above address.

Git branches
------------

Paraslash has been developed using the git source code management
tool since 2006. Development is organized roughly in the same spirit
as the git development itself, as described below.

The following text passage is based on "A note from the maintainer",
written by Junio C Hamano, the maintainer of git.

There are three integration branches in the paraslash repository that track
the source tree: "master", "next", and "pu".

The "master" branch is meant to contain what is well tested and ready to be
used in a production setting. It is never rewound, and it is expected to be
more stable than any of the released versions.

A trivial and safe enhancement goes directly on top of "master".
New development does not usually happen on "master", however. Instead,
a separate topic branch is forked from "master", and the new code is first
tested in isolation. Usually there are a handful such topic branches that
are running ahead of "master". These branches are not pushed to the public
repository, however.

Topic branches often start out as "great idea" but also as "not yet working",
and "meticulously undocumented". With some more work they eventually become
feature complete, have no more known bugs and are fully documented. The "next"
branch combines topic branches that have reached this level of maturity. It
might not be quite rock-solid production ready, but is expected to work more
or less without major breakage.

The "next" branch always contains "master". Like "master", it will usually
not be rewound, and the same is true for all topic branches that have been
merged into "next", so it is safe to build on top of these. However, at times
"next" is rebuilt from the tip of "master" to get rid of merge commits that
will never be in "master". The commit that replaces "next" has the identical
tree but a different ancestry from the tip of "master".

The "pu" (proposed updates) branch always contains "next". Additionally, it
bundles the remainder of the topic branches. Hence "pu" contains all code that
is currently in development, mature or not. The topic branches that are only
in "pu" are subject to rebasing, and "pu" is rebuilt from "next" frequently.

Topics generally graduate from "pu" via "next" to "master". When a topic
graduates to "master", it is considered done and the topic branch is deleted.
The commits of the former topic branch will appear in the next release
because releases are cut from "master".

New versions are released by creating a signed tag whose name consists of
a leading "v" followed by three decimal digits separated by dots (e.g.,
v0.4.2). Releases happen when a serious bug has been fixed or significant
changes have been incorporated. There is no fixed release schedule.

Coding Style
------------

The preferred coding style for paraslash coincides more or less
with the style of the Linux kernel. So rather than repeating what is
written [there](https://www.kernel.org/doc/Documentation/process/coding-style.rst),
here are the most important points.

- Burn the GNU coding standards.
- Never use spaces for indentation.
- Tabs are 8 characters, and thus indentations are also 8 characters.
- Don't put multiple assignments on a single line.
- Avoid tricky expressions.
- Don't leave whitespace at the end of lines.
- The limit on the length of lines is 80 columns.
- Use K&R style for placing braces and spaces:
<pre>
		if (x is true) {
			we do y
		}
</pre>
- Use a space after (most) keywords.
- Do not add spaces around (inside) parenthesized expressions.
- Use one space around (on each side of) most binary and ternary operators.
- Do not use cute names like ThisVariableIsATemporaryCounter, call it tmp.
- Mixed-case names are frowned upon.
- Descriptive names for global variables are a must.
- Avoid typedefs.
- Functions should be short and sweet, and do just one thing.
- The number of local variables shouldn't exceed 10.
- Gotos are fine if they improve readability and reduce nesting.
- Don't use C99-style "// ..." comments.
- Names of macros defining constants and labels in enums are capitalized.
- Enums are preferred when defining several related constants.
- Always use the paraslash wrappers for allocating memory.
- If the name of a function is an action or an imperative.
  command, the function should return an error-code integer
  (<0 means error, >=0 means success). If the name is a
  predicate, the function should return a "succeeded" boolean.

Doxygen
-------

Doxygen is a documentation system for various programming
languages. The API reference on the paraslash web page is generated
by doxygen.

It is more illustrative to look at the source code for examples than
to describe the conventions in this manual, so we only describe which
parts of the code need doxygen comments, but leave out details on
documentation conventions.

As a rule, only the public part of the C source is documented with
Doxygen. This includes structures, defines and enumerations in header
files as well as public (non-static) C functions.  These should be
documented completely. For example, each parameter and the return
value of a public function should get a descriptive doxygen comment.

No doxygen comments are necessary for static functions and for
structures and enumerations in C files (which are used only within
this file). This does not mean, however, that those entities need
no documentation at all. Instead, common sense should be applied to
document what is not obvious from reading the code.

========
Appendix
========

Network protocols
-----------------

<h3> IP </h3>

The _Internet Protocol_ is the primary networking protocol used for
the Internet. All protocols described below use IP as the underlying
layer. Both the prevalent IPv4 and the next-generation IPv6 variant
are being deployed actively worldwide.

<h3> Connection-oriented and connectionless protocols </h3>

Connectionless protocols differ from connection-oriented ones in
that state associated with the sending/receiving endpoints is treated
implicitly. Connectionless protocols maintain no internal knowledge
about the state of the connection. Hence they are not capable of
reacting to state changes, such as sudden loss or congestion on the
connection medium. Connection-oriented protocols, in contrast, make
this knowledge explicit. The connection is established only after
a bidirectional handshake which requires both endpoints to agree
on the state of the connection, and may also involve negotiating
specific parameters for the particular connection. Maintaining an
up-to-date internal state of the connection also in general means
that the sending endpoints perform congestion control, adapting to
qualitative changes of the connection medium.

<h3> Reliability </h3>

In IP networking, packets can be lost, duplicated, or delivered
out of order, and different network protocols handle these
problems in different ways. We call a transport-layer protocol
_reliable_, if it turns the unreliable IP delivery into an ordered,
duplicate- and loss-free delivery of packets. Sequence numbers
are used to discard duplicates and re-arrange packets delivered
out-of-order. Retransmission is used to guarantee loss-free
delivery. Unreliable protocols, in contrast, do not guarantee ordering
or data integrity.

<h3> Classification </h3>

With these definitions the protocols which are used by paraslash for
steaming audio data may be classified as follows.

	- HTTP/TCP: connection-oriented, reliable,
	- UDP: connectionless, unreliable,

Below we give a short descriptions of these protocols.

<h3> TCP </h3>

The _Transmission Control Protocol_ provides reliable, ordered delivery of a
stream and a classic window-based congestion control. In contrast to UDP (see
below), TCP does not have record-oriented or datagram-based syntax, i.e. it
provides a stream which is unaware and independent of any record (packet)
boundaries. TCP is used extensively by many application layers. Besides HTTP
(the Hypertext Transfer Protocol), also FTP (the File Transfer protocol),
SMTP (Simple Mail Transfer Protocol), SSH (Secure Shell) all sit on top of TCP.

<h3> UDP </h3>

The _User Datagram Protocol_ is the simplest transport-layer protocol,
built as a thin layer directly on top of IP. For this reason, it offers
the same best-effort service as IP itself, i.e. there is no detection
of duplicate or reordered packets. Being a connectionless protocol,
only minimal internal state about the connection is maintained, which
means that there is no protection against packet loss or network
congestion. Error checking and correction (if at all) are performed
in the application.

<h3> HTTP </h3>

The _Hypertext Transfer Protocol_ is an application layer protocol
on top of TCP. It is spoken by web servers and is most often used
for web services.  However, as can be seen by the many Internet radio
stations and YouTube/Flash videos, http is by far not limited to the
delivery of web pages only. Being a simple request/response based
protocol, the semantics of the protocol also allow the delivery of
multimedia content, such as audio over http.

<h3> Multicast </h3>

IP multicast is not really a protocol but a technique for one-to-many
communication over an IP network. The challenge is to deliver information to
a group of destinations simultaneously using the most efficient strategy to
send the messages over each link of the network only once. This has benefits
for streaming multimedia: the standard one-to-one unicast offered by TCP means
that n clients listening to the same stream also consume n-times the resources,
whereas multicast requires to send the stream just once, irrespective of
the number of receivers. Since it would be costly to maintain state for
each listening receiver, multicast often implies connectionless transport,
which is the reason that it is currently only available via UDP.

Abstract socket namespace
-------------------------
UNIX domain sockets are a traditional way to communicate between
processes on the same machine. They are always reliable (see above)
and don't reorder datagrams. Unlike TCP and UDP, UNIX domain sockets
support passing open file descriptors or process credentials to
other processes.

The usual way to set up a UNIX domain socket (as obtained from
socket(2)) for listening is to first bind the socket to a file system
pathname and then call listen(2), then accept(2). Such sockets are
called _pathname sockets_ because bind(2) creates a special socket
file at the specified path. Pathname sockets allow unrelated processes
to communicate with the listening process by binding to the same path
and calling connect(2).

There are two problems with pathname sockets:

	* The listing process must be able to (safely) create the
	socket special in a directory which is also accessible to
	the connecting process.

	* After an unclean shutdown of the listening process, a stale
	socket special may reside on the file system.

The abstract socket namespace is a non-portable Linux feature which
avoids these problems. Abstract sockets are still bound to a name,
but the name has no connection with file system pathnames.

License
-------

Paraslash is licensed under the GPL, version 2. Most of the code
base has been written from scratch, and those parts are GPL V2
throughout. Notable exceptions are FEC and the WMA decoder. See the
corresponding source files for licencing details for these parts. Some
code sniplets of several other third party software packages have
been incorporated into the paraslash sources, for example log message
coloring was taken from the git sources. These third party software
packages are all published under the GPL or some other license
compatible to the GPL.

Acknowledgements
----------------

Many thanks to Gerrit Renker who read an early draft of this manual
and contributed significant improvements.

==========
References
==========

RFCs
----

- [RFC 768](https://www.ietf.org/rfc/rfc768.txt) (1980): User Datagram
Protocol

- [RFC 791](https://www.ietf.org/rfc/rfc791.txt) (1981): Internet
Protocol

- [RFC 2437](https://www.ietf.org/rfc/rfc2437.txt) (1998): RSA
Cryptography Specifications

- [RFC 6716](https://www.ietf.org/rfc/rfc6716.txt) (2012): Definition
of the Opus Audio Codec

Application web pages
---------------------

- [paraslash](https://people.tuebingen.mpg.de/maan/paraslash/)
- [mpg123](http://www.mpg123.de/)
- [gstreamer](https://gstreamer.freedesktop.org/)
- [icecast](https://www.icecast.org/)
- [Audio Compress](https://github.com/fluffy-critter/audiocompress)

External documentation
----------------------

- [Effective Erasure Codes for reliable Computer Communication
Protocols](http://info.iet.unipi.it/~luigi/fec_ccr.ps.gz) by Luigi
Rizzo

Code
----
- [Original FEC
implementation](http://info.iet.unipi.it/~luigi/vdm.tar.gz) by
Luigi Rizzo)