Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,7 @@ src/.idea

# debian build artifacts
/debian
/obj-*
/obj-*
# test output
test-output
__pycache__
80 changes: 80 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Notes for AI agents

CasparCG Server: a C++20 playout server. Sources are under `src/`, which is also the CMake root.

| Directory | What's in it |
| ----------------- | -------------------------------------------------------------------- |
| `src/common` | Shared utilities: logging, executors, environment/config |
| `src/core` | Channels, stage/layer, mixer, frame and producer/consumer interfaces |
| `src/accelerator` | Image mixer backends: `ogl` (OpenGL) and `vulkan` |
| `src/modules/*` | Producers and consumers: ffmpeg, decklink, html, image, ... |
| `src/protocol` | AMCP and the TCP server |
| `src/shell` | `main()`, server setup, the default `casparcg.config` |
| `src/tests` | Tests |

## Building (Linux)

```sh
cmake -S src -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX=$PWD/build/staging
cmake --build build --parallel # add -DENABLE_HTML=OFF above if CEF isn't installed
cmake --install build
```

`cmake --build` alone does not update `build/staging`. Anything that runs the installed server,
including the tests, needs `cmake --install` after every build, or it silently runs the previous
binary. See `BUILDING.md` for dependencies, Windows and the remaining build options.

## Code style

- Format C++ with the repo's `.clang-format`.
- Write code that reads like the code around it: naming, comment density, idioms.
- Keep comments short. Explain what isn't obvious.

## Tests

End-to-end tests (`src/tests/e2e/`, pytest) start the installed server on a free port with a config
of their own and talk AMCP to it. They need pytest, and are registered with CTest when
`-DBUILD_TESTING=ON` and the Python CMake finds has it:

```sh
python3 -m venv build/venv && build/venv/bin/pip install pytest
cmake -S src -B build -DBUILD_TESTING=ON -DPython3_EXECUTABLE=$PWD/build/venv/bin/python \
-DCMAKE_INSTALL_PREFIX=$PWD/build/staging
cmake --build build --parallel && cmake --install build
ctest --test-dir build -L e2e --output-on-failure
ctest --test-dir build -R e2e.lifecycle # one file; -LE accelerator skips the ones needing a GPU
# one test, directly (ctest sets CASPAR_BINARY itself):
cd build/tests && CASPAR_BINARY=$PWD/../staging/bin/casparcg \
../venv/bin/python -m pytest ../../src/tests/e2e/test_lifecycle.py -k kill
```

CTest runs `<CMAKE_INSTALL_PREFIX>/bin/casparcg`. Channels need an accelerator (a GPU, or Mesa's
drivers); `CASPAR_TEST_ACCELERATOR=vulkan|opengl` picks one. `src/tests/README.md` shows how to write
tests with the fixtures.

