]> git.tuebingen.mpg.de Git - paraslash.git/blob - web/manual.md
Let para_play depend on libreadline.
[paraslash.git] / web / manual.md
1 **Paraslash user manual**
2
3 This document describes how to install, configure and use the paraslash
4 network audio streaming system.  Most chapters start with a chapter
5 overview and conclude with an example section. We try to focus on
6 general concepts and on the interaction of the various pieces of the
7 paraslash package. Hence this user manual is not meant as a replacement
8 for the manual pages that describe all command line options of each
9 paraslash executable.
10
11 ============
12 Introduction
13 ============
14
15 In this chapter we give an [overview](#Overview) of the interactions
16 of the programs contained in the paraslash package, followed by
17 [brief descriptions](#The.paraslash.executables) of all executables.
18
19 Overview
20 --------
21
22 The core functionality of the para suite is provided by two main
23 applications, para_server and para_audiod. para_server maintains
24 the audio file database and acts as the streaming source, while
25 para_audiod is the streaming client. Usually, both run in the
26 background on different hosts but a local setup is also possible.
27
28 A simplified picture of a typical setup is as follows
29
30
31                                                 .____________________.
32                                                 |       ______       |
33         .-----------------------.               |    .d########b.    |
34         |.---------------------.|               |  .d############b   |
35         ||                     ||               | .d######""####//b. |
36         ||                     ||               | 9######(  )######P |
37         ||                     ||               | 'b######++######d' |
38         ||       Screen        ||               |  "9############P"  |
39         ||                     ||               |   "9a########P"    |
40         ||                     ||               |      `""""''       |
41         |`---------------------'|               |  ________________  |
42         `-----------------------'               | |________________| |
43               ___)     (___                     |____________________|
44               `-._______.-'                           loudspeaker
45                     |                                     |
46                     |                                     |
47                     |                                     |
48               .____/ \___.     ._____________.     ._____/ \_____.
49               |          |     |             |     |             |
50               | para_gui |-----| para_audioc |-----| para_audiod |
51               |____   ___|     |_____________|     |_____   _____|
52                    \ /                                   \ /
53                     |                                     |
54                     |                                     |
55                     |                                     |
56              ._____/ \_____.                       ._____/ \_____.
57              |             |                       |             |
58              | para_client |-----------------------| para_server |
59              |_____________|                       |_____   _____|
60                                                          \ /
61                                                           |
62                                                           |
63                                                       .-'"""`-.
64                                                      (         )
65                                                      |`-.___.-'|
66                                                      |         |
67                                                      |. ' " ` .|
68                                                      |         |
69                                                       `-.___.-'
70                                                        Database
71
72 The two client programs, para_client and para_audioc communicate with
73 para_server and para_audiod, respectively.
74
75 para_gui controls para_server and para_audiod by executing para_client
76 and para_audioc. In particular, it runs a command to obtain the state
77 of para_audiod and para_server, and the metadata of the current audio
78 file. This information is pretty-printed in a curses window.
79
80 The paraslash executables
81 -------------------------
82
83 <h3> para_server </h3>
84
85 para_server streams binary audio data (MP3, ...) over local and/or
86 remote networks. It listens on a TCP port and accepts commands such
87 as play, stop, pause, next from authenticated clients. The components
88 of para_server are illustrated in the following diagram:
89
90         ______________________________________________________________________ network
91               |                                  |      |      |         |
92               |           .-'""""`-.             |      |      |         |
93               |          (          )            |      |      |         |
94         .____/ \_____.   |`-.____.-'|      .____/ \____/ \____/ \____.   |
95         |            |   |          |      |                         |   |
96         | dispatcher |   | database |      | senders (http/udp/dccp) |   |
97         |____   _____|   |          |      |___________   ___________|   |
98              \ /         |. ' "" ` .|                  \ /               |
99               |          |          |                   |                |
100               |           `-.____.-'                    |                |
101               |               |                         |                |
102               |               |                         |                |
103               |               |                         |                |
104               |        ._____/ \_____.        .________/ \________.      |
105               |        |             |        |                   |      |
106               |        | audio  file |________| virtual streaming |      |
107               |        |  selector   |        |      system       |      |
108               |        |_____   _____|        |________   ________|      |
109               |              \ /                       \ /               |
110               |               |                         |                |
111               |               |                         |                |
112               |               |   ._________________.   |                |
113               |               |   |                 |   |                |
114               |               `---| command handler |---'                |
115               |                   |____   ___   ____|                    |
116               |                        \ /   \ /                         |
117               |                         |     |                          |
118               |                         |     |                          |
119               |                         |     |                          |
120               `-------------------------'     `--------------------------'
121
122
123 Incoming connections arrive at the dispatcher which creates a process
124 dedicated to the connection. Its task is to authenticate the client
125 and to run the command handler which forwards the client request to
126 either the audio file selector or the virtual streaming system. Results
127 (if any) are sent back to the client.
128
129 The audio file selector manages audio files using various database
130 tables. It maintains statistics on the usage of all audio files such as
131 last-played time and the number of times each file was selected. It
132 is also responsible for selecting and loading audio files for
133 streaming. Additional information may be added to the database to allow
134 fine-grained selection based on various properties of the audio file,
135 including information found in (ID3) tags. Simple playlists are also
136 supported. It is possible to store images (album covers) and lyrics
137 in the database and associate these to the corresponding audio files.
138 The section on the [audio file selector](#The.audio.file.selector)
139 discusses this topic in more detail.
140
141 Another component of para_server is the virtual streaming system,
142 which controls the paraslash senders. During streaming it requests
143 small chunks of data (e.g., mp3 frames) from the audio file selector
144 and feeds them to the senders which forward the chunks to connected
145 clients.
146
147 The three senders of para_server correspond to network streaming
148 protocols based on HTTP, DCCP, or UDP. This is explained in the
149 section on [networking](#Networking).
150
151 <h3> para_client </h3>
152
153 The client program to connect to para_server. paraslash commands
154 are sent to para_server and the response is dumped to STDOUT. This
155 can be used by any scripting language to produce user interfaces with
156 little programming effort.
157
158 All connections between para_server and para_client are encrypted
159 with a symmetric session key. For each user of paraslash you must
160 create a public/secret RSA key pair for authentication.
161
162 If para_client is started without non-option arguments, an interactive
163 session (shell) is started. Command history and command completion are
164 supported through libreadline.
165
166 <h3> para_audiod </h3>
167
168 The purpose of para_audiod is to download, decode and play an audio
169 stream received from para_server. A typical setup looks as follows.
170
171
172                .----------------------------.
173                |                            |
174                |                            |
175         ._____/ \_____.                .___/ \____.
176         |             |     .----------|          |
177         | para_server |     |   .______| receiver |
178         |_____    ____|     |   |      |___   ____|
179               \ /           |   |          \ /
180                |            |   |           |
181                |            |   |           |
182                |            |   |           |
183         ._____/ \_____.     |   |      .___/ \____.
184         |             |     |   |      |          |
185         | status task |-----+   |      | filter 1 |
186         |_____________|         |      |___   ____|
187                                 |          \ /
188                                 |           |            .____________________.
189                                 |           |            |       ______       |
190         .____________.          |      .___/ \____.      |    .d########b.    |
191         |            |          |      |          |      |  .d############b   |
192         | dispatcher |----------'      | filter 2 |      | .d######""####//b. |
193         |_____   ____|                 |___   ____|      | 9######(  )######P |
194               \ /                          \ /           | 'b######++######d' |
195                |                            |            |  "9############P"  |
196                |                            |            |   "9a########P"    |
197         ._____/ \_____.                .___/ \____.      |      `""""''       |
198         |             |                |          |      |  ________________  |
199         | para_audioc |                |  writer  |------| |________________| |
200         |_____________|                |__________|      |____________________|
201
202
203 The status task of para_audiod connects to para_server and runs the
204 "stat" command to retrieve the current server status. If an audio
205 stream is available, para_audiod starts a so-called buffer tree to
206 play the stream.
207
208 The buffer tree consists of a receiver, any number of filters and a
209 writer. The receiver downloads the audio stream from para_server and
210 the filters decode or modify the received data. The writer plays the
211 decoded stream.
212
213 The dispatcher of para_audiod listens on a local socket and runs
214 audiod commands on behalf of para_audioc. For example, para_gui runs
215 para_audioc to obtain status information about para_audiod and the
216 current audio file. Access to the local socket may be restricted by
217 means of Unix socket credentials.
218
219 <h3> para_audioc </h3>
220
221 The client program which talks to para_audiod. Used to control
222 para_audiod, to receive status info, or to grab the stream at any
223 point of the decoding process. Like para_client, para_audioc supports
224 interactive sessions on systems with libreadline.
225
226 <h3> para_recv </h3>
227
228 A command line HTTP/DCCP/UDP stream grabber. The http mode is
229 compatible with arbitrary HTTP streaming sources (e.g. icecast).
230 In addition to the three network streaming modes, para_recv can also
231 operate in local (afh) mode. In this mode it writes the content of
232 an audio file on the local file system in complete chunks to stdout,
233 optionally 'just in time'. This allows cutting audio files without
234 decoding, and it enables third-party software which is unaware of
235 the particular audio format to send complete frames in real time.
236
237 <h3> para_filter </h3>
238
239 A filter program that reads from STDIN and writes to STDOUT.
240 Like para_recv, this is an atomic building block which can be used to
241 assemble higher-level audio receiving facilities. It combines several
242 different functionalities in one tool: decoders for multiple audio
243 formats and a number of processing filters, among these a normalizer
244 for audio volume.
245
246 <h3> para_afh </h3>
247
248 A small stand-alone program that prints tech info about the given
249 audio file to STDOUT. It can be instructed to print a "chunk table",
250 an array of offsets within the audio file.
251
252 <h3> para_write </h3>
253
254 A modular audio stream writer. It supports a simple file writer
255 output plug-in and optional WAV/raw players for ALSA (Linux) and OSS.
256 para_write can also be used as a stand-alone WAV or raw audio player.
257
258 <h3> para_play </h3>
259
260 A command line audio player which supports the same audio formats as
261 para_server. It differs from other players in that it has an insert
262 and a command mode, like the vi editor. Line editing is based on
263 libreadline, and tab completion and command history are supported.
264
265 <h3> para_gui </h3>
266
267 Curses-based gui that presents status information obtained in a curses
268 window. Appearance can be customized via themes. para_gui provides
269 key-bindings for the most common server commands and new key-bindings
270 can be added easily.
271
272 <h3> para_mixer </h3>
273
274 An alarm clock and volume-fader for OSS and ALSA.
275
276 ===========
277 Quick start
278 ===========
279
280 This chapter lists the [necessary software](#Requirements)
281 that must be installed to compile the paraslash package, describes
282 how to [compile and install](#Installation) the paraslash
283 source code and the steps that have to be performed in order to
284 [set up](#Configuration) a typical server and client.
285
286 Requirements
287 ------------
288 <h3> For the impatient </h3>
289
290         git clone git://git.tuebingen.mpg.de/lopsub
291         cd lopsub && make && sudo make install
292         git clone git://git.tuebingen.mpg.de/osl
293         cd osl && make && sudo make install && sudo ldconfig
294         sudo apt-get install autoconf libssl-dev m4 \
295               libmad0-dev libid3tag0-dev libasound2-dev libvorbis-dev \
296               libfaad-dev libspeex-dev libflac-dev libsamplerate-dev \
297               libasound2-dev libao-dev libreadline-dev libncurses-dev \
298               libopus-dev
299
300 <h3> Detailed description </h3>
301
302 In any case you will need
303
304 - [lopsub](http://people.tuebingen.mpg.de/maan/lopsub/). The long
305 option parser for subcommands generates the command line and config
306 file parsers for all paraslash executables. Clone the source code
307 repository with
308
309                 git clone git://git.tuebingen.mpg.de/lopsub
310
311 - [gcc](ftp://ftp.gnu.org/pub/gnu/gcc) or
312 [clang](http://clang.llvm.org). All gcc versions >= 5.4 are currently
313 supported. Moderately recent versions of clang should work as well.
314
315 - [gnu make](ftp://ftp.gnu.org/pub/gnu/make) is also shipped with the
316 disto. On BSD systems the gnu make executable is often called gmake.
317
318 - [bash](ftp://ftp.gnu.org/pub/gnu/bash). Some scripts which run
319 during compilation require the _Bourne again shell_.  It is most
320 likely already installed.
321
322 - [m4](ftp://ftp.gnu.org/pub/gnu/m4/). Some source files are generated
323 from templates by the m4 macro processor.
324
325 Optional:
326
327 - [libosl](http://people.tuebingen.mpg.de/maan/osl/). The _object
328 storage layer_ library is used by para_server. To clone the source
329 code repository, execute
330
331                 git clone git://git.tuebingen.mpg.de/osl
332
333 - [openssl](https://www.openssl.org/) or
334 [libgcrypt](ftp://ftp.gnupg.org/gcrypt/libgcrypt/).  At least one
335 of these two libraries is needed as the backend for cryptographic
336 routines on both the server and the client side. Both openssl and
337 libgcrypt are usually shipped with the distro, but you might have
338 to install the development package (`libssl-dev` or `libgcrypt-dev`
339 on debian systems) as well.
340
341 - [flex](https://github.com/westes/flex) and
342 [bison](https://www.gnu.org/software/bison) are needed to build the
343 mood parser of para_server. The build system will skip para_server
344 if these tools are not installed.
345
346 - [libmad](http://www.underbit.com/products/mad/). To compile in MP3
347 support for paraslash, the development package must be installed. It
348 is called `libmad0-dev` on debian-based systems. Note that libmad is
349 not necessary on the server side, i.e., for sending MP3 files.
350
351 - [libid3tag](http://www.underbit.com/products/mad/). For version-2
352 ID3 tag support, you will need the libid3tag development package
353 `libid3tag0-dev`. Without libid3tag, only version-1 tags are
354 recognized. The mp3 tagger also needs this library for modifying
355 (id3v1 and id3v2) tags.
356
357 - [ogg vorbis](https://www.xiph.org/downloads/). For ogg vorbis streams
358 you need libogg, libvorbis, libvorbisfile. The corresponding Debian
359 packages are called `libogg-dev` and `libvorbis-dev`.
360
361 - [libfaad and mp4ff](https://sourceforge.net/projects/faac/). For aac files
362 (m4a) you need libfaad and libmp4ff (package: `libfaad-dev`). Note
363 that for some distributions, e.g. Ubuntu, mp4ff is not part of the
364 libfaad package. Install the faad library from sources (available
365 through the above link) to get the mp4ff library and header files.
366
367 - [speex](https://www.speex.org/). In order to stream or decode speex
368 files, libspeex (`libspeex-dev`) is required.
369
370 - [flac](https://xiph.org/flac/). To stream or decode files
371 encoded with the _Free Lossless Audio Codec_, libFLAC (`libFLAC-dev`)
372 must be installed.
373
374 - [libsamplerate](http://www.mega-nerd.com/SRC/index.html). The
375 resample filter will only be compiled if this library is
376 installed. Debian package: `libsamplerate-dev`.
377
378 - [alsa-lib](ftp://ftp.alsa-project.org/pub/lib/). On Linux, you will
379 need to have the ALSA development package `libasound2-dev` installed.
380
381 - [libao](https://ftp.osuosl.org/pub/xiph/releases/ao/). Needed to build
382 the ao writer (ESD, PulseAudio,...).  Debian package: `libao-dev`.
383
384 - [curses](ftp://ftp.gnu.org/pub/gnu/ncurses). Needed for
385 para_gui. Debian package: `libncurses-dev`.
386
387 - [GNU
388 Readline](http://cnswww.cns.cwru.edu/php/chet/readline/rltop.html). Only if
389 this library (`libreadline-dev`) is installed, para_play is built, Without it,
390 para_client(1) and para_audioc(1) still work, but lack support for interactive
391 sessions.
392
393 Installation
394 ------------
395 To build the sources from a tarball, execute
396
397         ./configure && make
398
399 To build from git or a gitweb snapshot, run this command instead:
400
401         ./autogen.sh
402
403 There should be no errors but probably some warnings about missing
404 packages which usually implies that not all audio formats will be
405 supported. If headers or libs are installed at unusual locations you
406 might need to tell the configure script where to find them. Try
407
408         ./configure --help
409
410 to see a list of options. If the paraslash package was compiled
411 successfully, execute (optionally)
412
413         make test
414
415 to run the paraslash test suite. If all tests pass, execute as root
416
417         make install
418
419 to install executables under /usr/local/bin and the man pages under
420 /usr/local/man.
421
422 Configuration
423 -------------
424
425 <h3> Create a paraslash user </h3>
426
427 In order to control para_server at runtime you must create a paraslash
428 user. As authentication is based on the RSA crypto system you'll have
429 to create an RSA key pair. If you already have a user and an RSA key
430 pair, you may skip this step.
431
432 In this section we'll assume a typical setup: You would like to run
433 para_server on some host called server_host as user foo, and you want
434 to connect to para_server from another machine called client_host as
435 user bar.
436
437 As foo@server_host, create ~/.paraslash/server.users by typing the
438 following commands:
439
440         user=bar
441         target=~/.paraslash/server.users
442         key=~/.paraslash/id_rsa.pub.$user
443         perms=AFS_READ,AFS_WRITE,VSS_READ,VSS_WRITE
444         mkdir -p ~/.paraslash
445         echo "user $user $key $perms" >> $target
446
447 Next, change to the "bar" account on client_host and generate the
448 key pair with the commands
449
450         ssh-keygen -q -t rsa -b 2048 -N '' -m RFC4716
451
452 This generates the two files id_rsa and id_rsa.pub in ~/.ssh.  Note
453 that para_server won't accept keys shorter than 2048 bits. Moreover,
454 para_client rejects private keys which are world-readable.
455
456 para_server only needs to know the public key of the key pair just
457 created. Copy this public key to server_host:
458
459         src=~/.ssh/id_rsa.pub
460         dest=.paraslash/id_rsa.pub.$LOGNAME
461         scp $src foo@server_host:$dest
462
463 Finally, tell para_client to connect to server_host:
464
465         conf=~/.paraslash/client.conf
466         echo 'hostname server_host' > $conf
467
468
469 <h3> Start para_server </h3>
470
471 For this first try, we'll use the info loglevel to make the output
472 of para_server more verbose.
473
474         para_server -l info
475
476 Now you can use para_client to connect to the server and issue
477 commands. Open a new shell as bar@client_host and try
478
479         para_client help
480         para_client si
481
482 to retrieve the list of available commands and some server info.
483 Don't proceed if this doesn't work.
484
485 <h3> Create and populate the database </h3>
486
487 An empty database is created with
488
489         para_client init
490
491 This initializes a couple of empty tables under
492 ~/.paraslash/afs_database-0.7. You normally don't need to look at these
493 tables, but it's good to know that you can start from scratch with
494
495         rm -rf ~/.paraslash/afs_database-0.7
496
497 in case something went wrong.
498
499 Next, you need to add some audio files to that database so that
500 para_server knows about them. Choose an absolute path to a directory
501 containing some audio files and add them to the audio file table:
502
503         para_client add /my/mp3/dir
504
505 This might take a while, so it is a good idea to start with a directory
506 containing not too many files. Note that the table only contains data
507 about the audio files found, not the files themselves.
508
509 You may print the list of all known audio files with
510
511         para_client ls
512
513 <h3> Configure para_audiod </h3>
514
515 We will have to tell para_audiod that it should receive the audio
516 stream from server_host via http:
517
518         para_audiod -l info -r '.:http -i server_host'
519
520 You should now be able to listen to the audio stream once para_server
521 starts streaming. To activate streaming, execute
522
523         para_client play
524
525 Since no playlist has been specified yet, the "dummy" mode which
526 selects all known audio files is activated automatically. See the
527 section on the [audio file selector](#The.audio.file.selector) for how
528 to use playlists and moods to specify which files should be streamed
529 in which order.
530
531 Troubleshooting
532 ---------------
533
534 To identify streaming problems try to receive, decode and play the
535 stream manually using para_recv, para_filter and para_write as follows.
536 For simplicity we assume that you're running Linux/ALSA and that only
537 MP3 files have been added to the database.
538
539         para_recv -r 'http -i server_host' > file.mp3
540         # (interrupt with CTRL+C after a few seconds)
541         ls -l file.mp3 # should not be empty
542         para_filter -f mp3dec -f wav < file.mp3 > file.wav
543         ls -l file.wav # should be much bigger than file.mp3
544         para_write -w alsa < file.wav
545
546 Double check what is logged by para_server and use the --loglevel
547 option of para_recv, para_filter and para_write to increase verbosity.
548
549 ===============
550 User management
551 ===============
552
553 para_server uses a challenge-response mechanism to authenticate
554 requests from incoming connections, similar to ssh's public key
555 authentication method. Authenticated connections are encrypted using
556 the AES stream cipher in integer counter mode.
557
558 In this chapter we briefly describe RSA and AES, and sketch the
559 [authentication handshake](#Client-server.authentication)
560 between para_client and para_server. User management is discussed
561 in the section on [the user_list file](#The.user_list.file).
562 These sections are all about communication between the client and the
563 server. Connecting para_audiod is a different matter and is described
564 in a [separate section](#Connecting.para_audiod).
565
566 RSA and AES
567 -----------
568
569 A block cipher is a transformation which operates on fixed-length
570 blocks. For symmetric block ciphers the transformation is determined
571 by a single key for both encryption and decryption. For asymmetric
572 block ciphers, on the other hand, the key consists of two parts,
573 called the public key and the private key. A message can be encrypted
574 with either key and only the counterpart of that key can decrypt the
575 message. Asymmetric block ciphers can be used for both signing and
576 encrypting a message.
577
578 RSA is an asymmetric block cipher which is used in many applications,
579 including ssh and gpg. The RSA public key encryption and signatures
580 algorithms are defined in detail in RFC 2437. Paraslash relies on
581 RSA for authentication.
582
583 Stream ciphers XOR the input with a pseudo-random key stream to produce
584 the output. Decryption uses the same function calls as encryption.
585 Any block cipher can be turned into a stream cipher by generating the
586 pseudo-random key stream by encrypting successive values of a counter
587 (counter mode).
588
589 AES, the advanced encryption standard, is a well-known symmetric block
590 cipher. Paraslash employs AES in counter mode as described above to
591 encrypt communications. Since a stream cipher key must not be used
592 twice, a random key is generated for every new connection.
593
594 Client-server authentication
595 ----------------------------
596
597 The authentication handshake between para_client and para_server goes
598 as follows:
599
600 - para_client connects to para_server and sends an authentication
601 request for a user. It does so by connecting to TCP port 2990 of the
602 server host. This port is called the para_server _control port_.
603
604 - para_server accepts the connection and forks a child process which
605 handles the incoming request. The parent process keeps listening on the
606 control port while the child process (also called para_server below)
607 continues as follows.
608
609 - para_server loads the RSA public key of that user, fills a
610 fixed-length buffer with random bytes, encrypts that buffer using the
611 public key and sends the encrypted buffer to the client. The first
612 part of the buffer is the challenge which is used for authentication
613 while the second part is the session key.
614
615 - para_client receives the encrypted buffer and decrypts it with the
616 user's private key, thereby obtaining the challenge buffer and the
617 session key. It hashes the challenge buffer with a crytographic hash
618 function, sends the hash value back to para_server and stores the
619 session key for further use.
620
621 - para_server also computes the hash value of the challenge and compares
622 it against what was sent back by the client.
623
624 - If the two hashes do not match, the authentication has failed and
625 para_server closes the connection.
626
627 - Otherwise the user is considered authenticated and the client is
628 allowed to proceed by sending a command to be executed. From this
629 point on the communication is encrypted using the stream cipher with
630 the session key known to both peers.
631
632 paraslash relies on the quality of the pseudo-random bytes provided
633 by the crypto library (openssl or libgcrypt), on the security of
634 the implementation of the RSA and AES crypto routines and on the
635 infeasibility to invert the hash function.
636
637 Neither para_server or para_client create RSA keys on their
638 own. This has to be done once for each user as sketched in
639 [Quick start](#Quick.start) and discussed in more detail
640 [below](#The.user_list.file).
641
642 The user_list file
643 ------------------
644
645 At startup para_server reads the user list file which contains one
646 line per user. The default location of the user list file may be
647 changed with the --user-list option.
648
649 There should be at least one user in this file. Each user must have
650 an RSA key pair. The public part of the key is needed by para_server
651 while the private key is needed by para_client. Each line of the
652 user list file must be of the form
653
654         user <username> <key> <perms>
655
656 where _username_ is an arbitrary string (usually the user's login
657 name), _key_ is the full path to that user's public RSA key, and
658 _perms_ is a comma-separated list of zero or more of the following
659 permission bits:
660
661         +---------------------------------------------------------+
662         | AFS_READ  | read the contents of the databases          |
663         +-----------+---------------------------------------------+
664         | AFS_WRITE | change database contents                    |
665         +-----------+---------------------------------------------+
666         | VSS_READ  | obtain information about the current stream |
667         +-----------+---------------------------------------------+
668         | VSS_WRITE | change the current stream                   |
669         +---------------------------------------------------------+
670
671 The permission bits specify which commands the user is allowed to
672 execute. The output of
673
674         para_client help
675
676 contains the permissions needed to execute the command.
677
678 It is possible to make para_server reread the user_list file by
679 executing the paraslash "hup" command or by sending SIGHUP to the
680 PID of para_server.
681
682 Connecting para_audiod
683 ----------------------
684
685 para_audiod listens on a Unix domain socket. Those sockets are
686 for local communication only, so only local users can connect to
687 para_audiod. The default is to let any user connect but this can be
688 restricted on platforms that support UNIX socket credentials which
689 allow para_audiod to obtain the Unix credentials of the connecting
690 process.
691
692 Use para_audiod's --user-allow option to allow connections only for
693 a limited set of users.
694
695 =======================
696 The audio file selector
697 =======================
698
699 paraslash comes with a sophisticated audio file selector (AFS),
700 whose main task is to determine which file to stream next, based on
701 information on the audio files stored in a database. It communicates
702 also with para_client via the command handler whenever an AFS command
703 is executed, for example to answer a database query.
704
705 Besides the simple playlists, AFS supports audio file selection
706 based on _moods_ which act as a filter that limits the set of all
707 known audio files to those which satisfy certain criteria. It also
708 maintains tables containing images (e.g. album cover art) and lyrics
709 that can be associated with one or more audio files.
710
711 In this chapter we sketch the setup of the [AFS
712 process](#The.AFS.process) during server startup and proceed with the
713 description of the [layout](#Database.layout) of the various database
714 tables. The section on [playlists and moods](#Playlists.and.moods)
715 explains these two audio file selection mechanisms in detail
716 and contains practical examples. The way [file renames and content
717 changes](#File.renames.and.content.changes) are detected is discussed
718 briefly before the [Troubleshooting](#Troubleshooting) section
719 concludes the chapter.
720
721 The AFS process
722 ---------------
723
724 On startup, para_server forks to create the AFS process which opens
725 the database tables. The AFS process accepts incoming connections
726 which arrive either on a pipe which is shared with para_server,
727 or on the local socket it is listening on. The setup is as follows.
728
729                   .___________________.  .______________.
730                   |                   |  |              |
731                   | virtual streaming |  | audio format |
732                   |      system       |  |   handler    |
733                   |_________   _______|  |_____   ______|
734                             \ /                \ /
735                              |                  |
736           .-'""""`-.         |                  |          .-'""""`-.
737          (          )        |                  |         (          )
738          |`-.____.-'|    .__/ \________________/ \___.    |`-.____.-'|
739          |          |    |                           |    |          |
740          |   file   |----| AFS (audio file selector) |----|    OSL   |
741          |  system  |    |         process           |    | database |
742          |          |    |___________________________|    |          |
743          |. ' "" ` .|                 |                   |. ' "" ` .|
744          |          |                 |                   |          |
745           `-.____.-'                  |                    `-.____.-'
746                              ._______/ \_______.
747                              |                 |
748                              | command handler |
749                              |_______   _______|
750                                      \ /
751                                       |
752                                       |
753                                       |
754                                ._____/ \_____.
755                                |             |
756                                | para_client |
757                                |_____________|
758
759 The virtual streaming system, which is part of the server process,
760 communicates with the AFS process via pipes and shared memory. When
761 the current audio file changes, it sends a notification through the
762 shared pipe. The AFS process queries the database to determine the
763 next audio file, opens it, verifies that it has not been changed since
764 it was added to the database and passes the open file descriptor back
765 to the virtual streaming system, along with audio file meta-data such
766 as file name, duration, audio format and so on. The virtual streaming
767 system then starts to stream the file.
768
769 The command handlers of all AFS server commands use the local socket
770 to query or update the database. For example, the command handler of
771 the add command sends the path of an audio file to the local socket.
772 The AFS process opens the file and tries to find an audio format
773 handler which recognizes the file. If all goes well, a new database
774 entry with metadata obtained from the audio format handler is added
775 to the database.
776
777 Note that AFS employs
778 [libosl](http://people.tuebingen.mpg.de/maan/osl/), the object
779 storage layer library, as the database backend. This library offers
780 functionality similar to a relational database, but is much more
781 lightweight than a full featured database management system.
782
783 Database layout
784 ---------------
785
786 Metadata about the known audio files is stored in an OSL database. This
787 database consists of the following tables:
788
789 - The audio file table contains path, hash and metadata of each
790 known file.
791
792 - The "attributes" table maps each of the 64 possible attributes to a
793 string.
794
795 - The "blob" tables store images, lyrics, moods, playlists. All of
796 these are optional.
797
798 - The "score" table describes the subset of admissible files for the
799 current playlist or mood.
800
801 All tables are described in more detail below.
802
803 <h3> The audio file table </h3>
804
805 This is the most important and usually also the largest table of the
806 AFS database. It contains the information needed to stream each audio
807 file. In particular the following data is stored for each audio file.
808
809 - The cryptographic hash value of the audio file contents. This is
810 computed once when the file is added to the database. Whenever AFS
811 selects this audio file for streaming the hash value is recomputed
812 and checked against the value stored in the database to detect
813 content changes.
814
815 - The time when this audio file was last played.
816
817 - The number of times the file has been played so far.
818
819 - The attribute bitmask.
820
821 - The image id which describes the image associated with this audio
822 file.
823
824 - The lyrics id which describes the lyrics associated with this
825 audio file.
826
827 - The audio format id (MP3, OGG, ...).
828
829 - An amplification value that can be used by the amplification filter
830 to pre-amplify the decoded audio stream.
831
832 - The chunk table. It describes the location and the timing of the
833 building blocks of the audio file. This is used by para_server to
834 send chunks of the file at appropriate times.
835
836 - The duration of the audio file.
837
838 - Tag information contained in the audio file (ID3 tags, Vorbis
839 comments, ...).
840
841 - The number of channels
842
843 - The encoding bitrate.
844
845 - The sampling frequency.
846
847 To add or refresh the data contained in the audio file table, the _add_
848 command is used. It takes the full path of either an audio file or a
849 directory. In the latter case, the directory is traversed recursively
850 and all files which are recognized as valid audio files are added to
851 the database.
852
853 <h3> The attribute table </h3>
854
855 The attribute table contains two columns, _name_ and _bitnum_. An
856 attribute is simply a name for a certain bit number in the attribute
857 bitmask of the audio file table.
858
859 Each of the 64 bits of the attribute bitmask can be set for each
860 audio file individually. Hence up to 64  different attributes may be
861 defined. For example, "pop", "rock", "blues", "jazz", "instrumental",
862 "german_lyrics", "speech", whatever. You are free to choose as
863 many attributes as you like and there are no naming restrictions
864 for attributes.
865
866 A new attribute "test" is created by
867
868         para_client addatt test
869 and
870         para_client lsatt
871
872 lists all available attributes. You can set the "test" attribute for
873 an audio file by executing
874
875         para_client setatt test+ /path/to/the/audio/file
876
877 Similarly, the "test" bit can be removed from an audio file with
878
879         para_client setatt test- /path/to/the/audio/file
880
881 Instead of a path you may use a shell wildcard pattern. The attribute
882 is applied to all audio files matching this pattern:
883
884         para_client setatt test+ '/test/directory/*'
885
886 The command
887
888         para_client -- ls -l=v
889
890 gives you a verbose listing of your audio files also showing which
891 attributes are set.
892
893 In case you wonder why the double-dash in the above command is needed:
894 It tells para_client to not interpret the options after the dashes. If
895 you find this annoying, just say
896
897         alias para='para_client --'
898
899 and be happy. In what follows we shall use this alias.
900
901 The "test" attribute can be dropped from the database with
902
903         para rmatt test
904
905 Read the output of
906
907         para help ls
908         para help setatt
909
910 for more information and a complete list of command line options to
911 these commands.
912
913 <h3> Blob tables </h3>
914
915 The image, lyrics, moods and playlists tables are all blob tables.
916 Blob tables consist of three columns each: The identifier which is
917 a positive number that is auto-incremented, the name (an arbitrary
918 string) and the content (the blob).
919
920 All blob tables support the same set of actions: cat, ls, mv, rm
921 and add. Of course, _add_ is used for adding new blobs to the table
922 while the other actions have the same meaning as the corresponding
923 Unix commands. The paraslash commands to perform these actions are
924 constructed as the concatenation of the table name and the action. For
925 example addimg, catimg, lsimg, mvimg, rmimg are the commands that
926 manipulate or query the image table.
927
928 The add variant of these commands is special as these commands read
929 the blob contents from stdin. To add an image to the image table the
930 command
931
932         para addimg image_name < file.jpg
933
934 can be used.
935
936 Note that the images and lyrics are not interpreted at all, and also
937 the playlist and the mood blobs are only investigated when the mood
938 or playlist is activated with the select command.
939
940 <h3> The score table </h3>
941
942 The score table describes those audio files which are admissible for
943 the current mood or playlist (see below). The table has two columns:
944 a pointer to a row of the audio file table and a score value.
945
946 Unlike all other tables of the database, the score table remains in
947 memory and is never stored on disk. It is initialized at startup and
948 recomputed when the select command loads a new mood or playlist.
949
950 When the audio file selector is asked to open the next audio file,
951 it picks the row with the highest score, opens the corresponding
952 file and passes the file descriptor to the virtual streaming system.
953 At this point the last_played and the num_played fields of the selected
954 file are updated and the score is recomputed.
955
956 Playlists and moods
957 -------------------
958
959 Playlists and moods offer two different ways of specifying the set of
960 admissible files. A playlist in itself describes a set of admissible
961 files. A mood, in contrast, describes the set of admissible files in
962 terms of attributes and other type of information available in the
963 audio file table. As an example, a mood can define a filename pattern,
964 which is then matched against the names of audio files in the table.
965
966 <h3> Playlists </h3>
967
968 Playlists are accommodated in the playlist table of the afs database,
969 using the aforementioned blob format for tables. A new playlist is
970 created with the addpl command by specifying the full (absolute)
971 paths of all desired audio files, separated by newlines. Example:
972
973         find /my/mp3/dir -name "*.mp3" | para addpl my_playlist
974
975 If _my_playlist_ already exists it is overwritten. To activate the
976 new playlist, execute
977
978         para select p/my_playlist
979
980 The audio file selector will assign scores to each entry of the list,
981 in descending order so that files will be selected in order. If a
982 file could not be opened for streaming, its entry is removed from
983 the score table (but not from the playlist).
984
985 <h3> Moods </h3>
986
987 A mood consists of a unique name and a definition. The definition
988 is an expression which describes which audio files are considered
989 admissible. At any time at most one mood can be active, meaning
990 that para_server will only stream files which are admissible for the
991 active mood.
992
993 The expression may refer to attributes and other metadata stored in
994 the database. Expressions may be combined by means of logical and
995 arithmetical operators in a natural way. Moreover, string matching
996 based on regular expression or wildcard patterns is supported.
997
998 The set of admissible files is determined by applying the expression
999 to each audio file in turn. For a mood definition to be valid, its
1000 expression must evaluate to a number, a string or a boolean value
1001 ("true" or "false"). For numbers, any value other than zero means the
1002 file is admissible. For strings, any non-empty string indicates an
1003 admissible file. For boolean values, true means admissible and false
1004 means not admissible.  As a special case, the empty expression treats
1005 all files as admissible.
1006
1007 <h3> Mood grammar </h3>
1008
1009 Expressions are based on a context-free grammar which distinguishes
1010 between several types for syntactic units or groupings. The grammar
1011 defines a set of keywords which have a type and a corresponding
1012 semantic value, as shown in the following table.
1013
1014 Keyword              |    Type | Semantic value
1015 :--------------------|--------:|:----------------------------------
1016 `path`               |  string | Full path of the current audio file
1017 `artist`             |  string | Content of the artist meta tag
1018 `title`              |  string | Content of the title meta tag
1019 `album`              |  string | Content of the album meta tag
1020 `comment`            |  string | Content of the somment meta tag
1021 `num_attributes_set` | integer | Number of attributes which are set
1022 `year`               | integer | Content of the year meta tag [\*]
1023 `num_played`         | integer | How many times the file has been streamed
1024 `image_id`           | integer | The identifier of the (cover art) image
1025 `lyrics_id`          | integer | The identifier of the lyrics blob
1026 `bitrate`            | integer | The average bitrate
1027 `frequency`          | integer | The output sample rate
1028 `channels`           | integer | The number of channels
1029 `duration`           | integer | The number of milliseconds
1030 `is_set("foo")`      | boolean | True if attribute "foo" is set.
1031
1032 [\*] For most audio formats, the year tag is stored as a string. It
1033 is converted to an integer by the mood parser. If the audio file
1034 has no year tag or the content of the year tag is not a number, the
1035 semantic value is zero. A special convention applies if the year tag
1036 is a one-digit or a two-digit number. In this case 1900 is added to
1037 the tag value.
1038
1039 Expressions may be grouped using parentheses, logical and
1040 arithmetical operators or string matching operators. The following
1041 table lists the available operators.
1042
1043 Token  | Meaning
1044 :------|:-------
1045 `\|\|` | Logical Or
1046 `&&`   | Logical And
1047 `!`    | Logical Not
1048 `==`   | Equal (can be applied to all types)
1049 `!=`   | Not equal. Likewise
1050 `<`    | Less than
1051 `<=`   | Less or equal
1052 `>=`   | Greater or equal
1053 `+`    | Arithmetical minus
1054 `-`    | Binary/unary minus
1055 `*`    | Multiplication
1056 `/`    | Division
1057 `=~`   | Regular expression match
1058 `=\|`  | Filename match
1059
1060 Besides integers, strings and booleans there is an additional type
1061 which describes regular expression or wildcard patterns. Patterns
1062 are not just strings because they also include a list of flags which
1063 modify matching behaviour.
1064
1065 Regular expression patterns are of the form `/pattern/[flags]`. That
1066 is, the pattern is delimited by slashes, and is followed by zero or
1067 more characters, each specifying a flag according to the following
1068 table
1069
1070 Flag |    POSIX name | Meaning
1071 :----|--------------:|--------
1072 `i`  |   `REG_ICASE` | Ignore case in match
1073 `n`  | `REG_NEWLINE` | Treat newline as an ordinary character
1074
1075 Note that only extended regular expression patterns are supported. See
1076 regex(3) for details.
1077
1078 Wildcard patterns are similar, but the pattern must be delimited by
1079 `'|'` characters rather than slashes. For wildcard patterns different
1080 flags exist, as shown below.
1081
1082 Flag |             POSIX name | Meaning
1083 :----|-----------------------:|--------
1084 `n`  | `FNM_NOESCAPE`         | Treat backslash as an ordinary character
1085 `p`  | `FNM_PATHNAME`         | Match a slash only with a slash in pattern
1086 `P`  | `FNM_PERIOD`           | Leading period has to be matched exactly
1087 `l`  | `FNM_LEADING_DIR` [\*] | Ignore "/\*" rest after successful matching
1088 `i`  | `FNM_CASEFOLD` [\*]    | Ignore case in match
1089 `e`  | `FNM_EXTMATCH` [\*\*]  | Enable extended pattern matching
1090
1091 [\*] Not in POSIX, but both FreeBSD and NetBSD have it.
1092
1093 [\*\*] GNU extension, silently ignored on non GNU systems.
1094
1095 See fnmatch(3) for details.
1096
1097 Mood definitions may contain arbitrary whitespace and comments.
1098 A comment is a word beginning with #. This word and all remaining
1099 characters of the line are ignored.
1100
1101 <h3> Example moods </h3>
1102
1103 * Files with no/invalid year tag: `year == 0`
1104
1105 * Only oldies: `year != 0 && year < 1980`
1106
1107 * Only 80's Rock or Metal: `(year >= 1980 && year < 1990) &&
1108   (is_set("rock") || is_set("metal"))`
1109
1110 * Files with incomplete tags: `artist == "" || title == "" || album =
1111 "" || comment == "" || year == 0`
1112
1113 * Files with no attributes defined so far: `num_attributes_set == 0`
1114
1115 * Only newly added files: `num_played == 0`
1116
1117 * Only poor quality files: `bitrate < 96`
1118
1119 * Cope with different spellings of Motörhead: `artist =~ /mot(ö|oe{0,1})rhead/i`
1120
1121 * The same with extended wildcard patterns: `artist =| |mot+(o\|oe\|ö)rhead|ie`
1122
1123 <h3> Mood usage </h3>
1124
1125 To create a new mood called "my_mood", write its definition into
1126 some temporary file, say "tmpfile", and add it to the mood table
1127 by executing
1128
1129         para addmood my_mood < tmpfile
1130
1131 If the mood definition is really short, you may just pipe it to the
1132 client instead of using temporary files. Like this:
1133
1134         echo "$MOOD_DEFINITION" | para addmood my_mood
1135
1136 There is no need to keep the temporary file since you can always use
1137 the catmood command to get it back:
1138
1139         para catmood my_mood
1140
1141 A mood can be activated by executing
1142
1143         para select m/my_mood
1144
1145 Once active, the list of admissible files is shown by the ls command
1146 if the "-a" switch is given:
1147
1148         para ls -a
1149
1150 File renames and content changes
1151 --------------------------------
1152
1153 Since the audio file selector knows the hash of each audio file that
1154 has been added to the afs database, it recognizes if the content of
1155 a file has changed, e.g. because an ID3 tag was added or modified.
1156 Also, if a file has been renamed or moved to a different location,
1157 afs will detect that an entry with the same hash value already exists
1158 in the audio file table.
1159
1160 In both cases it is enough to just re-add the new file. In the
1161 first case (file content changed), the audio table is updated, while
1162 metadata such as the num_played and last_played fields, as well as
1163 the attributes, remain unchanged. In the other case, when the file
1164 is moved or renamed, only the path information is updated, all other
1165 data remains as before.
1166
1167 It is possible to change the behaviour of the add command by using the
1168 "-l" (lazy add) or the "-f" (force add) option.
1169
1170 Troubleshooting
1171 ---------------
1172
1173 Use the debug loglevel (-l debug) to show debugging info. All paraslash
1174 executables have a brief online help which is displayed when -h is
1175 given. The --detailed-help option prints the full help text.
1176
1177 If para_server crashed or was killed by SIGKILL (signal 9), it
1178 may refuse to start again because of "dirty osl tables". In this
1179 case you'll have to run the oslfsck program of libosl to fix your
1180 database:
1181
1182         oslfsck -fd ~/.paraslash/afs_database-0.7
1183
1184 However, make sure para_server isn't running before executing oslfsck.
1185
1186 If you don't mind to recreate your database you can start
1187 from scratch by removing the entire database directory, i.e.
1188
1189         rm -rf ~/.paraslash/afs_database-0.7
1190
1191 Be aware that this removes all attribute definitions, all playlists
1192 and all mood definitions and requires to re-initialize the tables.
1193
1194 Although oslfsck fixes inconsistencies in database tables it doesn't
1195 care about the table contents. To check for invalid table contents, use
1196
1197         para_client check
1198
1199 This prints out references to missing audio files as well as invalid
1200 playlists and mood definitions.
1201
1202 Similarly, para_audiod refuses to start if its socket file exists, since
1203 this indicates that another instance of para_audiod is running. After
1204 a crash a stale socket file might remain and you must run
1205
1206         para_audiod --force
1207
1208 once to fix it up.
1209
1210 =======================================
1211 Audio formats and audio format handlers
1212 =======================================
1213
1214 Audio formats
1215 -------------
1216
1217 The following audio formats are supported by paraslash:
1218
1219 <h3> MP3 </h3>
1220
1221 Mp3, MPEG-1 Audio Layer 3, is a common audio format for audio storage,
1222 designed as part of its MPEG-1 standard.  An MP3 file is made up of
1223 multiple MP3 frames, which consist of a header and a data block. The
1224 size of an MP3 frame depends on the bit rate and on the number
1225 of channels. For a typical CD-audio file (sample rate of 44.1 kHz
1226 stereo), encoded with a bit rate of 128 kbit, an MP3 frame is about
1227 400 bytes large.
1228
1229 <h3> OGG/Vorbis </h3>
1230
1231 OGG is a standardized audio container format, while Vorbis is an
1232 open source codec for lossy audio compression. Since Vorbis is most
1233 commonly made available via the OGG container format, it is often
1234 referred to as OGG/Vorbis. The OGG container format divides data into
1235 chunks called OGG pages. A typical OGG page is about 4KB large. The
1236 Vorbis codec creates variable-bitrate (VBR) data, where the bitrate
1237 may vary considerably.
1238
1239 <h3> OGG/Speex </h3>
1240
1241 Speex is an open-source speech codec that is based on CELP (Code
1242 Excited Linear Prediction) coding. It is designed for voice
1243 over IP applications, has modest complexity and a small memory
1244 footprint. Wideband and narrowband (telephone quality) speech are
1245 supported. As for Vorbis audio, Speex bit-streams are often stored
1246 in OGG files. As of 2012 this codec is considered obsolete since the
1247 Oppus codec, described below, surpasses its performance in all areas.
1248
1249 <h3> OGG/Opus </h3>
1250
1251 Opus is a lossy audio compression format standardized through RFC
1252 6716 in 2012. It combines the speech-oriented SILK codec and the
1253 low-latency CELT (Constrained Energy Lapped Transform) codec. Like
1254 OGG/Vorbis and OGG/Speex, Opus data is usually encapsulated in OGG
1255 containers. All known software patents which cover Opus are licensed
1256 under royalty-free terms.
1257
1258 <h3> AAC </h3>
1259
1260 Advanced Audio Coding (AAC) is a standardized, lossy compression
1261 and encoding scheme for digital audio which is the default audio
1262 format for Apple's iPhone, iPod, iTunes. Usually MPEG-4 is used as
1263 the container format and audio files encoded with AAC have the .m4a
1264 extension. A typical AAC frame is about 700 bytes large.
1265
1266 <h3> WMA </h3>
1267
1268 Windows Media Audio (WMA) is an audio data compression technology
1269 developed by Microsoft. A WMA file is usually encapsulated in the
1270 Advanced Systems Format (ASF) container format, which also specifies
1271 how meta data about the file is to be encoded. The bit stream of WMA
1272 is composed of superframes, each containing one or more frames of
1273 2048 samples. For 16 bit stereo a WMA superframe is about 8K large.
1274
1275 <h3> FLAC </h3>
1276
1277 The Free Lossless Audio Codec (FLAC) compresses audio without quality
1278 loss. It gives better compression ratios than a general purpose
1279 compressor like zip or bzip2 because FLAC is designed specifically
1280 for audio. A FLAC-encoded file consists of frames of varying size, up
1281 to 16K. Each frame starts with a header that contains all information
1282 necessary to decode the frame.
1283
1284 Meta data
1285 ---------
1286
1287 Unfortunately, each audio format has its own conventions how meta
1288 data is added as tags to the audio file.
1289
1290 For MP3 files, ID3, version 1 and 2 are widely used. ID3 version 1
1291 is rather simple but also very limited as it supports only artist,
1292 title, album, year and comment tags. Each of these can only be at most
1293 32 characters long. ID3, version 2 is much more flexible but requires
1294 a separate library being installed for paraslash to support it.
1295
1296 Ogg vorbis, ogg speex and flac files contain meta data as Vorbis
1297 comments, which are typically implemented as strings of the form
1298 "[TAG]=[VALUE]". Unlike ID3 version 1 tags, one may use whichever
1299 tags are appropriate for the content.
1300
1301 AAC files usually use the MPEG-4 container format for storing meta
1302 data while WMA files wrap meta data as special objects within the
1303 ASF container format.
1304
1305 paraslash only tracks the most common tags that are supported by
1306 all tag variants: artist, title, year, album, comment. When a file
1307 is added to the AFS database, the meta data of the file is extracted
1308 and stored in the audio file table.
1309
1310 Chunks and chunk tables
1311 -----------------------
1312
1313 paraslash uses the word "chunk" as common term for the building blocks
1314 of an audio file. For MP3 files, a chunk is the same as an MP3 frame,
1315 while for OGG files a chunk is an OGG page, etc.  Therefore the chunk
1316 size varies considerably between audio formats, from a few hundred
1317 bytes (MP3) up to 16K (FLAC).
1318
1319 The chunk table contains the offsets within the audio file that
1320 correspond to the chunk boundaries of the file. Like the meta data,
1321 the chunk table is computed and stored in the database whenever an
1322 audio file is added.
1323
1324 The paraslash senders (see below) always send complete chunks. The
1325 granularity for seeking is therefore determined by the chunk size.
1326
1327 Audio format handlers
1328 ---------------------
1329
1330 For each audio format paraslash contains an audio format handler whose
1331 first task is to tell whether a given file is a valid audio file of
1332 this type. If so, the audio file handler extracts some technical data
1333 (duration, sampling rate, number of channels etc.), computes the
1334 chunk table and reads the meta data.
1335
1336 The audio format handler code is linked into para_server and executed
1337 via the _add_ command. The same code is also available as a stand-alone
1338 tool, para_afh, which prints the technical data, the chunk table
1339 and the meta data of a file. Moreover, all audio format handlers are
1340 combined in the afh receiver which is part of para_recv and para_play.
1341
1342 ==========
1343 Networking
1344 ==========
1345
1346 Paraslash uses different network connections for control and data.
1347 para_client communicates with para_server over a dedicated TCP control
1348 connection. To transport audio data, separate data connections are
1349 used. For these data connections, a variety of transports (UDP, DCCP,
1350 HTTP) can be chosen.
1351
1352 The chapter starts with the [control
1353 service](#The.paraslash.control.service), followed by a section
1354 on the various [streaming protocols](#Streaming.protocols)
1355 in which the data connections are described. The way
1356 audio file headers are embedded into the stream is discussed
1357 [briefly](#Streams.with.headers.and.headerless.streams) before the
1358 [example section](#Networking.examples) which illustrates typical
1359 commands for real-life scenarios.
1360
1361 Both IPv4 and IPv6 are supported.
1362
1363 The paraslash control service
1364 -----------------------------
1365
1366 para_server is controlled at runtime via the paraslash control
1367 connection. This connection is used for server commands (play, stop,
1368 ...) as well as for afs commands (ls, select, ...).
1369
1370 The server listens on a TCP port and accepts connections from clients
1371 that connect the open port. Each connection causes the server to fork
1372 off a client process which inherits the connection and deals with that
1373 client only. In this classical accept/fork approach the server process
1374 is unaffected if the child dies or goes crazy for whatever reason. In
1375 fact, the child process can not change address space of server process.
1376
1377 The section on [client-server
1378 authentication](#Client-server.authentication) above described the
1379 early connection establishment from the crypto point of view. Here
1380 it is described what happens after the connection (including crypto
1381 setup) has been established.  There are four processes involved during
1382 command dispatch as sketched in the following diagram.
1383
1384         server_host                                   client_host
1385         ~~~~~~~~~~~                                   ~~~~~~~~~~~
1386
1387         +-----------+             connect            +-----------+
1388         |para_server|<------------------------------ |para_client|
1389         +-----------+                                +-----------+
1390              |                                             ^
1391              |     fork   +---+                            |
1392              +----------> |AFS|                            |
1393              |            +---+                            |
1394              |              ^                              |
1395              |              |                              |
1396              |              | connect (cookie)             |
1397              |              |                              |
1398              |              |                              |
1399              |    fork   +-----+    inherited connection   |
1400              +---------->|child|<--------------------------+
1401                          +-----+
1402
1403 Note that the child process is not a child of the afs process,
1404 so communication of these two processes has to happen via local
1405 sockets. In order to avoid abuse of the local socket by unrelated
1406 processes, a magic cookie is created once at server startup time just
1407 before the server process forks off the AFS process. This cookie is
1408 known to the server, AFS and the child, but not to unrelated processes.
1409
1410 There are two different kinds of commands: First there are commands
1411 that cause the server to respond with some answer such as the list
1412 of all audio files. All but the addblob commands (addimg, addlyr,
1413 addpl, addmood) are of this kind. The addblob commands add contents
1414 to the database, so they need to transfer data the other way round,
1415 from the client to the server.
1416
1417 There is no knowledge about the server commands built into para_client,
1418 so it does not know about addblob commands. Instead, the server sends
1419 a special "awaiting data" packet for these commands. If the client
1420 receives this packet, it sends STDIN to the server, otherwise it
1421 dumps data from the server to STDOUT.
1422
1423 Streaming protocols
1424 -------------------
1425
1426 A network (audio) stream usually consists of one streaming source,
1427 the _sender_, and one or more _receivers_ which read data over the
1428 network from the streaming source.
1429
1430 Senders are thus part of para_server while receivers are part of
1431 para_audiod. Moreover, there is the stand-alone tool para_recv which
1432 can be used to manually download a stream, either from para_server
1433 or from a web-based audio streaming service.
1434
1435 The following three streaming protocols are supported by paraslash:
1436
1437 - HTTP. Recommended for public streams that can be played by any
1438 player like mpg123, xmms, itunes, winamp, etc. The HTTP sender is
1439 supported on all operating systems and all platforms.
1440
1441 - DCCP. Recommended for LAN streaming. DCCP is currently available
1442 only for Linux.
1443
1444 - UDP. Recommended for multicast LAN streaming.
1445
1446 See the Appendix on [network protocols](#Network.protocols)
1447 for brief descriptions of the various protocols relevant for network
1448 audio streaming with paraslash.
1449
1450 It is possible to activate more than one sender simultaneously.
1451 Senders can be controlled at run time and via config file and command
1452 line options.
1453
1454 Note that audio connections are _not_ encrypted. Transport or Internet
1455 layer encryption should be used if encrypted data connections are
1456 needed.
1457
1458 Since DCCP and TCP are both connection-oriented protocols, connection
1459 establishment/teardown and access control are very similar between
1460 these two streaming protocols. UDP is the most lightweight option,
1461 since in contrast to TCP/DCCP it is connectionless. It is also the
1462 only protocol supporting IP multicast.
1463
1464 The HTTP and the DCCP sender listen on a (TCP/DCCP) port waiting for
1465 clients to connect and establish a connection via some protocol-defined
1466 handshake mechanism. Both senders maintain two linked lists each:
1467 The list of all clients which are currently connected, and the list
1468 of access control entries which determines who is allowed to connect.
1469 IP-based access control may be configured through config file and
1470 command line options and via the "allow" and "deny" sender subcommands.
1471
1472 Upon receiving a GET request from the client, the HTTP sender sends
1473 back a status line and a message. The body of this message is the
1474 audio stream. This is common practice and is supported by many popular
1475 clients which can thus be used to play a stream offered by para_server.
1476 For DCCP things are a bit simpler: No messages are exchanged between
1477 the receiver and sender. The client simply connects and the sender
1478 starts to stream.
1479
1480 DCCP is an experimental protocol which offers a number of new features
1481 not available for TCP. Both ends can negotiate these features using
1482 a built-in negotiation mechanism. In contrast to TCP/HTTP, DCCP is
1483 datagram-based (no retransmissions) and thus should not be used over
1484 lossy media (e.g. WiFi networks). One useful feature offered by DCCP
1485 is access to a variety of different congestion-control mechanisms
1486 called CCIDs. Two different CCIDs are available per default on Linux:
1487
1488
1489 - _CCID 2_. A Congestion Control mechanism similar to that of TCP. The
1490 sender maintains a congestion window and halves this window in response
1491 to congestion.
1492
1493
1494 - _CCID-3_. Designed to be fair when competing for bandwidth.
1495 It has lower variation of throughput over time compared with TCP,
1496 which makes it suitable for streaming media.
1497
1498 Unlike the HTTP and DCCP senders, the UDP sender maintains only a
1499 single list, the _target list_. This list describes the set of clients
1500 to which the stream is sent. There is no list for access control and
1501 no "allow" and "deny" commands for the UDP sender. Instead, the "add"
1502 and "delete" commands can be used to modify the target list.
1503
1504 Since both UDP and DCCP offer an unreliable datagram-based transport,
1505 additional measures are necessary to guard against disruptions over
1506 networks that are lossy or which may be subject to interference (as
1507 is for instance the case with WiFi). Paraslash uses FEC (Forward
1508 Error Correction) to guard against packet losses and reordering. The
1509 stream is FEC-encoded before it is sent through the UDP socket and
1510 must be decoded accordingly on the receiver side.
1511
1512 The packet size and the amount of redundancy introduced by FEC can
1513 be configured via the FEC parameters which are dictated by server
1514 and may also be configured through the "sender" command.  The FEC
1515 parameters are encoded in the header of each network packet, so no
1516 configuration is necessary on the receiver side. See the section on
1517 [FEC](#Forward.error.correction) below.
1518
1519 Streams with headers and headerless streams
1520 -------------------------------------------
1521
1522 For OGG/Vorbis, OGG/Speex and wma streams, some of the information
1523 needed to decode the stream is only contained in the audio file
1524 header of the container format but not in each data chunk. Clients
1525 must be able to obtain this information in case streaming starts in
1526 the middle of the file or if para_audiod is started while para_server
1527 is already sending a stream.
1528
1529 This is accomplished in different ways, depending on the streaming
1530 protocol. For connection-oriented streams (HTTP, DCCP) the audio file
1531 header is sent prior to audio file data. This technique however does
1532 not work for the connectionless UDP transport. Hence the audio file
1533 header is periodically being embedded into the UDP audio data stream.
1534 By default, the header is resent after five seconds. The receiver has
1535 to wait until the next header arrives before it can start decoding
1536 the stream.
1537
1538 Networking examples
1539 -------------------
1540
1541 The "si" (server info) command lists some information about the
1542 currently running server process.
1543
1544 -> Show PIDs, number of connected clients, uptime, and more:
1545
1546         para_client si
1547
1548 By default para_server activates both the HTTP and th DCCP sender on
1549 startup. This can be changed via command line options or para_server's
1550 config file.
1551
1552 -> List config file options for senders:
1553
1554         para_server -h
1555
1556 -> Receive a DCCP stream using CCID2 and write the output into a file:
1557
1558         host=foo.org; ccid=2; filename=bar
1559         para_recv --receiver "dccp --host $host --ccid $ccid" > $filename
1560
1561 Note the quotes around the arguments for the dccp receiver. Each
1562 receiver has its own set of command line options and its own command
1563 line parser, so arguments for the dccp receiver must be protected
1564 from being interpreted by para_recv.
1565
1566 -> Receive FEC-encoded multicast stream and write the output into a file:
1567
1568         filename=foo
1569         para_recv -r udp > $filename
1570
1571 -> Receive this (FEC-encoded) unicast stream:
1572
1573         filename=foo
1574         para_recv -r 'udp -i 0.0.0.0' > $filename
1575
1576 -> Create a minimal config for para_audiod for HTTP streams:
1577
1578         c=$HOME/.paraslash/audiod.conf.min; s=server.foo.com
1579         echo receiver \".:http -i $s\" > $c
1580         para_audiod --config $c
1581
1582 =======
1583 Filters
1584 =======
1585
1586 A paraslash filter is a module which transforms an input stream into
1587 an output stream. Filters are included in the para_audiod executable
1588 and in the stand-alone tool para_filter which usually contains the
1589 same modules.
1590
1591 While para_filter reads its input stream from STDIN and writes
1592 the output to STDOUT, the filter modules of para_audiod are always
1593 connected to a receiver which produces the input stream and a writer
1594 which absorbs the output stream.
1595
1596 Some filters depend on a specific library and are not compiled in
1597 if this library was not found at compile time. To see the list of
1598 supported filters, run para_filter and para_audiod with the --help
1599 option. The output looks similar to the following:
1600
1601         Available filters:
1602                 compress wav amp fecdec wmadec prebuffer oggdec aacdec mp3dec
1603
1604 Out of these filter modules, a chain of filters can be constructed,
1605 much in the way Unix pipes can be chained, and analogous to the use
1606 of modules in gstreamer: The output of the first filter becomes the
1607 input of the second filter. There is no limitation on the number of
1608 filters and the same filter may occur more than once.
1609
1610 Like receivers, each filter has its own command line options which
1611 must be quoted to protect them from the command line options of
1612 the driving application (para_audiod or para_filter). Example:
1613
1614         para_filter -f 'mp3dec --ignore-crc' -f 'compress --damp 1'
1615
1616 For para_audiod, each audio format has its own set of filters. The
1617 name of the audio format for which the filter should be applied can
1618 be used as the prefix for the filter option. Example:
1619
1620         para_audiod -f 'mp3:prebuffer --duration 300'
1621
1622 The "mp3" prefix above is actually interpreted as a POSIX extended
1623 regular expression. Therefore
1624
1625         para_audiod -f '.:prebuffer --duration 300'
1626
1627 activates the prebuffer filter for all supported audio formats (because
1628 "." matches all audio formats) while
1629
1630         para_audiod -f 'wma|ogg:prebuffer --duration 300'
1631
1632 activates it only for wma and ogg streams.
1633
1634 Decoders
1635 --------
1636
1637 For each supported audio format there is a corresponding filter
1638 which decodes audio data in this format to 16 bit PCM data which
1639 can be directly sent to the sound device or any other software that
1640 operates on undecoded PCM data (visualizers, equalizers etc.). Such
1641 filters are called _decoders_ in general, and xxxdec is the name of
1642 the paraslash decoder for the audio format xxx. For example, the mp3
1643 decoder is called mp3dec.
1644
1645 Note that the output of the decoder is about 10 times larger than
1646 its input. This means that filters that operate on the decoded audio
1647 stream have to deal with much more data than filters that transform
1648 the audio stream before it is fed to the decoder.
1649
1650 Paraslash relies on external libraries for most decoders, so these
1651 libraries must be installed for the decoder to be included in the
1652 executables. For example, the mp3dec filter depends on the mad library.
1653
1654 Forward error correction
1655 ------------------------
1656
1657 As already mentioned [earlier](#Streaming.protocols), paraslash
1658 uses forward error correction (FEC) for the unreliable UDP and
1659 DCCP transports. FEC is a technique which was invented already in
1660 1960 by Reed and Solomon and which is widely used for the parity
1661 calculations of storage devices (RAID arrays). It is based on the
1662 algebraic concept of finite fields, today called Galois fields, in
1663 honour of the mathematician Galois (1811-1832). The FEC implementation
1664 of paraslash is based on code by Luigi Rizzo.
1665
1666 Although the details require a sound knowledge of the underlying
1667 mathematics, the basic idea is not hard to understand: For positive
1668 integers k and n with k < n it is possible to compute for any k given
1669 data bytes d_1, ..., d_k the corresponding r := n -k parity bytes p_1,
1670 ..., p_r such that all data bytes can be reconstructed from *any*
1671 k bytes of the set
1672
1673         {d_1, ..., d_k, p_1, ..., p_r}.
1674
1675 FEC-encoding for unreliable network transports boils down to slicing
1676 the audio stream into groups of k suitably sized pieces called _slices_
1677 and computing the r corresponding parity slices. This step is performed
1678 in para_server which then sends both the data and the parity slices
1679 over the unreliable network connection. If the client was able
1680 to receive at least k of the n = k + r slices, it can reconstruct
1681 (FEC-decode) the original audio stream.
1682
1683 From these observations it is clear that there are three different
1684 FEC parameters: The slice size, the number of data slices k, and the
1685 total number of slices n. It is crucial to choose the slice size
1686 such that no fragmentation of network packets takes place because
1687 FEC only guards against losses and reordering but fails if slices are
1688 received partially.
1689
1690 FEC decoding in paralash is performed through the fecdec filter which
1691 usually is the first filter (there can be other filters before fecdec
1692 if these do not alter the audio stream).
1693
1694 Volume adjustment (amp and compress)
1695 ------------------------------------
1696
1697 The amp and the compress filter both adjust the volume of the audio
1698 stream. These filters operate on uncompressed audio samples. Hence
1699 they are usually placed directly after the decoding filter. Each
1700 sample is multiplied with a scaling factor (>= 1) which makes amp
1701 and compress quite expensive in terms of computing power.
1702
1703 <h3> amp </h3>
1704
1705 The amp filter amplifies the audio stream by a fixed scaling factor
1706 that must be known in advance. For para_audiod this factor is derived
1707 from the amplification field of the audio file's entry in the audio
1708 file table while para_filter uses the value given at the command line.
1709
1710 The optimal scaling factor F for an audio file is the largest real
1711 number F >= 1 such that after multiplication with F all samples still
1712 fit into the sample interval [-32768, 32767]. One can use para_filter
1713 in combination with the sox utility to compute F:
1714
1715         para_filter -f mp3dec -f wav < file.mp3 | sox -t wav - -e stat -v
1716
1717 The amplification value V which is stored in the audio file table,
1718 however, is an integer between 0 and 255 which is connected to F
1719 through the formula
1720
1721         V = (F - 1) * 64.
1722
1723 To store V in the audio file table, the command
1724
1725         para_client -- touch -a=V file.mp3
1726
1727 is used. The reader is encouraged to write a script that performs
1728 these computations :)
1729
1730 <h3> compress </h3>
1731
1732 Unlike the amplification filter, the compress filter adjusts the volume
1733 of the audio stream dynamically without prior knowledge about the peak
1734 value. It maintains the maximal volume of the last n samples of the
1735 audio stream and computes a suitable amplification factor based on that
1736 value and the various configuration options. It tries to chose this
1737 factor such that the adjusted volume meets the desired target level.
1738
1739 Note that it makes sense to combine amp and compress.
1740
1741 Misc filters (wav and prebuffer)
1742 --------------------------------
1743
1744 These filters are rather simple and do not modify the audio stream at
1745 all. The wav filter is only useful with para_filter and in connection
1746 with a decoder. It asks the decoder for the number of channels and the
1747 sample rate of the stream and adds a Microsoft wave header containing
1748 this information at the beginning. This allows writing wav files
1749 rather than raw PCM files (which do not contain any information about
1750 the number of channels and the sample rate).
1751
1752 The prebuffer filter simply delays the output until the given time has
1753 passed (starting from the time the first byte was available in its
1754 input queue) or until the given amount of data has accumulated. It
1755 is mainly useful for para_audiod if the standard parameters result
1756 in buffer underruns.
1757
1758 Both filters require almost no additional computing time, even when
1759 operating on uncompressed audio streams, since data buffers are simply
1760 "pushed down" rather than copied.
1761
1762 ======
1763 Output
1764 ======
1765
1766 Once an audio stream has been received and decoded to PCM format,
1767 it can be sent to a sound device for playback. This part is performed
1768 by paraslash _writers_ which are described in this chapter.
1769
1770 Writers
1771 -------
1772
1773 A paraslash writer acts as a data sink that consumes but does not
1774 produce audio data. Paraslash writers operate on the client side and
1775 are contained in para_audiod and in the stand-alone tool para_write.
1776
1777 The para_write program reads uncompressed audio data from STDIN. If
1778 this data starts with a wav header, sample rate, sample format and
1779 channel count are read from the header. Otherwise CD audio (44.1KHz
1780 16 bit little endian, stereo) is assumed but this can be overridden
1781 by command line options. para_audiod, on the other hand, obtains
1782 the sample rate and the number of channels from the decoder.
1783
1784 Like receivers and filters, each writer has an individual set of
1785 command line options, and for para_audiod writers can be configured
1786 per audio format separately. It is possible to activate more than
1787 one writer for the same stream simultaneously.
1788
1789 OS-dependent APIs
1790 -----------------
1791
1792 Unfortunately, the various flavours of Unix on which paraslash
1793 runs on have different APIs for opening a sound device and starting
1794 playback. Hence for each such API there is a paraslash writer that
1795 can play the audio stream via this API.
1796
1797 - *ALSA*. The _Advanced Linux Sound Architecture_ is only available on
1798 Linux systems. Although there are several mid-layer APIs in use by
1799 the various Linux distributions (ESD, Jack, PulseAudio), paraslash
1800 currently supports only the low-level ALSA API which is not supposed
1801 to be change. ALSA is very feature-rich, in particular it supports
1802 software mixing via its DMIX plugin. ALSA is the default writer on
1803 Linux systems.
1804
1805 - *OSS*. The _Open Sound System_ is the only API on \*BSD Unixes and
1806 is also available on Linux systems, usually provided by ALSA as an
1807 emulation for backwards compatibility. This API is rather simple but
1808 also limited. For example only one application can open the device
1809 at any time. The OSS writer is activated by default on BSD Systems.
1810
1811 - *FILE*. The file writer allows capturing the audio stream and
1812 writing the PCM data to a file on the file system rather than playing
1813 it through a sound device. It is supported on all platforms and is
1814 always compiled in.
1815
1816 - *AO*. _Libao_ is a cross-platform audio library which supports a wide
1817 variety of platforms including PulseAudio (gnome), ESD (Enlightened
1818 Sound Daemon), AIX, Solaris and IRIX.  The ao writer plays audio
1819 through an output plugin of libao.
1820
1821 Examples
1822 --------
1823
1824 -> Use the OSS writer to play a wav file:
1825
1826         para_write --writer oss < file.wav
1827
1828 -> Enable ALSA software mixing for mp3 streams:
1829
1830         para_audiod --writer 'mp3:alsa -d plug:swmix'
1831
1832
1833 ===
1834 Gui
1835 ===
1836
1837 para_gui executes an arbitrary command which is supposed to print
1838 status information to STDOUT. It then displays this information in
1839 a curses window. By default the command
1840
1841         para_audioc -- stat -p
1842
1843 is executed, but this can be customized via the --stat-cmd option. In
1844 particular it possible to use
1845
1846         para_client -- stat -p
1847
1848 to make para_gui work on systems on which para_audiod is not running.
1849
1850 Key bindings
1851 ------------
1852
1853 It is possible to bind keys to arbitrary commands via custom
1854 key-bindings. Besides the internal keys which can not be changed (help,
1855 quit, loglevel, version...), the following flavours of key-bindings
1856 are supported:
1857
1858 - external: Shutdown curses before launching the given command.
1859 Useful for starting other ncurses programs from within para_gui,
1860 e.g. aumix or dialog scripts. Or, use the mbox output format to write
1861 a mailbox containing one mail for each (admissible) file the audio
1862 file selector knows about. Then start mutt from within para_gui to
1863 browse your collection!
1864
1865 - display: Launch the command and display its stdout in para_gui's
1866 bottom window.
1867
1868 - para: Like display, but start "para_client <specified command>"
1869 instead of "<specified command>".
1870
1871 The general form of a key binding is
1872
1873         key_map k:m:c
1874
1875 which maps key k to command c using mode m. Mode may be x, d or p
1876 for external, display and paraslash commands, respectively.
1877
1878 Themes
1879 ------
1880
1881 Currently there are only two themes for para_gui. It is easy, however,
1882 to add more themes. To create a new theme one has to define the
1883 position, color and geometry for for each status item that should be
1884 shown by this theme. See gui_theme.c for examples.
1885
1886 The "." and "," keys are used to switch between themes.
1887
1888 Examples
1889 --------
1890
1891 -> Show server info:
1892
1893         key_map "i:p:si"
1894
1895 -> Jump to the middle of the current audio file by pressing F5:
1896
1897         key_map "<F5>:p:jmp 50"
1898
1899 -> vi-like bindings for jumping around:
1900
1901         key_map "l:p:ff 10"
1902         key_map "h:p:ff 10-"
1903         key_map "w:p:ff 60"
1904         key_map "b:p:ff 60-"
1905
1906 -> Print the current date and time:
1907
1908         key_map "D:d:date"
1909
1910 -> Call other curses programs:
1911
1912         key_map "U:x:aumix"
1913         key_map "!:x:/bin/bash"
1914         key_map "^E:x:/bin/sh -c 'vi ~/.paraslash/gui.conf'"
1915
1916 ===========
1917 Development
1918 ===========
1919
1920 Contributing
1921 ------------
1922
1923 Paraslash is an open source project and contributions are
1924 welcome. Here's a list of things you can do to help the project:
1925
1926 - Report problems with building, installing or running the software.
1927   In particular, test the experimental git branches ("next" and "pu").
1928   This helps to identify and fix problems before the code gets merged
1929   and thus keeps the master branch as stable as possible.
1930 - Proofread the documentation (manual, web pages, man pages, source
1931   code documentation) and point out unclear or poorly written parts. If
1932   you are a native English speaker you will easily find a lot of text
1933   that could be improved.
1934 - Run analysis tools (coverity, afl, sparse, etc.) and report issues
1935   found by those tools.
1936 - Suggest new features you would like to see implemented.
1937 - Compile and test on your favorite architecture or operating
1938   system. The code is tested only on a limited set of systems, so you
1939   will probably encounter problems when building on different systems.
1940 - Post about paraslash on your blog or on social networks.
1941 - Build and maintain Debian/RPM packages for your favorite distribution.
1942
1943 Note that there is no mailing list, no bug tracker and no discussion
1944 forum for paraslash. If you'd like to contribute, or have questions
1945 about contributing, send email to Andre Noll <maan@tuebingen.mpg.de>.
1946 New releases are announced by email. If you would like to receive
1947 these announcements, contact the author through the above address.
1948
1949 Tools
1950 -----
1951
1952 In order to compile the sources from the git repository (rather than
1953 from tar balls) and for contributing non-trivial changes to the
1954 paraslash project, some additional tools should be installed on a
1955 developer machine.
1956
1957 - [git](http://git.or.cz/). As described in more detail
1958 [below](#Git.branches), the git source code management tool is used for
1959 paraslash development. It is necessary for cloning the git repository
1960 and for getting updates.
1961
1962 - [autoconf](ftp://ftp.gnu.org/pub/gnu/autoconf/) GNU autoconf creates
1963 the configure file which is shipped in the tarballs but has to be
1964 generated when compiling from git.
1965
1966 - [discount](http://www.pell.portland.or.us/~orc/Code/discount/). The
1967 HTML version of this manual and some of the paraslash web pages are
1968 written in the Markdown markup language and are translated into html
1969 with the converter of the *Discount* package.
1970
1971 - [doxygen](http://www.stack.nl/~dimitri/doxygen/). The documentation
1972 of paraslash's C sources uses the doxygen documentation system. The
1973 conventions for documenting the source code is described in the
1974 [Doxygen section](#Doxygen).
1975
1976 - [global](ftp://ftp.gnu.org/pub/gnu/global). This is used to generate
1977 browsable HTML from the C sources. It is needed by doxygen.
1978
1979 Git branches
1980 ------------
1981
1982 Paraslash has been developed using the git source code management
1983 tool since 2006. Development is organized roughly in the same spirit
1984 as the git development itself, as described below.
1985
1986 The following text passage is based on "A note from the maintainer",
1987 written by Junio C Hamano, the maintainer of git.
1988
1989 There are four branches in the paraslash repository that track the
1990 source tree: "master", "maint", "next", and "pu".
1991
1992 The "master" branch is meant to contain what is well tested and
1993 ready to be used in a production setting. There could occasionally be
1994 minor breakages or brown paper bag bugs but they are not expected to
1995 be anything major, and more importantly quickly and easily fixable.
1996 Every now and then, a "feature release" is cut from the tip of this
1997 branch, named with three dotted decimal digits, like 0.4.2.
1998
1999 Whenever changes are about to be included that will eventually lead to
2000 a new major release (e.g. 0.5.0), a "maint" branch is forked off from
2001 "master" at that point. Obvious, safe and urgent fixes after the major
2002 release are applied to this branch and maintenance releases are cut
2003 from it. New features never go to this branch. This branch is also
2004 merged into "master" to propagate the fixes forward.
2005
2006 A trivial and safe enhancement goes directly on top of "master".
2007 New development does not usually happen on "master", however.
2008 Instead, a separate topic branch is forked from the tip of "master",
2009 and it first is tested in isolation; Usually there are a handful such
2010 topic branches that are running ahead of "master". The tip of these
2011 branches is not published in the public repository to keep the number
2012 of branches that downstream developers need to worry about low.
2013
2014 The quality of topic branches varies widely. Some of them start out as
2015 "good idea but obviously is broken in some areas" and then with some
2016 more work become "more or less done and can now be tested by wider
2017 audience". Luckily, most of them start out in the latter, better shape.
2018
2019 The "next" branch is to merge and test topic branches in the latter
2020 category.  In general, this branch always contains the tip of "master".
2021 It might not be quite rock-solid production ready, but is expected to
2022 work more or less without major breakage. The maintainer usually uses
2023 the "next" version of paraslash for his own pleasure, so it cannot
2024 be _that_ broken. The "next" branch is where new and exciting things
2025 take place.
2026
2027 The two branches "master" and "maint" are never rewound, and "next"
2028 usually will not be either (this automatically means the topics that
2029 have been merged into "next" are usually not rebased, and you can find
2030 the tip of topic branches you are interested in from the output of
2031 "git log next"). You should be able to safely build on top of them.
2032
2033 However, at times "next" will be rebuilt from the tip of "master" to
2034 get rid of merge commits that will never be in "master". The commit
2035 that replaces "next" will usually have the identical tree, but it
2036 will have different ancestry from the tip of "master".
2037
2038 The "pu" (proposed updates) branch bundles the remainder of the
2039 topic branches.  The "pu" branch, and topic branches that are only in
2040 "pu", are subject to rebasing in general.  By the above definition
2041 of how "next" works, you can tell that this branch will contain quite
2042 experimental and obviously broken stuff.
2043
2044 When a topic that was in "pu" proves to be in testable shape, it
2045 graduates to "next".  This is done with
2046
2047                 git checkout next
2048                 git merge that-topic-branch
2049
2050 Sometimes, an idea that looked promising turns out to be not so good
2051 and the topic can be dropped from "pu" in such a case.
2052
2053 A topic that is in "next" is expected to be polished to perfection
2054 before it is merged to "master".  Similar to the above, this is
2055 done with
2056
2057                 git checkout master
2058                 git merge that-topic-branch
2059                 git branch -d that-topic-branch
2060
2061 Note that being in "next" is not a guarantee to appear in the next
2062 release (being in "master" is such a guarantee, unless it is later
2063 found seriously broken and reverted), nor even in any future release.
2064
2065 Coding Style
2066 ------------
2067
2068 The preferred coding style for paraslash coincides more or less
2069 with the style of the Linux kernel. So rather than repeating what is
2070 written [there](https://www.kernel.org/doc/Documentation/process/coding-style.rst),
2071 here are the most important points.
2072
2073 - Burn the GNU coding standards.
2074 - Never use spaces for indentation.
2075 - Tabs are 8 characters, and thus indentations are also 8 characters.
2076 - Don't put multiple assignments on a single line.
2077 - Avoid tricky expressions.
2078 - Don't leave whitespace at the end of lines.
2079 - The limit on the length of lines is 80 columns.
2080 - Use K&R style for placing braces and spaces:
2081 <pre>
2082                 if (x is true) {
2083                         we do y
2084                 }
2085 </pre>
2086 - Use a space after (most) keywords.
2087 - Do not add spaces around (inside) parenthesized expressions.
2088 - Use one space around (on each side of) most binary and ternary operators.
2089 - Do not use cute names like ThisVariableIsATemporaryCounter, call it tmp.
2090 - Mixed-case names are frowned upon.
2091 - Descriptive names for global variables are a must.
2092 - Avoid typedefs.
2093 - Functions should be short and sweet, and do just one thing.
2094 - The number of local variables shouldn't exceed 10.
2095 - Gotos are fine if they improve readability and reduce nesting.
2096 - Don't use C99-style "// ..." comments.
2097 - Names of macros defining constants and labels in enums are capitalized.
2098 - Enums are preferred when defining several related constants.
2099 - Always use the paraslash wrappers for allocating memory.
2100 - If the name of a function is an action or an imperative.
2101   command, the function should return an error-code integer
2102   (<0 means error, >=0 means success). If the name is a
2103   predicate, the function should return a "succeeded" boolean.
2104
2105 Doxygen
2106 -------
2107
2108 Doxygen is a documentation system for various programming
2109 languages. The API reference on the paraslash web page is generated
2110 by doxygen.
2111
2112 It is more illustrative to look at the source code for examples than
2113 to describe the conventions in this manual, so we only describe which
2114 parts of the code need doxygen comments, but leave out details on
2115 documentation conventions.
2116
2117 As a rule, only the public part of the C source is documented with
2118 Doxygen. This includes structures, defines and enumerations in header
2119 files as well as public (non-static) C functions.  These should be
2120 documented completely. For example, each parameter and the return
2121 value of a public function should get a descriptive doxygen comment.
2122
2123 No doxygen comments are necessary for static functions and for
2124 structures and enumerations in C files (which are used only within
2125 this file). This does not mean, however, that those entities need
2126 no documentation at all. Instead, common sense should be applied to
2127 document what is not obvious from reading the code.
2128
2129 ========
2130 Appendix
2131 ========
2132
2133 Network protocols
2134 -----------------
2135
2136 <h3> IP </h3>
2137
2138 The _Internet Protocol_ is the primary networking protocol used for
2139 the Internet. All protocols described below use IP as the underlying
2140 layer. Both the prevalent IPv4 and the next-generation IPv6 variant
2141 are being deployed actively worldwide.
2142
2143 <h3> Connection-oriented and connectionless protocols </h3>
2144
2145 Connectionless protocols differ from connection-oriented ones in
2146 that state associated with the sending/receiving endpoints is treated
2147 implicitly. Connectionless protocols maintain no internal knowledge
2148 about the state of the connection. Hence they are not capable of
2149 reacting to state changes, such as sudden loss or congestion on the
2150 connection medium. Connection-oriented protocols, in contrast, make
2151 this knowledge explicit. The connection is established only after
2152 a bidirectional handshake which requires both endpoints to agree
2153 on the state of the connection, and may also involve negotiating
2154 specific parameters for the particular connection. Maintaining an
2155 up-to-date internal state of the connection also in general means
2156 that the sending endpoints perform congestion control, adapting to
2157 qualitative changes of the connection medium.
2158
2159 <h3> Reliability </h3>
2160
2161 In IP networking, packets can be lost, duplicated, or delivered
2162 out of order, and different network protocols handle these
2163 problems in different ways. We call a transport-layer protocol
2164 _reliable_, if it turns the unreliable IP delivery into an ordered,
2165 duplicate- and loss-free delivery of packets. Sequence numbers
2166 are used to discard duplicates and re-arrange packets delivered
2167 out-of-order. Retransmission is used to guarantee loss-free
2168 delivery. Unreliable protocols, in contrast, do not guarantee ordering
2169 or data integrity.
2170
2171 <h3> Classification </h3>
2172
2173 With these definitions the protocols which are used by paraslash for
2174 steaming audio data may be classified as follows.
2175
2176         - HTTP/TCP: connection-oriented, reliable,
2177         - UDP: connectionless, unreliable,
2178         - DCCP: connection-oriented, unreliable.
2179
2180 Below we give a short descriptions of these protocols.
2181
2182 <h3> TCP </h3>
2183
2184 The _Transmission Control Protocol_ provides reliable, ordered delivery
2185 of a stream and a classic window-based congestion control. In contrast
2186 to UDP and DCCP (see below), TCP does not have record-oriented or
2187 datagram-based syntax, i.e. it provides a stream which is unaware
2188 and independent of any record (packet) boundaries.  TCP is used
2189 extensively by many application layers. Besides HTTP (the Hypertext
2190 Transfer Protocol), also FTP (the File Transfer protocol), SMTP (Simple
2191 Mail Transfer Protocol), SSH (Secure Shell) all sit on top of TCP.
2192
2193 <h3> UDP </h3>
2194
2195 The _User Datagram Protocol_ is the simplest transport-layer protocol,
2196 built as a thin layer directly on top of IP. For this reason, it offers
2197 the same best-effort service as IP itself, i.e. there is no detection
2198 of duplicate or reordered packets. Being a connectionless protocol,
2199 only minimal internal state about the connection is maintained, which
2200 means that there is no protection against packet loss or network
2201 congestion. Error checking and correction (if at all) are performed
2202 in the application.
2203
2204 <h3> DCCP </h3>
2205
2206 The _Datagram Congestion Control Protocol_ combines the
2207 connection-oriented state maintenance known from TCP with the
2208 unreliable, datagram-based transport of UDP. This means that it
2209 is capable of reacting to changes in the connection by performing
2210 congestion control, offering multiple alternative approaches. But it
2211 is bound to datagram boundaries (the maximum packet size supported
2212 by a medium), and like UDP it lacks retransmission to protect
2213 against loss. Due to the use of sequence numbers, it is however
2214 able to react to loss (interpreted as a congestion indication) and
2215 to ignore out-of-order and duplicate packets. Unlike TCP it allows
2216 to negotiate specific, binding features for a connection, such as
2217 the choice of congestion control: classic, window-based congestion
2218 control known from TCP is available as CCID-2, rate-based, "smooth"
2219 congestion control is offered as CCID-3.
2220
2221 <h3> HTTP </h3>
2222
2223 The _Hypertext Transfer Protocol_ is an application layer protocol
2224 on top of TCP. It is spoken by web servers and is most often used
2225 for web services.  However, as can be seen by the many Internet radio
2226 stations and YouTube/Flash videos, http is by far not limited to the
2227 delivery of web pages only. Being a simple request/response based
2228 protocol, the semantics of the protocol also allow the delivery of
2229 multimedia content, such as audio over http.
2230
2231 <h3> Multicast </h3>
2232
2233 IP multicast is not really a protocol but a technique for one-to-many
2234 communication over an IP network. The challenge is to deliver
2235 information to a group of destinations simultaneously using the
2236 most efficient strategy to send the messages over each link of the
2237 network only once. This has benefits for streaming multimedia: the
2238 standard one-to-one unicast offered by TCP/DCCP means that n clients
2239 listening to the same stream also consume n-times the resources,
2240 whereas multicast requires to send the stream just once, irrespective
2241 of the number of receivers.  Since it would be costly to maintain state
2242 for each listening receiver, multicast often implies connectionless
2243 transport, which is the reason that it is currently only available
2244 via UDP.
2245
2246 Abstract socket namespace
2247 -------------------------
2248 UNIX domain sockets are a traditional way to communicate between
2249 processes on the same machine. They are always reliable (see above)
2250 and don't reorder datagrams. Unlike TCP and UDP, UNIX domain sockets
2251 support passing open file descriptors or process credentials to
2252 other processes.
2253
2254 The usual way to set up a UNIX domain socket (as obtained from
2255 socket(2)) for listening is to first bind the socket to a file system
2256 pathname and then call listen(2), then accept(2). Such sockets are
2257 called _pathname sockets_ because bind(2) creates a special socket
2258 file at the specified path. Pathname sockets allow unrelated processes
2259 to communicate with the listening process by binding to the same path
2260 and calling connect(2).
2261
2262 There are two problems with pathname sockets:
2263
2264         * The listing process must be able to (safely) create the
2265         socket special in a directory which is also accessible to
2266         the connecting process.
2267
2268         * After an unclean shutdown of the listening process, a stale
2269         socket special may reside on the file system.
2270
2271 The abstract socket namespace is a non-portable Linux feature which
2272 avoids these problems. Abstract sockets are still bound to a name,
2273 but the name has no connection with file system pathnames.
2274
2275 License
2276 -------
2277
2278 Paraslash is licensed under the GPL, version 2. Most of the code
2279 base has been written from scratch, and those parts are GPL V2
2280 throughout. Notable exceptions are FEC and the WMA decoder. See the
2281 corresponding source files for licencing details for these parts. Some
2282 code sniplets of several other third party software packages have
2283 been incorporated into the paraslash sources, for example log message
2284 coloring was taken from the git sources. These third party software
2285 packages are all published under the GPL or some other license
2286 compatible to the GPL.
2287
2288 Acknowledgements
2289 ----------------
2290
2291 Many thanks to Gerrit Renker who read an early draft of this manual
2292 and contributed significant improvements.
2293
2294 ==========
2295 References
2296 ==========
2297
2298 Articles
2299 --------
2300 - [Polynomial Codes over Certain Finite
2301 Fields](http://kom.aau.dk/~heb/kurser/NOTER/KOFA01.PDF) by Reed, Irving
2302 S.; Solomon, Gustave (1960), Journal of the Society for Industrial
2303 and Applied Mathematics (SIAM) 8 (2): 300-304, doi:10.1137/0108018)
2304
2305 RFCs
2306 ----
2307
2308 - [RFC 768](http://www.ietf.org/rfc/rfc768.txt) (1980): User Datagram
2309 Protocol
2310
2311 - [RFC 791](http://www.ietf.org/rfc/rfc791.txt) (1981): Internet
2312 Protocol
2313
2314 - [RFC 2437](http://www.ietf.org/rfc/rfc2437.txt) (1998): RSA
2315 Cryptography Specifications
2316
2317 - [RFC 4340](http://www.ietf.org/rfc/rfc4340.txt) (2006): Datagram
2318 Congestion Control Protocol (DCCP)
2319
2320 - [RFC 4341](http://www.ietf.org/rfc/rfc4341.txt) (2006): Congestion
2321 Control ID 2: TCP-like Congestion Control
2322
2323 - [RFC 4342](http://www.ietf.org/rfc/rfc4342.txt) (2006): Congestion
2324 Control ID 3: TCP-Friendly Rate Control (TFRC)
2325
2326 - [RFC 6716](http://www.ietf.org/rfc/rfc6716.txt) (2012): Definition
2327 of the Opus Audio Codec
2328
2329 Application web pages
2330 ---------------------
2331
2332 - [paraslash](http://people.tuebingen.mpg.de/maan/paraslash/)
2333 - [xmms](https://xmms2.org/wiki/Main_Page)
2334 - [mpg123](http://www.mpg123.de/)
2335 - [gstreamer](https://gstreamer.freedesktop.org/)
2336 - [icecast](http://www.icecast.org/)
2337 - [Audio Compress](https://beesbuzz.biz/code/audiocompress.php)
2338
2339 External documentation
2340 ----------------------
2341
2342 - [The mathematics of
2343 Raid6](https://www.kernel.org/pub/linux/kernel/people/hpa/raid6.pdf)
2344 by H. Peter Anvin
2345
2346 - [Effective Erasure Codes for reliable Computer Communication
2347 Protocols](http://info.iet.unipi.it/~luigi/fec_ccr.ps.gz) by Luigi
2348 Rizzo
2349
2350 Code
2351 ----
2352 - [Original FEC
2353 implementation](http://info.iet.unipi.it/~luigi/vdm.tar.gz) by
2354 Luigi Rizzo)