### Input from ALSA Soundcard
Source: https://www.liquidsoap.info/doc-2.3.1/quick_start
Captures audio input directly from the ALSA soundcard. This requires a working ALSA setup on the system. It's a direct way to get audio from hardware into Liquidsoap.
```liquidsoap
liquidsoap 'output.alsa(input.alsa())'
```
--------------------------------
### Liquidsoap Common Settings Examples
Source: https://www.liquidsoap.info/doc-2.3.1/help
Provides examples of common Liquidsoap settings that can be used to configure the application's behavior.
```APIDOC
## Liquidsoap Settings Configuration
### Description
These are examples of common Liquidsoap settings that can be modified to control application behavior, such as logging levels, audio/video parameters, and initialization options.
### Method
N/A (These are configuration directives within a Liquidsoap script)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```liquidsoap
# Enable verbose logging
settings.log.level := 4
# Log to a file
settings.log.file := true
# Log to standard output
settings.log.stdout := true
# Run Liquidsoap as a daemon
init.daemon := true
# Set audio sample rate
audio.samplerate := 48000
# Set audio channels
audio.channels := 2
# Set video frame width
video.frame.width := 720
# Set video frame height
video.frame.height := 1280
```
### Response
N/A (These are configuration settings, not API responses)
```
--------------------------------
### Example: Set Metadata
Source: https://www.liquidsoap.info/doc-2.3.1/harbor_http
Register a GET handler that allows updating the metadata of a source via HTTP requests. Metadata is passed as query parameters.
```APIDOC
## Set metadata
Using `insert_metadata`, you can register a GET handler that updates the metadata of a given source. For instance:
```
# s = some source
# Create a source equipped with a `insert_metadata` method:
s = insert_metadata(s)
# The handler
def set_meta(request, response) =
# Filter out unusual metadata
meta = metadata.export(request.query)
# Grab the returned message
ret =
if
meta != []
then
s.insert_metadata(meta)
"OK!"
else
"No metadata to add!"
end
response.html("
#{ret}")
end
# Register handler on port 700
harbor.http.register(port=7000, method="GET", "/setmeta", set_meta)
```
Now, a request of the form `http://server:7000/setmeta?title=foo` will update the metadata of source `s` with `[("title","foo")]`. You can use this handler, for instance, in a custom HTML form.
```
--------------------------------
### Example: Get Metadata
Source: https://www.liquidsoap.info/doc-2.3.1/harbor_http
Register an HTTP endpoint to fetch and display the current metadata of a source. This endpoint returns metadata in JSON format.
```APIDOC
## Get metadata
You can use harbor to register HTTP services to fecth/set the metadata of a source.
```
meta = ref([])
# s = some source
s.on_metadata(fun (m) -> meta := m)
# Return the json content of meta
def get_meta(_, response) =
response.json(meta())
end
# Register get_meta at port 700
harbor.http.register(port=7000, method="GET", "/getmeta", get_meta)
```
Once the script is running, a GET request for `/getmeta` at port `7000` returns the following:
```
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
"genre": "Soul",
"album": "The Complete Stax-Volt Singles: 1959-1968 (Disc 8)",
"artist": "Astors",
"title": "Daddy Didn't Tell Me"
}
```
```
--------------------------------
### Common Liquidsoap Settings Examples
Source: https://www.liquidsoap.info/doc-2.3.1/help
Examples of common Liquidsoap settings that control application behavior, such as logging levels, file output, daemon mode, and audio/video parameters. These are shortcuts to their respective 'settings' values.
```liquidsoap
settings.log.level := 4
settings.log.file := true
settings.log.stdout := true
init.daemon := true
audio.samplerate := 48000
audio.channels := 2
video.frame.width := 720
video.frame.height := 1280
```
--------------------------------
### Example of Output with Crossfade and Playlist
Source: https://www.liquidsoap.info/doc-2.3.1/clocks
This example demonstrates a typical Liquidsoap setup involving an Icecast output, a crossfade operator, and a playlist. It illustrates how different parts of the stream can be managed by distinct clocks, with the crossfade operator potentially using a dedicated internal clock for smoother track transitions.
```liquidsoap
output.icecast(fallback([crossfade(playlist(...)),jingles]))
```
--------------------------------
### Liquidsoap String Escaping Example (OCaml REPL)
Source: https://www.liquidsoap.info/doc-2.3.1/language
Provides an example of an escaped string in the Liquidsoap OCaml REPL, showing how various escape sequences are interpreted.
```ocaml
# "\" \t \045 \x2f \u4f32";;
- : string = """ % / 2"
```
--------------------------------
### Create OCaml Switch and Install Liquidsoap with FFmpeg using OPAM
Source: https://www.liquidsoap.info/doc-2.3.1/install
Installs Liquidsoap along with the FFmpeg package using the OPAM package manager. This method ensures most expected functionalities like encoding, decoding, and metadata support are available out-of-the-box. It also handles external system dependencies.
```bash
opam switch create
opam install ffmpeg liquidsoap
```
--------------------------------
### Start Live Show Relay with Liquidsoap
Source: https://www.liquidsoap.info/doc-2.3.1/complete_case
This command demonstrates how to start a live show relay using Liquidsoap. It configures an Icecast output for the live stream, specifying the format, mount point, host, password, and using ALSA as the audio input source.
```bash
liquidsoap 'output.icecast(%vorbis, \
mount="live.ogg",host="...",password="...",input.alsa())'
```
--------------------------------
### Run Liquidsoap Script File
Source: https://www.liquidsoap.info/doc-2.3.1/quick_start
Executes a Liquidsoap script file. Scripts allow for more complex configurations and better code organization. The file should have a `.liq` extension.
```bash
liquidsoap myscript.liq
```
--------------------------------
### Liquidsoap Playlist with Cue Points Example
Source: https://www.liquidsoap.info/doc-2.3.1/seek
This example shows how to configure a playlist source in Liquidsoap to use cue-in and cue-out points. It utilizes the `annotate` protocol to specify absolute cue-in and cue-out times (in seconds) for all tracks within the playlist. This is useful for precisely cutting the beginning and end of audio files.
```liquidsoap
s = playlist(prefix="annotate:liq_cue_in=\"10.\",liq_cue_out=\"45\":",
"/path/to/music")
```
--------------------------------
### Liquidsoap 'while' loop example
Source: https://www.liquidsoap.info/doc-2.3.1/language
Illustrates the 'while' loop in Liquidsoap, which repeatedly executes code as long as a condition remains true. This example doubles a reference 'n' until its value is no longer less than 10.
```liquidsoap
n = ref(1)
while n() < 10 do
n := n() * 2
end
print(n())
```
--------------------------------
### Input from HTTP Stream
Source: https://www.liquidsoap.info/doc-2.3.1/quick_start
Uses an audio stream from a remote HTTP source (e.g., an Icecast radio stream) as an audio input for Liquidsoap. This is useful for processing or rebroadcasting existing streams.
```liquidsoap
liquidsoap \
'output(input.http("https://icecast.radiofrance.fr/fip-hifi.aac"))'
```
--------------------------------
### Install Optional Opus Support for Liquidsoap using OPAM
Source: https://www.liquidsoap.info/doc-2.3.1/install
Adds optional Opus encoding and decoding support to an existing Liquidsoap installation managed by OPAM. This command installs the 'opus' package and its dependencies, then recompiles Liquidsoap to include the new functionality.
```bash
opam install opus
```
--------------------------------
### Custom Authentication Function Example
Source: https://www.liquidsoap.info/doc-2.3.1/harbor
An example demonstrating how to define a custom `auth` function to handle user authentication for harbor sources, potentially by calling an external script.
```APIDOC
## Custom Authentication Function Example
This example shows how to implement a custom authentication logic using an external script.
### `auth` Function Definition
```liquidsoap
def auth(args)
# Call an external process to check the credentials.
# Ensure proper escaping of arguments to prevent command injection.
ret = process.read.lines(
"/path/to/script --user=#{args.user} --password=#{args.password}"
)
# Get the first line of the output.
ret = list.hd(default="", ret)
# Return true if the output is "true", otherwise false.
if ret == "true" then true else false end
end
```
### Notes on ICY (Shoutcast) Connections
For ICY connections, the `user` parameter passed to `input.harbor` is used as the username for the authentication function. The source client does not provide a username directly.
```
--------------------------------
### Liquidsoap 'for' loop example
Source: https://www.liquidsoap.info/doc-2.3.1/language
Demonstrates the 'for' loop in Liquidsoap, which iterates a block of code with an integer variable incrementing within specified bounds. This example prints integers from 1 to 5.
```liquidsoap
for i = 1 to 5 do
print(i)
end
```
--------------------------------
### Example: Redirect Icecast Pages
Source: https://www.liquidsoap.info/doc-2.3.1/harbor_http
Configure a handler to redirect specific HTTP requests to an Icecast server, useful for serving listener statistics or other Icecast-related pages.
```APIDOC
## Examples
These functions can be used to create your own HTTP interface. Some examples are:
## Redirect Icecast’s pages
Some source clients using the harbor may also request pages that are served by an icecast server, for instance listeners statistics. In this case, you can register the following handler:
```
# Redirect all files other than /admin.* to icecast, located at localhost:8000.
def redirect_icecast(request, response) =
response.redirect("http://localhost:8000#{request.path}")
end
# Register this handler at port 8005 (provided harbor sources are also served
# from this port).
harbor.http.register.regexp(
port=8005, method="GET", r/^\/admin/, redirect_icecast
)
```
```
--------------------------------
### On-Demand Relaying Without Re-encoding using FFmpeg
Source: https://www.liquidsoap.info/doc-2.3.1/ffmpeg_cookbook
This example shows how to relay a stream on-demand, starting and stopping the input only when listeners are connected, all without re-encoding. It uses FFmpeg with a format like MP3 and a fallback mechanism with a blank file to manage the stream's availability based on listener count.
```liquidsoap
stream = input.http(start = false, "https://wwoz-sc.streamguys1.com/wwoz-hi.mp3")
listeners_count = ref(0)
def on_connect(~headers=_, ~uri=_, ~protocol=_, _) =
listeners_count := listeners_count() + 1
if listeners_count() > 0 and not stream.is_started() then
log("Starting input")
stream.start()
end
end
def on_disconnect(_) =
listeners_count := listeners_count() - 1
if listeners_count() == 0 and stream.is_started() then
log("Stopping input")
stream.stop()
end
end
blank = single("/tmp/blank.mp3")
stream = fallback(track_sensitive=false, [stream, blank])
output.harbor(
%ffmpeg(format="mp3", %audio.copy),
format="audio/mpeg",
mount="relay",
on_connect=on_connect,
on_disconnect=on_disconnect,
stream)
```
--------------------------------
### Stream Audio to Icecast Server
Source: https://www.liquidsoap.info/doc-2.3.1/quick_start
Streams audio encoded as Ogg Vorbis to an Icecast server. Requires optional dependencies like 'cry' for Icecast output and 'vorbis' for encoding. The `mksafe` function ensures a stable playlist source.
```liquidsoap
liquidsoap \
'output.icecast(%vorbis,
host = "localhost", port = 8000,
password = "hackme", mount = "liq.ogg",
mksafe(playlist("playlist.m3u")))'
```
--------------------------------
### Install FFmpeg Package with Opam
Source: https://www.liquidsoap.info/doc-2.3.1/ffmpeg
This command installs the FFmpeg binding package for Liquidsoap using the opam package manager. Ensure opam is configured correctly for your system.
```bash
% opam install ffmpeg
```
--------------------------------
### Example: Icecast Output with Random Playlist Fallback
Source: https://www.liquidsoap.info/doc-2.3.1/sources
This example demonstrates how to configure an Icecast output using Liquidsoap. It utilizes a 'random' combinator to select from a fallback mechanism that chooses between multiple playlists, ensuring continuous playback even if some playlists are unavailable. The output format is Vorbis.
```liquidsoap
radio = output.icecast(
%vorbis,mount="test.ogg",
random(
[ jingle ,
fallback([ playlist1,playlist2,playlist3 ]) ]))
```
--------------------------------
### List Available Settings in Liquidsoap
Source: https://www.liquidsoap.info/doc-2.3.1/help
Retrieve a comprehensive list of all available settings in Liquidsoap, along with their documentation. This output can be used as a starting point for configuring Liquidsoap's behavior by editing and loading the script.
```bash
liquidsoap --list-settings
```
--------------------------------
### Make Liquidsoap Script Executable
Source: https://www.liquidsoap.info/doc-2.3.1/quick_start
Makes a Liquidsoap script file executable using the `chmod` command. This allows the script to be run directly as a program, especially when using a shebang line.
```bash
chmod u+x myscript.liq
```
--------------------------------
### Example: Available Codecs for AV1 Decoding
Source: https://www.liquidsoap.info/doc-2.3.1/settings
Specifies the available codecs that FFmpeg can utilize for decoding the AV1 video format in Liquidsoap. This example shows multiple potential decoding libraries, including hardware-accelerated options if available.
```liquidsoap
settings.decoder.ffmpeg.codecs.av1.available := ["libdav1d", "libaom-av1", "av1", "av1_cuvid"]
```
--------------------------------
### Stream Audio using HLS
Source: https://www.liquidsoap.info/doc-2.3.1/quick_start
Streams audio using the HLS protocol to a specified directory. Supports AAC encoding via FFmpeg. The output directory will contain all necessary files for an HLS stream, which can then be served over HTTP.
```liquidsoap
liquidsoap \
'output.file.hls(
"/path/to/hls/directory",
[("aac",
%ffmpeg(
format="mpegts",
%audio(codec="aac", b="128k")
))],
mksafe(playlist("playlist.m3u")))'
```
--------------------------------
### Set Up Multiple Genre-Specific Icecast Outputs
Source: https://www.liquidsoap.info/doc-2.3.1/radiopi
Provides example configurations for setting up various genre-specific radio channels using the `mkoutput` function. Each call configures a unique mount point, source, display name, and genre for an Icecast stream.
```liquidsoap
mkoutput(
"jazz",
jazz,
"RadioPi - Canal Jazz",
"jazz"
)
mkoutput(
"discoqueen",
discoqueen,
"RadioPi - Canal DiscoQueen",
"discoqueen"
)
mkoutput(
"classique",
classique,
"RadioPi - Canal Classique",
"classique"
)
mkoutput(
"That70Sound",
That70Sound,
"RadioPi - Canal That70Sound",
"That70Sound"
)
mkoutput(
"metal",
metal,
"RadioPi - Canal Metal",
"metal"
)
mkoutput(
"reggae",
reggae,
"RadioPi - Canal Reggae",
"reggae"
)
mkoutput(
"Rock",
Rock,
"RadioPi - Canal Rock",
"Rock"
)
```
--------------------------------
### Crossfade Playlist with Normalization
Source: https://www.liquidsoap.info/doc-2.3.1/quick_start
Plays a playlist with smart cross-fading between tracks and also normalizes the volume. This provides a smoother listening experience with consistent audio levels.
```liquidsoap
# ... same, but also add smart cross-fading
liquidsoap 'output(crossfade(
normalize(playlist("playlist_file"))))'
```
--------------------------------
### Middleware Registration
Source: https://www.liquidsoap.info/doc-2.3.1/harbor_http
Demonstrates how to register middleware functions with the Harbor HTTP server, using CORS as an example.
```APIDOC
## POST /middleware/register
### Description
Registers middleware functions to be executed for incoming HTTP requests. Middleware can modify requests or responses and can be chained.
### Method
POST
### Endpoint
`/middleware/register`
### Parameters
#### Query Parameters
- **middleware** (function) - Required - The middleware function to register. Examples include `harbor.http.middleware.cors`.
### Request Example
```lua
# Enable CORS middleware for requests originating from example.com
harbor.http.middleware.register(harbor.http.middleware.cors(origin="example.com"))
```
### Response
#### Success Response (200)
- **None** - Middleware registration is typically a side effect.
#### Response Example
(No direct response, but subsequent requests will be affected by the registered middleware.)
```
--------------------------------
### Normalize Playlist Volume
Source: https://www.liquidsoap.info/doc-2.3.1/quick_start
Plays a playlist while normalizing the audio volume. This ensures consistent loudness across all tracks in the playlist.
```liquidsoap
# Listen to your playlist, but normalize the volume
liquidsoap 'output(normalize(playlist("playlist_file")))'
```
--------------------------------
### Control Script Startup Behavior
Source: https://www.liquidsoap.info/doc-2.3.1/settings
Options to control Liquidsoap's startup behavior, such as forcing a start without active sources, dumping an initialization trace, or running OCaml memory compaction.
```liquidsoap
settings.init.force_start := false
settings.init.trace := false
settings.init.compact_before_start := false
```
--------------------------------
### Example: Available Codecs for ASV2 Decoding
Source: https://www.liquidsoap.info/doc-2.3.1/settings
Configures the available codecs for decoding the ASV2 format using FFmpeg in Liquidsoap. This specific configuration indicates that only 'asv2' is available for this format.
```liquidsoap
settings.decoder.ffmpeg.codecs.asv2.available := ["asv2"]
```
--------------------------------
### Liquidsoap labeled arguments type and application
Source: https://www.liquidsoap.info/doc-2.3.1/language
Shows the type signature for functions with labeled arguments and how to call them by explicitly naming the arguments. This example uses the 'samplerate' function with labeled arguments.
```liquidsoap
(samples : float, duration : float) -> float
```
```liquidsoap
samplerate(samples=110250., duration=2.5)
```
```liquidsoap
samplerate(duration=2.5, samples=110250.)
```
--------------------------------
### Transcode audio streams with FFmpeg
Source: https://www.liquidsoap.info/doc-2.3.1/cookbook
Transcodes input audio streams to different formats, bitrates, and sample rates using FFmpeg. This example demonstrates transcoding to MP3 at 32kbps and 128kbps, and outputting via Icecast.
```liquidsoap
# Input the stream from an Icecast server or any other source
url = "https://icecast.radiofrance.fr/fip-hifi.aac"
input = mksafe(input.http(url))
# First transcoder: mp3 32 kbps. We also degrade the samplerate, and encode in
# mono Accordingly, a mono conversion is performed on the input stream
output.icecast(
%mp3(bitrate=32, samplerate=22050, stereo=false),
mount="/your-stream-32.mp3",
host="streaming.example.com", port=8000, password="xxx",
mean(input))
# Second transcoder: mp3 128 kbps using %ffmpeg
output.icecast(
%ffmpeg(format="mp3", %audio(codec="libmp3lame", b="128k")),
mount="/your-stream-128.mp3",
host="streaming.example.com", port=8000, password="xxx",
input)
```
--------------------------------
### Compile Liquidsoap using Dune
Source: https://www.liquidsoap.info/doc-2.3.1/build
This command compiles the Liquidsoap project using the dune build system. Ensure all dependencies are installed before running. If errors occur, dependency updates might be necessary.
```bash
dune build
```
--------------------------------
### MP3 Encoding with libmp3lame and Video Copy
Source: https://www.liquidsoap.info/doc-2.3.1/ffmpeg_encoder
This example demonstrates encoding audio to MP3 using libmp3lame while copying the video stream without re-encoding. This is efficient for preserving video quality and reducing CPU load.
```liquidsoap
%ffmpeg(
format="mp3",
%audio(codec="libmp3lame"),
%video.copy
)
```
--------------------------------
### Configure and Stream Basic Radio with Liquidsoap
Source: https://www.liquidsoap.info/doc-2.3.1/quick_start
This Liquidsoap script sets up a simple radio station. It plays music from a playlist, intersperses jingles randomly, and includes a default track for security. The final output is an Ogg Vorbis stream sent to an Icecast server. Dependencies include Liquidsoap and an Icecast server.
```liquidsoap
#!/usr/bin/liquidsoap
# Log dir
log.file.path.set("/tmp/basic-radio.log")
# Music
myplaylist = playlist("~/radio/music.m3u")
# Some jingles
jingles = playlist("~/radio/jingles.m3u")
# If something goes wrong, we'll play this
security = single("~/radio/sounds/default.ogg")
# Start building the feed with music
radio = myplaylist
# Now add some jingles
radio = random(weights=[1, 4], [jingles, radio])
# And finally the security
radio = fallback(track_sensitive=false, [radio, security])
# Stream it out
output.icecast(
%vorbis,
host="localhost",
port=8000,
password="hackme",
mount="basic-radio.ogg",
radio
)
```
--------------------------------
### Execute Liquidsoap Script
Source: https://www.liquidsoap.info/doc-2.3.1/build
This command executes the liquidsoap script, which builds the latest code and runs it immediately. It simulates running the installed liquidsoap binary and can be used with command-line arguments like '-h output.ao'.
```bash
./liquidsoap -h output.ao
```
--------------------------------
### Get Function Help in Liquidsoap
Source: https://www.liquidsoap.info/doc-2.3.1/help
Access detailed documentation for specific Liquidsoap functions directly from the command line. This is useful for understanding function parameters, types, and available methods. The output format is a Liquidsoap script snippet.
```bash
$ liquidsoap -h sine
Generate a sine wave.
Type: (?id : string?, ?amplitude : {float}, ?duration : float,
?{float}) -> source(audio=internal('a),
video=internal('b),
midi=internal('c))
Category: Source / Input
Parameters:
* id : string? (default: null)
Force the value of the source ID.
* amplitude : {float} (default: 1.)
Maximal value of the waveform.
* duration : float (default: -1.)
Duration in seconds (negative means infinite).
* (unlabeled) : {float} (default: 440.)
Frequency of the sine.
Methods:
* fallible : bool
Indicate if a source may fail, i.e. may not be ready to stream.
* id : () -> string
Identifier of the source.
* is_active : () -> bool
`true` if the source is active, i.e. it is continuously animated by its
own clock whenever it is ready. Typically, `true` for outputs and
sources such as `input.http`.
* is_ready : () -> bool
Indicate if a source is ready to stream. This does not mean that the
source is currently streaming, just that its resources are all properly
initialized.
* is_up : () -> bool
Indicate that the source can be asked to produce some data at any time.
This is `true` when the source is currently being used or if it could be
used at any time, typically inside a `switch` or `fallback`.
* on_leave : ((() -> unit)) -> unit
Register a function to be called when source is not used anymore by
another source.
* on_metadata : ((([string * string]) -> unit)) -> unit
Call a given handler on metadata packets.
* on_shutdown : ((() -> unit)) -> unit
Register a function to be called when source shuts down.
* on_track : ((([string * string]) -> unit)) -> unit
Call a given handler on new tracks.
* remaining : () -> float
Estimation of remaining time in the current track.
* seek : (float) -> float
Seek forward, in seconds (returns the amount of time effectively
seeked).
* self_sync : () -> bool
Is the source currently controlling its own real-time loop.
* skip : () -> unit
Skip to the next track.
* time : () -> float
Get a source's time, based on its assigned clock.
```
--------------------------------
### Handling Fallible Sources with Fallback in Liquidsoap
Source: https://www.liquidsoap.info/doc-2.3.1/quick_start
Demonstrates how to use the `fallback` function in Liquidsoap to provide a default stream when a primary, fallible source becomes unavailable. This ensures continuous playback by switching to a predefined 'security' source, such as a silence file or a pre-recorded track.
```liquidsoap
fallback([your_fallible_source_here, single("failure.ogg")])
```
--------------------------------
### HTTPS GET Request
Source: https://www.liquidsoap.info/doc-2.3.1/reference-deprecated
Performs an HTTP GET request. This is a deprecated function, use `http.get` instead.
```APIDOC
## GET /resource
### Description
Sends an HTTP GET request to the specified URL and returns the response body. Note: This function is deprecated; use `http.get` for new implementations.
### Method
GET
### Endpoint
`/resource`
### Parameters
#### Query Parameters
- **url** (string) - Required - The URL to send the GET request to.
- **headers** ([string * string]?) - Optional - A list of HTTP headers to include in the request.
- **http_version** (string?) - Optional - The HTTP protocol version to use (e.g., "1.1", "2").
- **redirect** (bool?) - Optional - Whether to follow redirects (defaults to true).
- **timeout** (float?) - Optional - The request timeout in seconds (defaults to 10.0).
- **normalize_url** (bool?) - Optional - Whether to normalize the URL before sending.
### Response
#### Success Response (200)
- **body** (string) - The response body from the server.
- **headers** ([string * string]) - The response headers.
- **http_version** (string) - The HTTP protocol version used for the response.
- **status_code** (int) - The HTTP status code of the response.
- **status_message** (string) - The HTTP status message of the response.
#### Response Example
```json
{
"body": "
Hello, World!
",
"headers": [
["Content-Type", "text/html"],
["Content-Length", "40"]
],
"http_version": "1.1",
"status_code": 200,
"status_message": "OK"
}
```
```
--------------------------------
### Using ReplayGain Protocol with Annotations in Liquidsoap
Source: https://www.liquidsoap.info/doc-2.3.1/replay_gain
This example illustrates how to use the `replaygain:` protocol in Liquidsoap, combined with other protocols like `annotate:`. It shows how to prefix a file URI with `replaygain:` to trigger ReplayGain retrieval or computation on a per-file basis, and how to chain protocols for advanced metadata manipulation.
```liquidsoap
annotate:foo="bar":replaygain:/path/to/file.mp3
```
--------------------------------
### Configure and Use Input.harbor for Live Streams (Liquidsoap)
Source: https://www.liquidsoap.info/doc-2.3.1/cookbook
This example shows how to set up Liquidsoap to receive live streams via the input.harbor operator. It configures server binding addresses, defines an emergency fallback source, a playlist, and the main live input. The 'radio' source then uses a fallback mechanism to prioritize the live stream over the playlist and emergency file. Requires Icecast compatibility.
```liquidsoap
# Serveur settings
settings.harbor.bind_addrs := ["0.0.0.0"]
# An emergency file
emergency = single("/path/to/emergency/single.ogg")
# A playlist
playlist = playlist("/path/to/playlist")
# A live source
live = input.harbor("live",port=8080,password="hackme")
# fallback
radio = fallback(track_sensitive=false, [live, playlist, emergency])
# output it
output.icecast(
%vorbis,
mount="test",
host="host",
radio)
```
--------------------------------
### MP3 Encoding Example with libshine
Source: https://www.liquidsoap.info/doc-2.3.1/ffmpeg_encoder
This example shows how to encode audio to MP3 format using the libshine encoder at a sample rate of 48000kHz. The format is set to 'mp3'.
```liquidsoap
%ffmpeg(format="mp3", %audio(codec="libshine", samplerate=48000))
```
--------------------------------
### Liquidsoap ALSA Output Configuration for Low Latency
Source: https://www.liquidsoap.info/doc-2.3.1/cookbook
This example shows a basic Liquidsoap configuration for ALSA output, aiming for minimal delay, which is useful for live broadcasting. It includes conditional definitions for ALSA input and output to ensure compatibility and provides a placeholder for setting the correct frame size, which is hardware-dependent.
```liquidsoap
%ifndef input.alsa
let input.alsa = blank
%endif
%ifndef output.alsa
let output.alsa = output.dummy
%endif
# BEGIN
# Set correct frame size:
# This makes it possible to set any audio frame size.
```
--------------------------------
### Liquidsoap Output File Example
Source: https://www.liquidsoap.info/doc-2.3.1/encoding_formats
This example demonstrates how to use an MP3 encoder with the output.file function in Liquidsoap. It specifies the MP3 format and the output file path, linking it to a playlist source.
```liquidsoap
output.file(%mp3,"/tmp/foo.mp3",playlist("~/audio"))
```
--------------------------------
### Call Function with Optional Argument (Liquidscript)
Source: https://www.liquidsoap.info/doc-2.3.1/language
Shows how to call the `samplerate` function. The first example calls it without specifying `duration`, using the default value. The second example explicitly provides a `duration` value, overriding the default.
```liquidscript
samplerate(samples=110250.)
```
```liquidscript
samplerate(samples=132300., duration=3.)
```
--------------------------------
### Start Liquidsoap Interactive Variables Web Interface
Source: https://www.liquidsoap.info/doc-2.3.1/server
Starts a web server that provides an interface for easily changing the values of defined interactive variables. This enhances usability for dynamic parameter control.
```liquidsoap
interactive.harbor()
```
--------------------------------
### in
Source: https://www.liquidsoap.info/doc-2.3.1/reference-deprecated
Deprecated function for creating input sources. Use `input` instead.
```APIDOC
## in
### Description
Deprecated: use `input` instead.
### Method
(Not specified)
### Endpoint
(Not specified)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **id** (string?) - Optional identifier for the source, defaults to null.
- **start** (bool?) - Whether to start the source immediately, defaults to true.
- **on_start** (() -> unit?) - Function to call when the source starts.
- **on_stop** (() -> unit?) - Function to call when the source stops.
- **fallible** (bool?) - Whether the source can fail, defaults to false.
### Request Example
```json
{
"id": "my_input",
"start": true,
"fallible": false
}
```
### Response
#### Success Response (200)
- **source(audio=pcm('A))** - The created input source.
#### Response Example
```json
{
"source_id": "my_input"
}
```
### Methods
- `buffered` (type: `() -> [string * float]`) - Length of buffered data.
- `clock` (type: `clock`) - The source’s clock.
- `duration` (type: `() -> float`) - Estimation of the duration of the current track.
- `elapsed` (type: `() -> float`) - Elapsed time in the current track.
- `fallible` (type: `bool`) - Indicates if a source may fail.
- `id` (type: `() -> string`) - Identifier of the source.
- `is_active` (type: `() -> bool`) - Returns `true` if the source is active.
- `is_ready` (type: `() -> bool`) - Indicates if a source is ready to stream.
- `is_started` (type: `() -> bool`) - Returns `true` if the output or source is started.
- `is_up` (type: `() -> bool`) - Indicates that the source can be asked to produce data.
- `last_metadata` (type: `() -> [string * string]?`) - Returns the last metadata from the source.
- `log` (type: `{level : (() -> int?).{set : (int) -> unit}}`) - Get or set the source’s log level.
- `on_metadata` (type: `((([string * string]) -> unit)) -> unit`) - Calls a handler on metadata packets.
- `on_shutdown` (type: `((() -> unit)) -> unit`) - Registers a function to be called when the source shuts down.
- `on_track` (type: `((([string * string]) -> unit)) -> unit`) - Calls a handler on new tracks.
- `on_wake_up` (type: `((() -> unit)) -> unit`) - Registers a function to be called after the source is asked to get ready.
- `register_command` (type: `(?usage : string?, description : string, string, ((string) -> string)) -> unit`) - Registers a server command for this source.
- `remaining` (type: `() -> float`) - Estimation of remaining time in the current track.
- `reset_last_metadata_on_track` (type: `(() -> bool).{set : (bool) -> unit}`) - Resets `last_metadata` on each new track.
- `seek` (type: `(float) -> float`) - Seeks forward in seconds.
- `self_sync` (type: `() -> bool`) - Indicates if the source is controlling its own real-time loop.
- `shutdown` (type: `() -> unit`) - Shuts down the output or source.
- `skip` (type: `() -> unit`) - Skips to the next track.
- `start` (type: `() -> unit`) - Asks the source or output to start.
- `stop` (type: `() -> unit`) - Asks the source or output to stop.
- `time` (type: `() -> float`) - Gets the source’s time.
```
--------------------------------
### Managing Liquidsoap Dependencies with opam
Source: https://www.liquidsoap.info/doc-2.3.1/build
Shows how to pin the latest Liquidsoap code and then query opam to list and understand its dependencies. This process helps identify required, optional, and system-specific packages.
```shell
opam pin -ny git+https://github.com/savonet/liquidsoap
```
```shell
opam info liquidsoap
opam info liquidsoap-lang
```
```shell
opam info soundtouch
```
--------------------------------
### Add Jingle at Hour Start (Liquidsoap)
Source: https://www.liquidsoap.info/doc-2.3.1/cookbook
Adds a jingle to the normal audio stream at the beginning of every hour. This is achieved by using the `add` operator with the normal source and a switch that selects the jingle at the start of the hour. Dependencies: None.
```liquidsoap
s = add([normal, switch([({0m}, jingle)])])
```
--------------------------------
### Start Liquidsoap Telnet Server Emulation via Web Interface
Source: https://www.liquidsoap.info/doc-2.3.1/server
Starts a web interface that emulates the telnet server, making it accessible via a web browser. This provides a user-friendly way to interact with the Liquidsoap server commands.
```liquidsoap
server.harbor()
```
--------------------------------
### Pinning OCaml Packages with opam
Source: https://www.liquidsoap.info/doc-2.3.1/build
Demonstrates how to use `opam pin` to manage package versions, either from a local directory or a Git URL. This is useful for updating dependencies to their latest versions before they are officially published.
```shell
git clone https://github.com/savonet/ocaml-metadata.git
cd ocaml-metadata
opam pin -ny .
```
```shell
opam pin -ny git+https://github.com/savonet/ocaml-cry
```
--------------------------------
### Update Source Metadata via HTTP GET Request in Liquidsoap
Source: https://www.liquidsoap.info/doc-2.3.1/harbor_http
Provides a Liquidsoap HTTP handler to update a source's metadata using GET parameters. It parses metadata from the request query and uses `insert_metadata` to apply changes to the source.
```liquidsoap
# s = some source
# Create a source equipped with a `insert_metadata` method:
s = insert_metadata(s)
# The handler
def set_meta(request, response) =
# Filter out unusual metadata
meta = metadata.export(request.query)
# Grab the returned message
ret =
if
meta != []
then
s.insert_metadata(meta)
"OK!"
else
"No metadata to add!"
end
response.html("#{ret}")
end
# Register handler on port 700
harbor.http.register(port=7000, method="GET", "/setmeta", set_meta)
```
--------------------------------
### Applying ReplayGain to a Queued Playlist in Liquidsoap
Source: https://www.liquidsoap.info/doc-2.3.1/beets
Demonstrates how to wrap a Liquidsoap request queue with an `amplify` operator to benefit from ReplayGain metadata. This ensures consistent volume for tracks added via the Beets protocol.
```liquidsoap
userrequested = amplify(override="replaygain_track_gain", 1.0,
request.queue(id="userrequested")
)
```
--------------------------------
### get_mime
Source: https://www.liquidsoap.info/doc-2.3.1/reference-deprecated
Deprecated function for getting MIME type. Use `file.mime` instead.
```APIDOC
## get_mime
### Description
Deprecated: use `file.mime`
### Method
N/A (Function signature)
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
N/A
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### Record and Module Pattern Matching in Liquidsoap
Source: https://www.liquidsoap.info/doc-2.3.1/language
Demonstrates pattern matching for records and modules, including capturing fields, using spreads for remaining fields, and handling optional fields with `?`.
```liquidsoap
# Record capture
let {foo, bar} = {foo = 123, bar = "baz", gni = true}
# foo = 123, bar = "baz"
# Record capture with spread
let {foo, bar, ...x} = {foo = 123, bar = "baz", gni = true}
# foo = 123, bar = "baz", x = {gni = true}
# Module capture
let v.{foo, bar} = "aabbcc".{foo = 123, bar = "baz", gni = true}
# v = "aabbcc", foo = 123, bar = "baz"
# Module capture with ignored value
let _.{foo, bar} = "aabbcc".{foo = 123, bar = "baz", gni = true}
# foo = 123, bar = "baz"
# Record capture with sub-patterns. Same works for module!
let {foo = [x, y, z], gni} = {foo = [1, 2, 3], gni = "baz"}
# foo = [1, 2, 3], x = 1, y = 2, z = 3, gni = "baz"
# Record capture with optional methods:
let { foo? } = ()
# foo = null()
let { foo? } = { foo = 123 }
# foo = 123
```
--------------------------------
### Liquidsoap Server Seek Function Example
Source: https://www.liquidsoap.info/doc-2.3.1/seek
This example demonstrates how to create a server function in Liquidsoap to seek within a playlist source. It registers a 'seek' command that accepts a duration in seconds and uses `source.seek` to adjust the playback position. The function logs the seek operation and returns the actual duration seeked.
```liquidsoap
# A playlist source
s = playlist("/path/to/music")
# The server seeking function
def seek(t) =
t = float_of_string(default=0., t)
log(
"Seeking #{t} sec"
)
ret = source.seek(s, t)
"Seeked #{ret} seconds."
end
# Register the function
server.register(
namespace=source.id(s),
description=
"Seek to a relative position in source #{source.id(s)}",
usage=
"seek ",
"seek",
seek
)
```
--------------------------------
### Create a playlist source
Source: https://www.liquidsoap.info/doc-2.3.1/cookbook
Creates a source that plays a playlist of URIs. Playlists can be shuffled, played in order, reloaded periodically, and can be sourced from local files or remote URLs.
```liquidsoap
# Shuffle, play every URI, start over.
s1 = playlist("/my/playlist.txt")
# Do not randomize
s2 = playlist(mode="normal", "/my/pl.m3u")
# The playlist can come from any URI, can be reloaded every 10 minutes.
s3 = playlist(reload=600, "http://my/playlist.txt")
```
--------------------------------
### Single-line Comments in Liquidsoap
Source: https://www.liquidsoap.info/doc-2.3.1/language
Illustrates the syntax for single-line comments in Liquidsoap, which start with the '#' character and extend to the end of the line. This is used for inline explanations.
```liquidsoap
def f(x) = # This is a single line comment.
123
end
```
--------------------------------
### FFmpeg Encoder Full Syntax Example
Source: https://www.liquidsoap.info/doc-2.3.1/ffmpeg_encoder
This snippet outlines the complete syntax for the FFmpeg encoder in Liquidsoap, showing the structure for specifying format, audio, video, and generic options. It includes placeholders for various codec and option configurations.
```liquidsoap
%ffmpeg(
format=,
# Audio section
%audio(codec=, =, ...),
# Or:
%audio.raw(codec=, =, ...),
# Or:
%audio.copy(