- Fixtures (`e2e/conftest.py`): `server` (one 720p5000 channel), `make_server(channels=(...),
accelerator=...)` and `output_dir`. `Server` (`e2e/caspar.py`) has `command("VERSION")`,
`kill()`, `wait_exit()` and `log()`.
- Every server is checked when its test ends: stopped with `KILL` if still running, it must exit
with code 0 (or the test's `server.expected_exit`) and log no `error` or `fatal` lines.
- A new test file `e2e/test_<name>.py` must be registered in `src/tests/CMakeLists.txt` with
`e2e_test(<name> LABELS <label>...)`, which makes it the CTest test `e2e.<name>`. Every file gets
the label `e2e`; add `accelerator` if it starts channels.
- A test's server folder (config, `server.log`, and `stacks.txt` if it hung) is kept under
`test-output/e2e/<file>/<test>/`. When a test fails, read `server.log` there.

Rules:

- **Commit the tests you write.** A test written to check a fix or a feature belongs in the repo,
not in a scratch folder or a one-off script.
- **Use the fixtures** instead of starting servers yourself; extend them if something is missing.
- **Never delete a test, disable it or loosen a check to make it pass** without saying so, and why,
in the commit message.
- Don't commit a test that fails, or is skipped, because of a bug you aren't fixing in the same
change. Describe the bug to the person you're working with instead; bugs are tracked as GitHub
issues, and only a person files them.

## Commits

Small, focused commits that each build. Conventional prefixes (`feat(ffmpeg):`, `fix(core):`,
`test(e2e):`, `build:`, `docs:`) are used in the history.
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@AGENTS.md
6 changes: 6 additions & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ set(CASPARCG_DOWNLOAD_MIRROR https://github.com/CasparCG/dependencies/releases/d
set(CASPARCG_DOWNLOAD_CACHE ${CMAKE_CURRENT_BINARY_DIR}/external CACHE STRING "Download cache directory for cmake ExternalProjects")

option(ENABLE_HTML "Enable HTML module, require CEF" ON)
option(BUILD_TESTING "Register the tests (run them with ctest)" OFF)

set(DIAG_FONT_PATH "LiberationMono-Regular.ttf" CACHE STRING
"Path to font that will be used to load diag font at runtime. By default
Expand Down Expand Up @@ -71,3 +72,8 @@ add_subdirectory(core)
add_subdirectory(modules)
add_subdirectory(protocol)
add_subdirectory(shell)

if (BUILD_TESTING)
enable_testing()
add_subdirectory(tests)
endif ()
56 changes: 42 additions & 14 deletions src/protocol/util/AsyncEventServer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#include <algorithm>
#include <array>
#include <functional>
#include <future>
#include <memory>
#include <set>
#include <string>
Expand All @@ -41,6 +42,25 @@ namespace caspar { namespace IO {

class connection;

namespace {

// Without throwing: the endpoints are gone once the peer disconnects or the socket is closed.
std::wstring local_port(const tcp::socket& socket)
{
boost::system::error_code ec;
auto endpoint = socket.local_endpoint(ec);
return ec ? L"no-port" : std::to_wstring(endpoint.port());
}

std::wstring remote_address(const tcp::socket& socket)
{
boost::system::error_code ec;
auto endpoint = socket.remote_endpoint(ec);
return ec ? L"no-address" : u16(endpoint.address().to_string());
}

} // namespace

using connection_set = std::set<spl::shared_ptr<connection>>;

class connection : public spl::enable_shared_from_this<connection>
Expand All @@ -51,6 +71,7 @@ class connection : public spl::enable_shared_from_this<connection>
const spl::shared_ptr<tcp::socket> socket_;
std::shared_ptr<boost::asio::io_context> io_context_;
const std::wstring listen_port_;
const std::wstring remote_address_;
const spl::shared_ptr<connection_set> connection_set_;
protocol_strategy_factory<char>::ptr protocol_factory_;
std::shared_ptr<protocol_strategy<char>> protocol_;
Expand Down Expand Up @@ -134,10 +155,7 @@ class connection : public spl::enable_shared_from_this<connection>

std::wstring address() const { return u16(socket_->local_endpoint().address().to_string()); }

std::wstring ipv4_address() const
{
return socket_->is_open() ? u16(socket_->remote_endpoint().address().to_string()) : L"no-address";
}
std::wstring ipv4_address() const { return remote_address_; }

void send(std::string&& data)
{
Expand Down Expand Up @@ -203,7 +221,8 @@ class connection : public spl::enable_shared_from_this<connection>
const spl::shared_ptr<connection_set>& connection_set)
: socket_(socket)
, io_context_(io_context)
, listen_port_(socket_->is_open() ? std::to_wstring(socket_->local_endpoint().port()) : L"no-port")
, listen_port_(local_port(*socket_))
, remote_address_(remote_address(*socket_))
, connection_set_(connection_set)
, protocol_factory_(protocol_factory)
, is_writing_(false)
Expand Down Expand Up @@ -274,6 +293,7 @@ struct AsyncEventServer::implementation : public spl::enable_shared_from_this<im
{
std::shared_ptr<boost::asio::io_context> io_context_;
tcp::acceptor acceptor_;
const std::wstring port_;
protocol_strategy_factory<char>::ptr protocol_factory_;
spl::shared_ptr<connection_set> connection_set_;
std::vector<lifecycle_factory_t> lifecycle_factories_;
Expand Down Expand Up @@ -303,18 +323,29 @@ struct AsyncEventServer::implementation : public spl::enable_shared_from_this<im

return tcp::acceptor(*io_context_, endpoint);
}())
, port_(std::to_wstring(acceptor_.local_endpoint().port()))
, protocol_factory_(protocol)
{
}

void stop()
{
try {
acceptor_.cancel();
acceptor_.close();
} catch (...) {
CASPAR_LOG_CURRENT_EXCEPTION();
// The acceptor isn't thread-safe: close it on the thread that runs its handlers.
auto close = [this] {
boost::system::error_code ec;
acceptor_.cancel(ec);
acceptor_.close(ec);
};
if (io_context_->stopped()) {
close();
return;
}
std::promise<void> closed;
boost::asio::dispatch(*io_context_, [&] {
close();
closed.set_value();
});
closed.get_future().wait();
}

~implementation()
Expand Down Expand Up @@ -358,10 +389,7 @@ struct AsyncEventServer::implementation : public spl::enable_shared_from_this<im
start_accept();
}

std::wstring print() const
{
return L"async_event_server[:" + std::to_wstring(acceptor_.local_endpoint().port()) + L"]";
}
std::wstring print() const { return L"async_event_server[:" + port_ + L"]"; }

void add_client_lifecycle_object_factory(const lifecycle_factory_t& factory)
{
Expand Down
27 changes: 27 additions & 0 deletions src/tests/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# End-to-end tests: pytest files in e2e/, run against the installed server (cmake --install). One
# CTest test per file; run single tests with pytest directly (see AGENTS.md).
find_package(Python3 COMPONENTS Interpreter)
if (Python3_FOUND)
execute_process(COMMAND ${Python3_EXECUTABLE} -c "import pytest" RESULT_VARIABLE no_pytest OUTPUT_QUIET ERROR_QUIET)
endif ()
if (NOT Python3_FOUND OR no_pytest)
message(STATUS "pytest not found for ${Python3_EXECUTABLE}: end-to-end tests are not registered. "
"Install pytest, or point -DPython3_EXECUTABLE at a Python that has it.")
return()
endif ()

# e2e_test(<name> LABELS <label>...) registers e2e/test_<name>.py as the CTest test e2e.<name>. Every
# test file must be registered here. Label "accelerator" marks tests that start channels and so
# need an accelerator (a GPU, or Mesa's drivers).
function (e2e_test name)
cmake_parse_arguments(PARSE_ARGV 1 arg "" "" "LABELS")
add_test(NAME e2e.${name}
COMMAND ${Python3_EXECUTABLE} -m pytest -p no:cacheprovider -v ${CMAKE_CURRENT_SOURCE_DIR}/e2e/test_${name}.py
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
set_tests_properties(e2e.${name} PROPERTIES
LABELS "e2e;${arg_LABELS}"
TIMEOUT 900
ENVIRONMENT "CASPAR_BINARY=${CMAKE_INSTALL_PREFIX}/bin/${CASPARCG_BINARY_NAME}")
endfunction ()

e2e_test(lifecycle LABELS accelerator)
128 changes: 128 additions & 0 deletions src/tests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# Tests

## End-to-end tests

The tests in `e2e/` are pytest files. Each test starts the installed CasparCG server
(`cmake --install` output) with a config of its own, on a free port, and talks AMCP to it.
`AGENTS.md` at the repo root has the build and setup commands.

### Running

```sh
ctest --test-dir build -L e2e --output-on-failure # all of them
ctest --test-dir build -R e2e.lifecycle # one file
ctest --test-dir build -L e2e -LE accelerator # only the ones that don't need a GPU
```

To run single tests, or to use pytest options, run pytest directly. CTest sets `CASPAR_BINARY`;
set it yourself when you don't go through CTest:

```sh
cd build/tests && CASPAR_BINARY=$PWD/../staging/bin/casparcg \
../venv/bin/python -m pytest ../../src/tests/e2e/test_lifecycle.py -k kill
```

`CASPAR_TEST_ACCELERATOR=vulkan|opengl` picks the accelerator (default `auto`).
`CASPAR_TEST_OUTPUT` moves the output folder (default `./test-output`).

### Adding a test file

Write `e2e/test_<name>.py`, then register it in `CMakeLists.txt`:

```cmake
e2e_test(<name> LABELS accelerator)
```

It runs as the CTest test `e2e.<name>`. Every file gets the label `e2e`; add `accelerator` if its
tests start channels, since those need a GPU or Mesa's drivers.

### Fixtures

The fixtures are in `e2e/conftest.py` and the server class is in `e2e/caspar.py`.

#### `server`

A running server with one 720p5000 channel and no consumers.

```python
def test_version(server):
reply = server.command("VERSION")
assert reply.code == 201
assert reply.lines[0].startswith("2.")
```

`server.command()` opens a connection, sends one command and returns a `Reply`:

- `code`: the status code, e.g. `201`.
- `status`: the whole first line, e.g. `"201 VERSION OK"`.
- `lines`: the data lines after it. A `201` reply has one, and a `200` reply has all the lines up
to the empty line that ends it.

To send several commands on one connection, use `AmcpClient`:

```python
from caspar import AmcpClient

def test_two_commands(server):
with AmcpClient(server.port) as client:
assert client.send("VERSION").code == 201
assert client.send("INFO").code == 200
```

#### `make_server`

Starts servers with other settings. Call it once for each server you need:

```python
def test_two_channels(make_server):
server = make_server(channels=("1080i5000", "720p5000"))
...

def test_on_vulkan(make_server):
server = make_server(accelerator="vulkan")
...
```

The `server` fixture is `make_server()` with the defaults.

#### `output_dir`

The test's own folder, `test-output/e2e/<file>/<test>/`. It is emptied when the test starts and
kept afterwards. Each server gets a subfolder (`server0`, `server1`, ...) holding its config,
`server.log` and its `media`, `data` and `template` folders. Put a test's input files in
`server.folder / "media"`, and its own output files in `output_dir`.

### Checks when a test ends

Every server is checked when its test ends, so a test doesn't have to:

- A server that is still running is stopped with `KILL`.
- It must exit with code 0. A test that expects a different exit code sets
`server.expected_exit`.
- Its log must have no `error` or `fatal` lines.
- If it doesn't exit within 15 s, its threads' stacks are written to `stacks.txt` in its folder
and it is killed.

A test that shuts the server down itself waits for it to exit:

```python
def test_kill_shuts_down(server):
server.kill()
server.wait_exit()
```

`kill()` accepts the server closing the connection without a reply, because the server starts
shutting down while the KILL command runs and may close the connection before replying.
`server.log()` returns the server's output so far, read from its stdout (and copied to
`server.log`). After `wait_exit()` it holds everything:

```python
def test_logs_shutdown(server):
server.kill()
server.wait_exit()
assert "Executing command: KILL" in server.log()
```

While the server runs, a line may arrive after the reply to the command that logged it.

When a test fails, read `server.log` in its server folder.
Loading
Loading