Technical Manual

YASDE — Yet Another Samsung Dex Emulator
Independent project, not affiliated with, endorsed by or sponsored by Samsung. Samsung and Samsung DeX are trademarks of Samsung Electronics Co., Ltd.
Version2.1.0
DateNovember 2026
Chapter 1

Introduction

1.1 · What YASDE is

YASDE (Yet Another Samsung Dex Emulator) is a Linux program with a single window that is an emulated desktop: the apps of an Android 14+ phone run as windows inside it. This manual describes how it is built, for a developer who must change the code. It documents the code as it is today; where the code and the older design documents disagree, the code wins and the difference is listed in 1.5 “Known deviations from the design documents”.

The product has two halves. On the PC a program written in C17 (built with Meson) talks to the phone over wireless ADB, decodes the video the phone sends, plays its audio, and draws the desktop with GTK4. On the phone a small Java component, started with app_process, creates virtual displays, encodes them to H.264, captures audio, injects input and answers questions about the phone. Nothing is installed on the phone and nothing needs root.

i
Note. YASDE is an independent project, not affiliated with Samsung. “DeX” is a trademark of its owner and is used only to say which behaviour the desktop imitates.

The project's site is https://yasde.nicfio.it/. Questions and reports: yasde@nicfio.it.

1.2 · Principles

Four rules shape every design choice in the code. They come from the project instructions and are enforced by review, not by the compiler.

PrincipleWhat it means in the code
Nothing installed on the phoneThe component is a jar copied to /data/local/tmp/yasde-<8 hex digits>.jar at every start and deleted at the end. No APK, no package, no service registered with Android.
No rootThe component runs as the shell user (uid 2000), exactly like any command typed in adb shell. It refuses connections from any other uid (Pari, see 6.4 “Who may talk to the component”).
Plain Android APIs onlyPublic APIs first. Hidden APIs are reached by reflection and gathered in one class per folder (Nascoste, NascosteVideo, NascosteAudio, NascostePannello ...), each with a check at start-up that names the ones missing on this phone. No vendor-specific code: a workaround is triggered by a measured symptom, never by the manufacturer's name.
Every change has its undoWhatever the component changes on the phone (screen timeout, media volume, panel power, minimum refresh rate) registers its undo command with the guardian Custode before the change is made (6.5 “The guardian and the restore list”).
Table 1.1 — The four principles

1.3 · Requirements

What is needed to build and run YASDE, as declared by the meson.build files.

WhereRequirement
PC, language and buildC17, warnings as errors, Meson; tests run under AddressSanitizer. Version 2.1.0 (meson.build at the root).
PC, librariesOpenSSL (TLS 1.3, RSA, AES-GCM, HKDF, SPAKE2 arithmetic), FFmpeg (libavcodec, libavformat, libavutil, libswscale), Vulkan headers and loader (to detect hardware decoding), Opus, PipeWire (libpipewire-0.3), GTK 4.14 or newer for the shell, pthreads.
PC, hardwareA GPU with VA-API H.264 decoding (first choice) or Vulkan Video; the software decoder is the last resort.
PhoneAndroid 14 or newer, wireless debugging turned on and the PC paired with it (5.2 “Pairing with the six-digit code”).
Phone jarJava source level 8 against android.jar (no lambdas, no method references), converted with d8 at --min-api 34 by telefono/costruisci.sh.
Table 1.2 — Requirements

1.4 · Conventions and names

Code, comments and internal documents are written in Italian, so identifiers in this manual are Italian too. The first time a recurring name appears its meaning is given in brackets; the table lists the ones you meet most.

NameMeaningWhere
Custodethe guardian: the process that undoes the phone changes if the service diestelefono/base
Registrothe registry where the pieces of the component register themselvestelefono/contratto
Parithe peers: the check on who connects to the sockettelefono/base
Smistatorethe dispatcher of command-channel messagestelefono/base
Sessioneone video session (virtual display, encoder and app)telefono/video
Pannellothe physical panel (phone screen) managertelefono/pannello
TieniSveglio“keep awake”: the wake locktelefono/pannello
collegamentothe link: the state machine that keeps one phone connectedsrc/collegamento
componentethe component: PC side of the protocolsrc/componente
scopertadiscovery of phones with mDNSsrc/scoperta
abbinamentopairing with the six-digit codesrc/abbinamento
datiphone data: apps, state, notifications, search, clipboardsrc/dati
PhErroreerror record: a sentence in Italian saying what was being donesrc/comune/errore.h
Table 1.3 — Italian names that recur

Conventions of the C code: every public name starts with ph_ or Ph (the prefix is historical and was kept); functions return 0 or -1 (pointers return NULL on error) and fill a PhErrore; no function calls exit() for a failure that depends on the phone or the network. The full list of code conventions is in chapter 18.

1.5 · Known deviations from the design documents

The table lists the places where this manual states that the code does not do what the design documents say. Each one is detailed in the chapter named in the last column.

Design document saysCode doesChapter
The shell draws with Vulkan.The shell draws with GTK4. Vulkan is used only to detect and drive hardware H.264 decoding.see chapter 8
Two guardians (connection and service).One guardian, Custodesee chapter 6
Audio and video are synchronised.No synchronisation is active: video frames are shown as they arrive. ph_audio_tempo_telefono_us exists but nothing outside src/audio calls it.see chapter 9
The protocol defines VIDEO_EVENTO kind 3 (size changed).The phone code never sends it; sizes change only through the resize request and the new configuration packet.see chapter 8
Hardware decoding hands frames to the screen without copies.Only with VA-API, the first automatic choice. Vulkan is the fallback where VA-API is missing: in that case ph_esporta copies the frame to memory (PH_ESPORTA_RIPIEGO).see chapter 8
Audio capture starts 5 s after the drawer mirror opens.Audio starts 5 s after the first video stream of the session; there is no mirror at start-up (sv_audio.c).see chapter 9
The panel goes off again after the inactivity time chosen by the user.Only the first input from the PC turns it off again; there is no inactivity timer on the PC.see chapter 10
The panel turns on when the last window closes.Closing the last window does not turn the panel on while YASDE is connected.see chapter 10
The mouse is one finger.True for the left button only. The right and middle buttons pressed on the content of an app window reach the phone as real mouse buttons (context menu, open in a new tab), as DeX does.see chapter 10
Minimum refresh rate set to 60 Hz when the panel goes off.Set to the highest rate with the same resolution (capped by the user's peak rate) only if the measured rate is lower.see chapter 10
Table 1.4 — Where code and design documents differ
!
Warning. This manual was written from the sources. Behaviour that has not been tried on a real phone is said so in the text; the first launch on a real phone is the proof.
Chapter 2

Architecture

2.1 · The two halves

YASDE is one Linux process on the PC plus one short-lived Java process on the phone. They talk over a single ADB connection (TCP, TLS 1.3) opened by the PC; every logical channel of the protocol is an ADB channel multiplexed on it.

GUI process (GTK4 shell)shellsrc/shell/*: desktop, windows, bar, launcherossatura (skeleton)real services: sv_*.cfinestre, config, trasferimenti, meteologic around the shellPC engine (C, no GUI)linkstate machinecomponenteprotocol, video, inputdatiapps, state, searchaudioOpus + PipeWirevideoFFmpegfilesync:scopertamDNSabbinamentoSPAKE2 pairingadb: TLS client, channels, shell v2OpenSSL, one reader thread per connectionPhone (Java, app_process, uid 2000)baseservice, guardian, registryvideo, inputvirtual displays, MediaCodecaudio, dati, archiviocapture, data, files, clipboardpannello, controllipanel, wake lock, switchesFigure 2.1 — The pieces and what sits on top of what (arrows: use; dashed: Wi-Fi, ADB over TLS)

The PC side is divided into pieces, one folder each under src/, and the build (meson.build at the root, one meson.build per piece defining <piece>_dep) lets a piece be compiled alone with -Dpezzo=<name>: whatever a piece depends on is then replaced by a fake written inside its own folder. The phone side is one folder per piece under telefono/ compiled together into yasde.jar.

2.2 · Pieces and dependencies

Each PC piece depends only on the ones listed here. The shell is the only code that sees all of them, and it never uses a lower piece directly: it goes through the service layer described in chapter 11.

PieceFolderUsesWhat it provides
Commonsrc/comune-PhBuffer, PhErrore, PhFotogramma (the frame handed to the shell)
ADB clientsrc/adbcommon, OpenSSLRSA key and certificate, TLS connection, channels, shell v2 (4.1 “The ADB client: transport”)
Discoverysrc/scopertacommonmDNS search for connect and pairing services (5.1 “Discovery with mDNS”)
Pairingsrc/abbinamentoadb (key), commonpairing with the six-digit code (5.2 “Pairing with the six-digit code”)
Filessrc/fileadbcopy and listing through sync: (4.6 “File transfer with sync”)
Componentsrc/componenteadb, filestarts the service, command channel, video sessions, input, presence (6.1 “Starting the component on the phone”)
Datasrc/daticomponentapps, icons, state, notifications, search, clipboard
Videosrc/videocommon, FFmpeg, VulkanH.264 decoding, export to PhFotogramma, PNG and MP4 capture (8.4 “Video: receiving and decoding”; the hardware path stage by stage: 8.5 “Hardware acceleration end to end”)
Audiosrc/audioadb, Opus, PipeWiredecoding, jitter queue, playback, gain (9.3 “Audio: playback on the PC”)
Linksrc/collegamentoscoperta, adb, abbinamento, componente, dati, configthe state machine that keeps one phone connected (3.3 “Link states and timings”)
Configsrc/configcommonfiles in ~/.config/YASDE, language table, phone profile
Windows, transfers, weathersrc/finestre, src/trasferimenti, src/meteocommon, config, file, adbsee chapters 12, 13 and 15
Shellsrc/shellall of the aboveGTK4 desktop; src/shell/ossatura wires the real services
Table 2.1 — PC pieces and their dependencies

The phone side follows the same idea. telefono/contratto holds the shared interfaces (Registro, GestoreCanale, GestoreComandi, Guardiano); telefono/base holds the service; every other folder (video, audio, dati, archivio, appunti, pannello, controlli) registers itself through Registro and never names another folder: base and video talk only through Registro.

2.3 · Threads

The code is thread-based, with no event loop of its own on the PC side. The table lists the long-lived threads and who owns them.

ThreadOwnerJob
ADB readerph_adb_collegareads every ADB packet from the TLS socket and routes it to its channel; one per connection
Link threadph_col_avviasearch, connect, monitor every 500 ms, drop, close; delivers every notice one at a time
Component: commandsph_componente_avviareads the command channel and separates answers from events
Component: shellph_componente_avviareads and discards the log lines of the service process
Component: presenceph_componente_avviasends PRESENZA when nothing has been sent for 5 minutes
Search, clipboardsrc/datione thread per file search and one for the clipboard channel
Audio reader, PipeWiresrc/audioreads and decodes Opus; PipeWire calls the fill function from its own real-time thread
Manager ph-gestoresrc/shell/ossaturabuilds the session when the link is up, tears it down on loss, starts audio after its delay
Worker poolssrc/shell/ossaturaseven GThreadPools: 3 general workers, and one thread each for state, icons, writing, streams, input, install
Video readerthe shell surfacecalls sv_flusso_leggi in a loop: receive, decode, export, one thread per window
GTK main threadGTKeverything visible; never waits on the network
Table 2.2 — Threads

The rules that keep this safe are in the contract headers and are checked first by review: a public function that uses an object must survive a close called from another thread at the same moment (a use counter that close waits for); no callback runs while holding a lock its receiver might want; no wait is unbounded unless the contract says so; no lock is held during an external command or a network write. The single known exception is the input channel lock, held during a write because ADB forbids two writers on one channel.

i
Note. Objects owned by a session (PhAdb, PhComponente, PhDati) are never used without a loan: 3.4 “Loans: using the session objects”.

2.4 · Life of a click

This is the path of a user action, to fix the picture before the details. A click on a window of a phone app:

  • GTK delivers the pointer event to the window surface; the shell turns it into a PhSrvInput in the video's own coordinates and calls sv_flusso_input.
  • If the stream is active and the video size matches, the phone panel is switched off if the phone is “in hand”, then the event is queued on the input pool.
  • ph_input_tocco writes a TOCCO message (type 0x50) on the input channel, with the video size it was computed on.
  • On the phone, Input reads it, drops it if the size is stale, scales it to the virtual display and injects a MotionEvent touchscreen event on that display.
  • The app draws; the virtual display feeds the encoder; a H.264 packet travels the video:<id> channel back; the reader thread decodes it with FFmpeg and hands the frame to GTK (as a DMA-BUF texture with VA-API; copied to memory first with the Vulkan via, used only where VA-API is missing).
Chapter 3

Startup and session lifecycle

3.1 · Startup: from the AppImage to the window

The AppImage runs pacchetto/AppRun, a POSIX shell script that prepares the environment and then replaces itself (exec) with usr/bin/yasde. The program is src/shell/ossatura/main.c, which only calls ph_ossatura_esegui.

AppRunpaths, loadersmainph_ossatura_eseguiGtkApplicationit.yasde.YASDEservicesph_col_avviawindowdesktop appearsFigure 3.1 — From the AppImage to the window
  1. AppRun takes APPDIR from its own location (never from the environment, which could point to another package), puts the package libraries first in LD_LIBRARY_PATH, adds the package schemas to XDG_DATA_DIRS, and points GIO_MODULE_DIR to an empty folder so that no system GIO module of another GLib version is loaded.
  2. The image-loader cache for gdk-pixbuf is generated from a template with the mount point of the package (~/.cache/YASDE/yasde-pixbuf-<pid>.cache); files of dead processes (or older than a day) are removed. If the folder is not writable or the path has unsafe characters the program starts without these loaders (WebP does not open; PNG and JPEG stay).
  3. ph_ossatura_esegui first loads the preferences; an unreadable file is set aside and defaults are used.
  4. ph_lingua_inizializza always selects English: the lingua preference is read and ignored.
  5. If the user chose a fixed shell scale, GDK_DPI_SCALE is set from it before GTK starts (GTK4 has no fractional widget scale; it is applied to fonts).
  6. The GtkApplication has the id it.yasde.YASDE and is unique per session. In startup (primary instance only) SIGTERM and SIGINT are routed to g_application_quit, temporary files older than 3600 s are removed and orphan background images are cleaned.
  7. In activate the services are built (ph_ossatura_servizi_veri: the yasde.jar is looked up next to the executable; the key path is chiave.pem in the config folder), then the shell and the window are created and the pieces installed. A second launch only presents the existing window.

3.2 · Connecting: from search to a live session

Everything between “no phone” and “connected” happens in tentativo and prova_candidato (src/collegamento/collegamento.c) on the link thread. The thread starts in CERCO (searching) as soon as ph_col_avvia returns.

link threadkeeps one phonescopertamDNSadbTLS clientcomponentePC sidephonethe serviceph_adb_collega(last address)no answer or no address: search the networkph_scoperta_cerca(1500 ms)candidatesph_adb_collega(candidate, 8000 ms)getprop ro.serialno (serial)ph_componente_avvia(15000 ms)sync: copy yasde-XXXXXXXX.jarlaunch app_process (service)PRONTO (stdout line)command and input channels; greetingOK: API, screen, modelph_dati_apri, ph_dati_statoconnected (or locked): notice to the shellFigure 3.2 — From searching to connected
  1. Last known address. From telefoni.toml (the config piece): the phone expected, or the most recently seen one. It is tried first because the port of wireless debugging changes every time the option is turned on, but the address often still works.
  2. Discovery. ph_scoperta_cerca for 1500 ms; pairing services are ignored here. Known phones come first (heaviest weight: the most recently seen), then the others. If several are found and none is known, the first is taken and the notice says so (scelta_arbitraria).
  3. ADB connection with ph_adb_collega (8000 ms). If the phone does not recognise the key the outcome is T_NON_ABBINATO: if no candidate connects, the state becomes NON_ABBINATO and the link waits for the pairing code (5.2 “Pairing with the six-digit code”).
  4. Serial number. getprop ro.serialno; if empty or unknown, aid-<android_id> (from settings get secure android_id), and as a last resort modello-<model>. After the first connection only the same serial is accepted: another phone at the same address is discarded.
  5. Component start (6.1 “Starting the component on the phone”) with a 15000 ms limit for copy, launch, PRONTO and greeting.
  6. Data: ph_dati_apri registers on the events 0x7e-0x7f (the link is the only one that does: there is one listener per component); then the locked state is read once.
  7. Record. telefoni.toml is updated (serial, name, address as host:port or [host]:port for IPv6, last seen); a failure to save is never fatal. The session is published and the state becomes COLLEGATO, or BLOCCATO if the screen is locked.

3.3 · Link states and timings

The link is a state machine with its own thread and no graphics. Notices are delivered one at a time from that thread, in order, and repeated notices are not sent twice.

StateMeaningLeaves when
CERCOsearching, connectingconnected; or no candidate answers (waits pausa_cerca_ms and tries again); or the key is rejected
COLLEGATOADB alive, component started, greeting donethe screen locks (BLOCCATO), or the connection or component dies (PERSO)
BLOCCATOconnected but the phone screen is locked: the shell shows a veilunlock (COLLEGATO), or drop (PERSO)
PERSOlost: retries by itself with growing waitsa retry succeeds; ph_col_riconnetti_ora skips the wait
NON_ABBINATOthe phone does not know this PC's keyph_col_abbina (pairing), or ph_col_riconnetti_ora to retry without pairing
CHIUSOclose requested; everything released in orderfinal state
Table 3.1 — Link states
OptionDefaultUsed for
durata_scoperta_ms1500one network search
timeout_collega_ms8000ph_adb_collega (the whole TCP, STLS, TLS procedure)
timeout_componente_ms15000ph_componente_avvia
timeout_abbinamento_ms15000ph_abbinamento_esegui
pausa_cerca_ms1000between two searches in CERCO
riprova_iniziale_ms1000first wait in PERSO; doubles every time
riprova_massimo_ms30000ceiling of that wait
riprova_dopo_blocco_ms3000ceiling after a drop that happened from BLOCCATO: wireless debugging is reopened on unlock
controllo_ms500period of the liveness and lock check
attesa_prestiti_ms3000how long a drop waits for loans to be returned
Table 3.2 — Link timings (PhColOpzioni; 0 means default)

While COLLEGATO or BLOCCATO the thread checks every controllo_ms that ph_adb_viva and ph_componente_vivo are still true and follows the lock flag, which comes from the 0x7e events and from the first state read. Some phones turn wireless debugging off when they lock: “locked, lost, unlocked, connected” then happens without any intervention.

3.4 · Loans: using the session objects

The link's sessions live only while the connection does. Whoever wants to use the ADB connection, the component or the data object takes a loan and gives it back; the link never destroys an object under the feet of a borrower.

  • ph_col_presta returns a loan only in COLLEGATO or BLOCCATO; ph_col_prestito_adb, ph_col_prestito_componente and ph_col_prestito_dati are valid until ph_col_restituisci.
  • On a drop (or on close) the link first stops granting loans, calls the in_perdita notice (“about to lose the connection: give back”), then waits up to attesa_prestiti_ms for them.
  • If a loan is not returned in time the session becomes an orphan: its memory stays valid, calls fail quickly because the connection is dead, and the last to return destroys it in order (data, component, connection; up to about 2 s). Meanwhile the link goes on with a new session.
  • Everything opened with the borrowed objects (channels from ph_componente_canale, searches and clipboard of dati) must be closed before the loan is returned. Video streams may be closed afterwards: the component closes them anyway, but they must still be passed to ph_video_chiudi.
  • A loan must never be returned from inside a component or data callback (it could wait for that very callback): the same rule forbids calling ph_col_chiudi from a notice.

3.5 · Building the session on the shell side

When the link reports COLLEGATO or BLOCCATO, col_avviso (in src/shell/ossatura/servizi_veri.c) posts a message to the manager thread ph-gestore, which builds the shell-side session.

  1. Weather: the phone's serial is told to the weather service; the phone profile (window layout, desktop, preferences per phone) is loaded.
  2. Data (sv_dati_sessione_nuova): the state is read; the listener for panel events 0x6e is registered and PANNELLO_STATO is asked; if the panel is on and the phone is not “in hand” it is switched off, queued on the state pool because it can take seconds (10.4 “The phone panel: off when connected”); the clipboard channel is opened; the app list and the notifications are requested; the quick-controls state is read.
  3. Transfers: the transfer queue gets the new session.
  4. Streams: every window already open (after a drop) is reopened (8.2 “Video: sessions and recovery”).
  5. Weather position: there is a phone now, so the position is the phone's.
  6. Audio is not started here: the first stream of the session schedules it SV_AUDIO_RITARDO_MS (5000 ms) later, and a failed start is retried after 2, 4, 8 and 16 s (9.3 “Audio: playback on the PC”).

3.6 · Orderly close, drop and reconnection

There are two ways out: the user closes YASDE (orderly), or the connection or the service dies (drop). Both end with the phone as it was, the first by the component, the second by the guardian.

Orderly close. The window is hidden and destroyed (pieces stop listening), then ph_shell_libera closes the streams, then the services are freed: ph_col_chiudi raises in_perdita, the manager closes the session and returns the loan, and the component is closed. ph_componente_chiudi first forbids any new PRESENZA, sends CHIUDI and waits at most 2000 ms for the answer (the wait for the turn included), then joins its threads and closes the channels. The shell channel goes last: closing it is the safety net that stops the service. SIGTERM and SIGINT take the same path.

On the phone the Servizio answers OK and then: closes the command socket and the listening socket; runs the pieces' close actions on a separate thread for at most 3 s; asks the guardian to run the restore list (20 s limit per run); deletes its files; prints servizio terminato and exits.

Drop. If the connection dies (ph_adb_viva becomes false within about 10 s thanks to TCP keepalive and TCP_USER_TIMEOUT), or the service process ends, the link moves to PERSO, gives back the session as above and retries with waits of 1, 2, 4 ... up to 30 s. On the phone the service sees its command channel or stdin close and shuts down by itself; if it was killed (kill -9, or adbd restarted), the guardian reads end-of-file on its pipe and runs the restore list. The streams of the open windows become PERSO and are reopened by themselves when a new session exists; a running recording is stopped.

!
Warning. A service killed together with its guardian (restarting adbd kills the whole process group) leaves the jar and the restore script behind. The next service cleans them at start-up (6.6 “Cleaning up leftovers at start-up”).
Chapter 4

The ADB client

4.1 · The ADB client: transport

The ADB client is src/adb: a client for the Android Debug Bridge protocol written from scratch, with no ADB library and no use of the adb tool. It opens one TLS connection to the phone's wireless-debugging port and multiplexes any number of channels on it. It knows nothing about video, audio or files; its public header is src/adb/adb.h.

FileRole
adb.hthe contract: PhChiave, PhAdb, PhCanale, ph_shell_esegui
chiave.cRSA key file, self-signed certificate, public key in Android format
connessione.cTCP, STLS, TLS 1.3, reader thread, channels and flow control
pacchetto.c, interno.hthe 24-byte packet header and its checksum
shell.cshell v2 commands
finto_telefono.ca fake phone used by tests
Table 4.1 — Files of src/adb

The concurrency model is binding: one reader thread per PhAdb reads every packet from the socket and routes it to its channel; writes on the socket are serialised by a mutex so that a packet is never split by another; every channel has its own incoming queue; ph_canale_leggi blocks (with a timeout) only the thread that reads that channel. On one channel one reader and one writer may work together, two readers or two writers may not. If the connection dies, every read and write in progress returns an error at once, no thread stays blocked, and ph_adb_viva becomes false.

4.2 · Connection and TLS handshake

The connection is opened by ph_adb_collega(host, port, key, timeout, not_paired, error). One deadline covers the whole procedure: TCP connect, STLS exchange, TLS handshake and the phone's greeting.

PCph_adb_collegaphoneadbdTCP connect (non-blocking, with deadline)CNXN version 0x01000001, max 1 MiB, featuresSTLS (or AUTH: not paired)STLSTLS 1.3 handshake, client certificate of the PCCNXN banner, max data, featuresPhAdb alive; reader thread startedFigure 4.1 — The connection handshake
  1. TCP. A non-blocking socket tried on every address returned by getaddrinfo. After connecting: TCP_NODELAY, SO_KEEPALIVE with idle 5 s, interval 2 s, 3 probes, and TCP_USER_TIMEOUT 10000 ms: a phone that leaves the Wi-Fi without closing is detected in about 10 s instead of hours. SIGPIPE is ignored for the whole process (once, only if nobody chose a behaviour), because OpenSSL writes with write().
  2. CNXN in clear. Version 0x01000001 (checksum no longer verified: integrity is given by TLS), maximum data 1 MiB, banner host::features=shell_v2,cmd,delayed_ack;. The final semicolon is required: adbd reads the banner as a C++ string including the terminator, and without it the last feature would be delayed_ack followed by a NUL byte and would not be recognised.
  3. STLS. If the phone answers AUTH the PC is not paired (*non_abbinato = true); any other answer is an error. The PC answers STLS and starts TLS.
  4. TLS 1.3 only, with the PC certificate. The phone certificate is not verified (it is self-signed, as for the standard tool): what matters is that the phone recognises the PC, and it decides by the PC key. The handshake failing with a certificate alert, or the phone closing during or just after the handshake, is reported as “not paired”; any other error is a network error.
  5. Greeting. Inside TLS the phone sends its CNXN: its maximum data (capped at 1 MiB, and refused if below 256) and the banner (which contains the model). delayed_ack is active only if both sides declared it.

The banner is available as ph_adb_presentazione. ph_adb_chiudi marks the connection closed, shuts the socket down to wake the reader, joins it and releases; the file descriptor and the SSL object stay until the last channel is closed, so that a channel finishing an operation never finds a recycled descriptor.

4.3 · The PC key and certificate

The key and the certificate live in chiave.c. The key file is chiave.pem in ~/.config/YASDE, an RSA 2048-bit private key in PKCS#8 PEM (the format of the standard tool's adbkey, so that in development an already paired phone can be reused).

ItemValue
Creationph_chiave_carica_o_crea: if the file is missing the key is generated and saved with permissions 0600, creating the folder with 0700
CertificateX.509 v3, serial 1, subject and issuer CN=yasde, valid from one day ago for ten years, signed with SHA-256; used for TLS and for pairing
Public key for the phoneph_chiave_pubblica_adb: Android's RSAPublicKey structure (length in words, n0inv, modulus, rr = (2^2048)^2 mod n, exponent; little endian; 524 bytes) in base64, followed by a space and user@host, NUL-terminated
OpenSSL APIonly EVP and BN calls of OpenSSL 3; the deprecated low-level RSA functions are not used
Table 4.2 — The PC key and certificate
i
Note. n0inv and rr are what adbd needs for Montgomery multiplication; this is why the key cannot be sent as a plain public key.

4.4 · Channels and flow control

A channel is one ADB service opened on the connection: ph_canale_apri(adb, service, timeout, error). Services used by YASDE: shell,v2,raw:<command>, shell:<command>, sync: and localabstract:yasde.

FunctionBehaviour
ph_canale_leggireads 1 to n bytes; returns the count, PH_CANALE_CHIUSO (0: the other side closed and the queue is empty), PH_CANALE_ERRORE (-1, error filled) or PH_CANALE_TEMPO (-2: timeout, not an error); a negative timeout waits without limit
ph_canale_leggi_tuttoexactly n bytes or failure; closing before n bytes is an error
ph_canale_scriviall n bytes, split in ADB packets, or failure
ph_canale_chiudicloses and frees; wakes a read in progress in another thread
Table 4.3 — Channel functions

Flow control exists in two forms, chosen at connection time.

ModeSendingReceiving
delayed_ack (both sides declare it)a window per channel: the phone's OKAY carries the number of bytes by which the window grows; the PC never sends beyond it, and several writes may be in flightthe PC grants the phone a 4 MiB window per channel (FINESTRA_RICEZIONE); each OKAY widens it by what the reader really consumed, sent after 1 MiB of consumed data (ACK_SOGLIA); a phone sending beyond its window violates the flow control and the connection drops
classicafter a WRTE the OKAY is awaited before the next WRTE on the same channelthe OKAY is sent when data is queued, but withheld while the queue exceeds twice the maximum packet (SOGLIA_CODA), and resumes when the reader has emptied it
Table 4.4 — Flow control

The effect is that a slow reader brakes the phone instead of filling the PC's memory. Waiting for an OKAY or writing to the socket has a hard limit of 30000 ms (ATTESA_SCRITTURA_MS): a phone that stops answering does not block a thread for ever. A late reply to an open that had timed out is answered with CLSE so that the service is closed on the phone.

!
Warning. Packets coming from the phone are treated as hostile. The header is decoded with ph_pacchetto_decodifica, which refuses a magic that is not the complement of the command and a length above PH_ADB_MAX_DATI (1 MiB); an OKAY with a malformed payload in delayed_ack mode drops the connection.

4.5 · Shell commands

ph_shell_esegui(adb, command, out, err, &code, timeout, error) runs a command with the shell v2 protocol and waits for the end. It opens a channel with service shell,v2,raw:<command>, reads frames of one id byte plus a 32-bit little-endian length plus data, and closes the channel.

IdMeaning
1stdout: appended to out (may be NULL)
2stderr: appended to err (may be NULL)
3exit code, one byte; ends the command
Table 4.5 — Shell v2 frame ids used by the PC

It returns -1 if the command could not run or the time ran out; a non-zero exit code is not an error of the function. A frame longer than 16 MiB is refused. Read in slices of 4096 bytes. The component itself is started with the older shell: service because its output is a plain line stream (6.1 “Starting the component on the phone”).

4.6 · File transfer with sync

The copy of the component jar and every file transfer use the ADB sync: service, in src/file/file.c. Requests are four letters plus a 32-bit little-endian length (the protocol is documented in AOSP's SYNC.TXT; the code here is new). Each operation opens its own sync: channel, so several can run together from different threads.

OperationRequestNotes
ph_file_inviaSEND + DATA blocks + DONEPC to phone; creates or overwrites; keeps the local modification time; a partial remote file is removed on cancel or failure; mode 0100644
ph_file_riceviRECV, with a prior STA2phone to PC; writes <local>.parziale created exclusively, renames at the end without replacing an existing file, gives the phone's modification time; never overwrites a user file
ph_file_elencaLIS2 (entries DNT2)folder listing without . and ..; sorted: folders first, then files, by name ignoring case; hidden names are included (the shell filters)
ph_file_infoSTA2information on a path
remove remoteshell:rm -f -- '<path>'sync cannot delete; the path is quoted with '\'' for embedded quotes
Table 4.6 — sync: operations
ConstantValueMeaning
BLOCCO_MAX65536largest DATA block (protocol limit)
BLOCCHI_PER_SCRITTURA16blocks gathered in one write (cancellation is checked about every MiB)
PH_FILE_ATTESA_MS30000silence after which the phone is declared stuck
PH_FILE_FETTA_MS200read slice, so the cancel flag is checked often
PERCORSO_MAX1024longest path in a sync request
VOCI_MAX, NOMI_BYTE_MAX200000; 64 MiBsafety caps on entries and on the bytes of their names
Table 4.7 — Limits of src/file

Outcomes are PhFileEsito: PH_FILE_RIUSCITO, PH_FILE_ERRORE, PH_FILE_ANNULLATO (the cancel flag became true), PH_FILE_NON_TROVATO, PH_FILE_NON_CONSENTITO (Android denies access) and PH_FILE_ESISTE (the destination or its .parziale already exists on the PC: nothing was touched). A FAIL from the phone is plain text and is classified by its words.

Chapter 5

Discovery and pairing

5.1 · Discovery with mDNS

Discovery is src/scoperta: a multicast-DNS (DNS-SD) client written from scratch, with no Avahi and no library. It looks for the two services Android announces while Wireless debugging is on. It depends only on src/comune.

ServiceGivesExists
_adb-tls-connect._tcp.localthe port to connect to (abbinamento = false)while wireless debugging is on; the port changes every time it is turned on
_adb-tls-pairing._tcp.localthe pairing port (abbinamento = true)only while the phone shows the pairing-code screen
Table 5.1 — The two mDNS services

API. ph_scoperta_cerca(duration_ms, found, max, error) asks on every active interface, collects answers for the given time and fills PhTelefonoTrovato (instance name such as adb-R5CT0000000-AbCdEf, address text, port, pairing flag), without duplicates. It returns the count; zero is not an error. ph_scoperta_leggi_risposta and ph_scoperta_domanda are the pure parts, testable without a network; a malformed or hostile packet must never read outside the buffer and returns 0.

  1. Sockets. IPv4 only for sending: one socket per interface that is up, running, not loopback and multicast-capable (at most 16, one per distinct address), bound to that interface with IP_MULTICAST_IF, TTL 255, multicast loop off. Replies sent from a port other than 5353 come back unicast to that socket.
  2. Listening. One extra socket on UDP 5353 joined to 224.0.0.251, shared with other programs (Avahi may already own the port). If the port is not available the search goes on with unicast replies only.
  3. Questions. The first question has the QU bit (unicast answer wanted). Questions repeat at 0, 250, 1000, 2000, 3000, 4500, 6000 and 8000 ms from the start and then every 2 s, because a phone with Wi-Fi in power saving answers late. From the second question on, follow-up questions are added: SRV for an instance seen in a PTR without SRV, and A for an SRV target without an address.
  4. Filtering. A packet whose source is outside the subnet of every interface is discarded (multicast is not routed, so an outside sender is not a real neighbour). At most 64 packets are read per socket per turn, and the time limit is checked inside the loop.
  5. Combining. PTR, SRV and A/AAAA records may arrive in different packets and are joined only at the end; the list is recomputed from scratch at every turn so that a TTL 0 “goodbye” removes an entry already found. Name compression is followed for at most 16 pointers; the collection holds at most 64 SRV, 128 address and 64 PTR records.

The link asks for 1500 ms per search (3.3 “Link states and timings”). The hand tool src/scoperta/cerca.c searches for 5 seconds and prints a trace of every packet; it is how a silent phone is diagnosed.

i
Note. A phone that does not announce itself is not a YASDE fault: a real case was solved by turning Wireless debugging off and on again. YASDE cannot tell this from “no phone in range”.

5.2 · Pairing with the six-digit code

Pairing is src/abbinamento. ph_abbinamento_esegui(host, port, code, key, timeout_ms, error) makes the phone register the PC's public key. host and port are those of the pairing service, not of the connection. The code is the one the phone shows under Developer options, Wireless debugging, Pair device with pairing code.

PCph_abbinamento_eseguiphonepairing serviceTCP to the pairing portTLS 1.3, certificate of the PCexport 64 bytes (label adb-label) from this TLS sessionpassword = code + exported bytestype 0: SPAKE2 message (32 bytes)type 0: SPAKE2 message (32 bytes)shared key (64 bytes) → HKDF-SHA256 → AES-128 keytype 1: AES-GCM(info with the PC public key)type 1: AES-GCM(info of the phone)decrypts and verifies the tag: pairing doneFigure 5.1 — Pairing with the six-digit code
  1. Transport. TCP with a deadline, then TLS 1.3 with the PC certificate; the phone certificate is not verified (the guarantee comes from the code). All reads and writes have a socket timeout equal to timeout_ms (10000 if zero or negative). SIGPIPE is ignored, because pairing happens before any connection.
  2. Binding to the connection. 64 bytes are exported from the TLS session with SSL_export_keying_material (label adb-label including its terminating zero, no context). The SPAKE2 password is the code followed by these bytes, so a man in the middle cannot reuse the exchange on another connection. A code of 1 to 32 characters is accepted at this level.
  3. SPAKE2. On edwards25519, in the variant used by Android (BoringSSL's, with its quirks reproduced on purpose: without them the phone refuses). The PC is alice with the name adb pair client, the phone is bob (adb pair server); both names enter the final digest with their zero terminator (16 bytes each). The points M and N are fixed, generated from the seeds edwards25519 point generation seed (M) and (N), and a test regenerates them. The arithmetic uses OpenSSL BIGNUMs: correct but not constant time, which is accepted because the code is valid once, for a few seconds, on the home network.
  4. Key. HKDF-SHA256 over the 64-byte SPAKE2 key with info adb pairing_auth aes-128-gcm key (no terminating zero) gives a 16-byte AES key.
  5. Information exchange. Each side sends one packet of 8192 bytes plus the 16-byte AES-GCM tag, with nonce counter 0 (8 bytes little endian plus four zeros). The PC's plaintext is the type byte 0 (ADB public key) followed by the key text of ph_chiave_pubblica_adb; the rest is zeros.
  6. Verification. A wrong code is detected only by the failure to decrypt the phone's packet (or by the phone closing): this is the single confirmation.
FieldSizeValue
Version1 byte1
Type1 byte0 = SPAKE2 message, 1 = information
Length4 bytes big endianat most 2 * 8192; checked before reading
Bodylength32 bytes (SPAKE2) or 8192 + 16 bytes (information)
Table 5.2 — Pairing packet

Secrets are wiped with OPENSSL_cleanse (password, shared key, AES key, plaintext). Failures return a specific sentence: phone silent on that port; phone closed the pairing (code expired or screen closed); wrong protocol version; unexpected or oversized answer; “wrong or expired code”.

5.3 · Pairing as seen by the link and the shell

From the user's side pairing is a state of the link, not a separate program. When ph_adb_collega reports that no candidate knows the PC key, the link enters NON_ABBINATO and the shell shows the connection window.

  1. The window asks for the six-digit code. The field accepts only digits, at most 6, even when pasted: spaces and other characters are filtered out and the buffer is wiped (src/shell/connessione).
  2. The shell registers the request before calling ph_col_abbina(code) (or ph_col_abbina_a(host, port, code) when an address is typed) and starts a timer. The outcome is not a return value: it arrives in a link notice whose field esito_abbinamento is RIUSCITO or FALLITO, exactly once per accepted request. With no outcome in PH_SRV_ABB_LIMITE_S (60) seconds the request counts as expired.
  3. The link thread looks for the pairing service for 1500 ms: the one at the address of the phone that answered “not paired”, otherwise the only one present; with more than one and no match, or none, the notice says to open the pairing-code screen on the phone and try again.
  4. It loads or creates the key and calls ph_abbinamento_esegui with a 15000 ms limit. Success moves the state to CERCO (“pairing done: connecting”); failure stays in NON_ABBINATO with a sentence of the link's own: user-facing messages never contain addresses or the library's text.
  5. The code is wiped with explicit_bzero right after use and never reaches a log or a file. If a close arrives during pairing no notice concludes the request; only CHIUSO arrives.

ph_col_riconnetti_ora in NON_ABBINATO retries the connection without pairing; it is refused (-1) while a pairing is accepted or running.

!
Warning. Wrong code, pasted code with spaces, authorisation revoked from the phone, and wireless debugging switched off and on while the app is open were not yet tried on a real phone at the time of writing.
Chapter 6

The phone component

6.1 · Starting the component on the phone

The PC side of the phone component is src/componente. It copies the jar to the phone, launches the service, opens the protocol channels, greets the service and then offers the rest of the PC two things: requests answered with OK or ERRORE (and events that arrive at any time), and the video and input functions. It uses only adb.h and file.h and never decodes video: it hands packets to the layer above.

FileRole
componente.hthe contract: message codec, PhComponente, video and input functions, presence
componente.cstart, close, command thread, requests, input
video.cvideo sessions: open, read packets, resize, key frame, pause, close
messaggi.c, lettura.cmessage writer and bounded reader; resumable reads
interno.hinternal constants and the PhComponente structure
Table 6.1 — Files of src/componente

ph_componente_avvia(adb, jar, event_fn, user, info, timeout_ms, error) does the following in order. timeout_ms (0 means 10000) applies to the launch, the wait for PRONTO, opening the channels and the greeting; afterwards a request has 15000 ms (PH_TIMEOUT_RICHIESTA_MS, because opening an app can take a while).

PCph_componente_avviaadbdADB channelsserviceon the phonesync: SEND yasde-XXXXXXXX.jarlaunch app_process with the jarprocess started (uid 2000)socket, leftovers cleaned, guardian startedstdout line: readyabstract socket, then the command lineabstract socket, then the input lineSALUTO (version 1)OK: version, API, screen, density, modelFigure 6.1 — Starting the service
  1. Name. /data/local/tmp/yasde-<8 hex digits>.jar with the digits read from /dev/urandom. The name changes at every start so that the guardian of a service that has just died, which deletes its own jar, cannot delete the next one.
  2. Copy with ph_file_invia (4.6 “File transfer with sync”). The “jar copied” flag is set before the copy: if anything fails from here on, the jar is removed with rm -f (3000 ms limit, result ignored).
  3. Launch with the legacy shell: service: CLASSPATH=<jar> app_process / it.yasde.Servizio. The channel stays open for the whole life of the service; if it closes, the service ends.
  4. Wait for PRONTO: the output is read line by line (lines of at most 160 characters are kept, a longer unterminated chunk beyond 4096 bytes is dropped); earlier log lines are discarded but the last one is remembered for the error message (“the service ended before PRONTO; last line: ...”).
  5. Channels. Each protocol channel is an ADB channel localabstract:yasde followed by one ASCII line naming its type. The component opens comandi and input itself; the rest of the PC opens others through ph_componente_canale (audio, cerca, appunti), which refuses the three names owned by the component (comandi, input, video:...) and any line longer than 60 characters.
  6. Threads are started: command reader and shell-log reader; then SALUTO is sent; then the presence thread.
  7. Greeting. SALUTO carries the protocol version (1). The reply gives the version, the Android API level, the real screen size and density, and the model (PhTelefonoInfo). A different version is an error.
ConstantValueMeaning
PH_PROTOCOLLO_VERSIONE1protocol version
PH_MSG_MAX_CORPO1 MiBlargest message body; a larger declared length ends the command thread
PH_VIDEO_MAX_PACCHETTO8 MiBlargest video packet
PH_FETTA_MS50every blocking read is cut in slices of this size, so a close never waits long
PH_TIMEOUT_PREDEFINITO_MS10000start-up default
PH_TIMEOUT_RICHIESTA_MS15000one request
PH_PRESENZA_INTERVALLO_S300idle time after which PRESENZA is sent
Table 6.2 — Constants of the component

Requests. The command channel serves one request at a time: ph_componente_richiedi_coda takes the turn (a flag, not a mutex, because the wait is timed and the death of the component wakes the queue), writes the message and waits for the OK or ERRORE delivered by the reader thread. An ERRORE becomes a PhErrore with the phone's sentence; the sentence tipo sconosciuto is turned into “the service on the phone does not know request 0x..”. If the phone does not answer within the limit the channel is no longer aligned (a late answer would be taken for the next one), so the component is declared dead. An answer with no request waiting is discarded.

Events (phone to PC, any time, even between a request and its answer) are told apart by type. Video events (0x48) go to the PhEvento given at start; others go to listeners registered with ph_componente_ascolta by type range (at most 8, a range overlapping another without being equal is an error, a NULL function removes). The listener table lock stays held during the call, so removing a listener waits for a call in progress; a listener must return fast and must not call request functions.

Presence. The thread thread_presenza sends PRESENZA when no request has started for presenza_ms (300 s). It uses the boot clock (CLOCK_BOOTTIME, which advances while the PC sleeps, so at wake-up the message goes at once) and waits in slices of at most 30 s. A failure writes one generic line on stderr and is retried at the next expiry. See 10.7 “Signs of life and PC absence”.

6.2 · The service process

The service runs Servizio.main in telefono/base/it/yasde/Servizio.java. Every thread catches everything, including Error, so a broken channel cannot bring the service down. The order of its start-up matters.

  1. Find the running jar from CLASSPATH; it is accepted only if it is under /data/local/tmp/, ends in .jar and has no .. (otherwise nothing will be deleted at the end).
  2. Create the guardian object (not started).
  3. Take the socket: an abstract LocalServerSocket named yasde. From here no other service of this name is alive.
  4. Clean leftovers of dead sessions (6.6 “Cleaning up leftovers at start-up”), before starting the own guardian (its script could have the name of a dead one with the same pid).
  5. Start the guardian (6.5 “The guardian and the restore list”) and register it in Registro; add a JVM shutdown hook (SIGHUP, SIGTERM) that runs the close without System.exit.
  6. Check the hidden APIs (Nascoste.verifica) and log the missing ones; then register the pieces (below).
  7. Start the stdin guard thread: if the shell's stdin closes, the PC is gone and the service shuts down.
  8. Print PRONTO and loop on accept, one daemon thread named canale per connection.

Pieces. Servizio calls by reflection the static method registra() of each class in PEZZI; a missing class is skipped with a log line.

ClassFolderRegisters
Videotelefono/videochannel video, commands 0x40-0x4f, close action
Inputtelefono/videochannel input
Audiotelefono/audiochannel audio, close action
Datitelefono/daticommands 0x70-0x73, 0x76-0x77, 0x7b-0x7d, 0x90-0x9f; events 0x7e, 0x7f; close action
Archiviotelefono/archiviocommands 0x74, 0x75
Cercatelefono/archiviochannel cerca
Appuntitelefono/appuntichannel appunti, close action
Pannellotelefono/pannellocommands 0x60-0x6f, signs of life, close action
Controllitelefono/controllicommands 0x80-0x8f, close action (turns off the torch YASDE lit)
Table 6.3 — Pieces of the component

Channels. Each connection is first checked for who is on the other end (6.4 “Who may talk to the component”), then a line of at most 64 characters is read with a 5 s socket timeout. comandi is served by the service itself and only one command channel may exist (a second is refused). Any other line is split at the first colon into prefix and argument and handed to Registro.canale; an unknown prefix closes the channel.

Command channel. A loop reads a message, calls Smistatore.tratta and writes OK or ERRORE under a lock shared with the events, so answers and events never interleave. An exception becomes ERRORE with its message (an exception with no message becomes “malformed request”: a Java class name is never sent). After a successful CHIUDI the loop ends and the service shuts down; if the channel closes for any reason the service shuts down as well.

6.3 · The registry and the dispatcher

Registro (in telefono/contratto) is the meeting point between the service and the pieces, so the two folders compile without each other. Everything in it is thread-safe.

MethodUsed byPurpose
registraCanale(prefix, handler)piecesserve the channel whose first line starts with the prefix (GestoreCanale.gestisci(socket, argument))
registraComandi(from, to, handler)piecesserve command types in a range (GestoreComandi.gestisci(type, body) returns the body of the OK)
registraChiusura(runnable)pieceswhat to do at orderly close; run before the guardian restores; never run if the service is killed
mandaEvento(type, body)piecessend an event to the PC; does nothing without an open command channel
guardiano()piecesthe guardian; can be null in isolated tests of one piece
segnoDiVita(nowMs)dispatcherrecord a sign of life of the PC and notify listeners
registraSegnoDiVita(runnable)piecesbe notified at every sign of life, on the command thread: only wake a thread, no work
Table 6.4 — Registro

Smistatore has no Android classes (the clock and the greeting come from outside) so it can be tested on a plain JVM. For every message, even unknown or malformed, it first records the sign of life, then dispatches: SALUTO to the greeting function; PRESENZA answers an empty OK (and refuses a non-empty body); CHIUDI answers an empty OK; anything else goes to the handler registered for its type, or fails with tipo sconosciuto.

6.4 · Who may talk to the component

The socket is abstract and in principle reachable by any process of the phone. Without a check any app could take the command channel before the PC, or open input and send touches. The PC always arrives through adbd, that is as the shell user.

Right after accept and before reading one byte, Servizio.connessione reads the peer's credentials from the kernel (not forgeable) and accepts only Pari.UID_SHELL (2000) and Pari.UID_ROOT (0, which is adbd on development phones). Any other uid (apps start at 10000) is closed at once. If the credentials cannot be read, the connection is refused. The refusal is logged as collegamento rifiutato (uid N non ammesso) at most once per second. The uid is not personal data and is what tells you what to change if some phone's adb shows a different user.

!
Warning. The check was proven on a real phone: the live connection of 24 Nov 2026 succeeded with it active (adb arrives as uid 2000). If YASDE cannot connect on some other phone, look for that log line first.

6.5 · The guardian and the restore list

The guardian is the class Custode (telefono/base/it/yasde/Custode.java), the implementation of the Guardiano interface. It makes sure the phone returns as it was even if the service dies abruptly. The design documents speak of two guardians (connection and service); the code has this single one.

registerimposta(name, order, cmd)write listtmp file + renamechangeonly if imposta is trueundocmd, then togli(name)Figure 6.2 — The life of one restore entry
  1. A separate process. The service starts setsid sh -c <script>, a shell that is leader of its own session, so it dies neither with the service nor with the PC's shell. The service keeps the write end of a pipe open: its death, however it happens (even kill -9), closes the pipe and the guardian reads end-of-file.
  2. The list. The restore commands live in a file /data/local/tmp/yasde-custode-<pid>.sh, rewritten atomically (temporary file, fsync, rename on the same file system) at every imposta or togli. The guardian runs it as a script. It starts with echo $$ > "$0.pid" (the id of the session, used to kill leftovers) and defines timeout 20 if the phone has it.
  3. One shell per entry, sorted by order (lowest first; equal orders keep insertion order), each in its own sh -c '...' so a wrong command does not eat the next ones; each runs under timeout 20 when available.
  4. The guardian's script reads one line from the pipe. If the line is not fine (end-of-file: the service died) it runs the list. Then it deletes the list and its .tmp and .pid, deletes the jar only if it is still the same file seen at start (inode, size, date: the PC may already have copied a new one), and as a last act kills the processes still in its own session, including children of an expired restore adopted by init.
  5. Orderly close: ferma() runs the list itself (20 s limit; on expiry the session is killed with pgrep -s), then writes fine and closes the pipe; the guardian only deletes the files. If a restore does not finish in time, fine is not written and nothing is deleted: closing the pipe makes the guardian redo the list.

The contract (Guardiano): imposta(name, order, shellCommand) returns true only if the restore is really safe, that is the new list was written. If it returns false the caller must not make the change, because nobody would undo it. After the guardian has stopped, imposta executes the command at once (20 s) and returns false. togli(name) removes an entry whose change has already been undone; if the rewrite fails the disk list keeps the entry (one entry too many, conditional and harmless, is better than one too few).

Value-wins rule. A restore command changes a setting only if it still has the value YASDE wrote; if the user changed it meanwhile, it stays. Commands are self-contained shell lines: no environment variables of the service, no nested quotes.

EntryOrderRegistered byRestores
audio-volume50Catturamedia volume back to the original, only if still at the maximum YASDE set (cmd media_session volume --stream 3)
pannello-acceso400Pannellopanel on: CLASSPATH=<jar> app_process / it.yasde.Pannello accendi, which does nothing if Android is asleep
pannello-frequenza410Pannellomin_refresh_rate back to the user's value, only if still ours
pannello-timeout420Pannelloscreen_off_timeout back to the user's value (or deleted if it did not exist), only if still the maximum
trova-volume, trova-modo, trova-non-disturbare420-422Trovaunused: “find my phone” is not available in this version
Table 6.5 — Restore entries and their order
i
Note. Not everything has an undo on purpose. The ringer mode and Do Not Disturb set by the quick-switches widget are explicit user commands with a permanent effect, like tapping the phone's own quick tile; the torch is turned off at orderly close and, if the service dies, by the system because it is tied to the process that lit it (measured on the test phone).
i
Note. The wake lock (TieniSveglio) is not in the list for the same reason it is not needed: the system releases it when the process dies.

6.6 · Cleaning up leftovers at start-up

If adbd restarts (wireless debugging switched off and on), init kills every process of its group, even those with setsid: service and guardian die together and the jar and the restore script stay on the phone. The next service cleans them. The rule is in Resti (pure, with no Android classes: the processes are read from a folder passed in, so it is tested on a JVM) and Custode.pulisciResti.

  1. Names recognised by exact form only: yasde-custode-<pid>.sh with accessories .pid, .tmp and .tentativi, and yasde-<8 hex>.jar.
  2. If there is nothing of ours apart from the current jar, the costly scan of the processes is skipped.
  3. Scan of the processes in /proc: the pids of services and the paths under the folder cited by any process. If the own service is not among the processes read, the scan is not reliable and nothing is executed or deleted.
  4. The plan. A script is dead if its pid is not a live service (the own pid always counts as dead: its guardian has not started) and no live process cites it. A jar is old if it is not the current one and no live process cites it. Orphan accessories whose script is gone are deleted.
  5. Run dead scripts first (their pending restores) with a total budget 4000 ms, of which 1000 reserved to kill the session of an expired one; only files that are regular, not links and owned by shell or the service's own user are executed. A counter in .tentativi, written before running, stops retries: after MAX_TENTATIVI (3) failed starts the script is no longer executed and stays on the phone with the user's restores inside.
  6. Then delete the script and accessories, then the old jars; a jar cited by a script that is left behind stays, because the script's command (app_process ... it.yasde.Pannello accendi) needs it.

This must finish before PRONTO, which the PC waits for only a short time, hence the budget. The PC side removes its own jar when start-up fails (6.1 “Starting the component on the phone”).

6.7 · What happens when the service dies

What happens depends on how the service ends.

CauseServicePhonePC
PC closes YASDEgets CHIUDI, runs close actions and restores, deletes jaras beforeorderly
PC silent (no signs of life)keeps runningafter 30 minutes without signs of life the panel and the wake lock are released but service and sessions stay10.7 “Signs of life and PC absence”
Command channel or stdin closesshuts down by itself, restoresas beforelink goes to PERSO
SIGHUP, SIGTERMshutdown hook: close without exit; the guardian is the netas beforelink goes to PERSO
kill -9 of the servicegoneguardian reads end-of-file and runs the list, then removes fileslink goes to PERSO, reconnects with a new jar
adbd restartedservice and guardian both goneleftovers stay until the next startreconnects; the new service cleans (6.6 “Cleaning up leftovers at start-up”)
Table 6.6 — How the service ends
Chapter 7

The protocol

7.1 · Channels

The protocol between the PC and the component is described in docs/protocollo.md, which is the contract between src/componente (PC, C) and telefono/ (phone, Java). Whoever finds it wrong or incomplete does not change it alone: the problem is reported to whoever coordinates. This chapter reorganises that document for reading; the version is 1 (PH_PROTOCOLLO_VERSIONE, Protocollo.VERSIONE).

All the channels are ADB channels of the service localabstract:yasde. Immediately after opening one, the PC writes a line of ASCII text ended by a newline that names the channel type. The service accepts lines of at most 64 characters (5 s to arrive).

LineChannelHow manyDirection
comandirequests and answers, eventsoneboth
video:<id>H.264 packets of the session (decimal)one per sessionphone to PC
inputmouse and keyboard eventsonePC to phone
audioOpus packetsone (a second is closed)phone to PC
cercasearch of files and foldersone per searchboth
appuntishared clipboardoneboth
Table 7.1 — Channel types

An unknown type makes the service close the channel. The service runs as uid 2000 and, at the end (command channel closed, or shell closed), closes every session, runs the restores and deletes the jar.

7.2 · Message format

On comandi and input every message has the same shape. All numbers are big endian; a stringa is a 2-byte length followed by UTF-8 with no terminator.

FieldSizeNotes
type1 bytesee the tables below
length4 bytesbody length only; at most 1 MiB (PH_MSG_MAX_CORPO, Protocollo.MAX_CORPO)
bodylength bytesdepends on the type
Table 7.2 — Message header

On comandi the PC sends one request at a time and waits for the answer, OK (possibly with a body) or ERRORE. Events (phone to PC) may arrive at any moment, even between a request and its answer, and are recognised by their type. Two channels have a different layout: video:<id> (8.4 “Video: receiving and decoding”) and audio (9.1 “Audio: capture and transport”). The clipboard messages carry the text as a 32-bit length plus UTF-8, not as a stringa.

WriterReader
ph_msg_inizia, ph_msg_u8, ph_msg_u16, ph_msg_i16, ph_msg_u32, ph_msg_stringa, ph_msg_finisci (writes the provisional length, then corrects it)PhLettore with ph_leggi_u8..ph_leggi_u64 and ph_leggi_stringa: a cursor that never leaves the buffer; after a short body rotto stays true and reads return 0
Protocollo.scrivi, Protocollo.scriviStringa, Protocollo.corpoErroreProtocollo.leggi: refuses a length above the maximum
Table 7.3 — The codecs on the two sides
i
Note. Any message the phone receives from the PC on comandi counts as a sign of life (10.7 “Signs of life and PC absence”).

7.3 · Message types

Types by range. Direction: PC→T is a request or command from the PC to the phone, T→PC is an answer or event.

TypeNameDirectionBody
General (0x01–0x0f), on comandi
0x01SALUTOPC→Tu16 protocol version. Answer OK: u16 version, u16 API level, u16 width, u16 height, u16 dpi, stringa model. A different version is ERRORE
0x02OKT→PCdepends on the request; empty if not said
0x03ERRORET→PCstringa a sentence in Italian (shown to the user only after translation or kept to the log); unknown type: tipo sconosciuto
0x04CHIUDIPC→Tempty; the service answers OK and then restores everything and ends
0x05PRESENZAPC→Tempty; answer OK empty. “The PC is alive”
Video (0x40–0x4f), on comandi
0x40VIDEO_APRIPC→Tu32 id, u16 width, u16 height, u16 dpi, u32 bits per second, u8 fps, stringa app package (empty = mirror of the real screen)
0x41VIDEO_CHIUDIPC→Tu32 id, u8 remove_task (1 = remove the app from recents)
0x42VIDEO_RIDIMENSIONAPC→Tu32 id, u16 width, u16 height, u16 dpi. Answer OK: u16 width, u16 height actually applied
0x43VIDEO_CHIAVEPC→Tu32 id: ask for a key frame now
0x44VIDEO_PAUSAPC→Tu32 id
0x45VIDEO_RIPRENDIPC→Tu32 id
0x48VIDEO_EVENTOT→PC eventu32 id, u8 what, u16 a, u16 b
Input (0x50–0x55), on input, PC to phone only, no answer
0x50TOCCOPC→Tu32 id, u16 width, u16 height, u8 action (0 down, 1 move, 2 up, 3 cancel), u16 x, u16 y, u8 buttons (bit 0 left, 1 right, 2 middle; sent by the PC, not read by the phone in this version)
0x51ROTELLAPC→Tu32 id, u16 width, u16 height, u16 x, u16 y, i16 horizontal, i16 vertical (in 120ths of a notch)
0x52TASTOPC→Tu32 id, u8 action (0 down, 1 up), u32 Android key code (KeyEvent.KEYCODE_*), u32 modifier state (KeyEvent.META_*)
0x53TESTOPC→Tu32 id, stringa text to insert
0x54INDIETROPC→Tu32 id: the Back key (down and up)
0x55PIZZICOPC→Tu32 id, u16 width, u16 height, u8 phase (0 start, 1 continue, 2 end, 3 cancel), u16 x, u16 y, i16 step (120ths of a notch, positive = zoom in, −1200..1200)
Clipboard (0x58–0x5a), on appunti
0x58APPUNTI_TESTOT→PCthe text just copied on the phone
0x59APPUNTI_IMPOSTAPC→Tthe text to put in the phone's clipboard
0x5aAPPUNTI_INCOLLAPC→Tu32 video session id, then the text; puts it in the clipboard and sends “paste” to the app of that session
Panel (0x60–0x6f), on comandi
0x60PANNELLO_IMPOSTAPC→Tu8 0 = off, 1 = on
0x61PANNELLO_STATOPC→Tempty. Answer OK: u8 on, u8 in hand
0x6ePANNELLO_EVENTOT→PC eventu8 on, u8 reason (1 user, 2 call, 3 call ended, 4 asked by PC, 5 restore at close, 6 PC absent 30 min)
Phone data (0x70–0x7f), on comandi unless noted
0x70APP_ELENCOPC→Tempty. Answer: u16 count, then per app stringa package, stringa shown name, u8 flags (bit 0 system app, bit 1 portrait only)
0x71APP_ICONAPC→Tstringa package, u16 side in pixels (16–512). Answer: the bytes of a square PNG
0x72STATOPC→Tempty. Answer: u8 battery 0–100, u8 charging, u8 network (0 none, 1 Wi-Fi, 2 cellular), u8 signal 0–4, u8 screen locked
0x73NOTIFICHEPC→Tempty. Answer: u16 count, then per notification stringa key, package, title, text, u64 time (ms since 1970)
0x74MINIATURAPC→Tstringa file path, u16 maximum side (32–512). Answer: the bytes of a JPEG
0x75MEMORIAPC→Tempty. Answer: u64 total bytes, u64 free bytes of internal storage
0x76MEMORIA_DETTAGLIOPC→Tempty. Answer: u64 bytes of images, video, audio, apps (code and data, cache included); unreadable = 0xFFFFFFFFFFFFFFFF
0x77CALENDARIOPC→Tu8 maximum (1–16). Answer: u16 count, per event stringa title, u64 start, u64 end, u8 all-day
0x78CERCAPC→Ton cerca: stringa start folder, stringa text, u8 folders only, u16 maximum results
0x79TROVATOT→PCon cerca: stringa full path, u8 is a folder
0x7aCERCA_FINET→PCon cerca: u8 reason (0 finished, 1 maximum reached, 2 error)
0x7bCALENDARIO_INTERVALLOPC→Tu64 from, u64 to (at most 62 days), u16 maximum (1–500). Answer: u8 truncated, stringa package of the default calendar app, then count and events as in CALENDARIO
0x7cSVEGLIAPC→Tempty. Answer: u8 there is one, u64 time, stringa package that set it
0x7dBATTERIAPC→Tempty. Answer: u8 level, u8 status, u8 power source bits, i16 temperature in tenths of °C (0x7fff unknown), u8 health, u16 millivolts, i32 minutes to full, i32 minutes of estimated autonomy (−1 unknown)
0x7eSTATO_CAMBIATOT→PC eventas the answer of STATO
0x7fNOTIFICHE_CAMBIATET→PC eventempty: the PC asks NOTIFICHE again
Quick controls (0x80–0x8f), on comandi
0x80CONTROLLI_STATOPC→Tempty. Answer: u8 ringer (0 ring, 1 vibrate, 2 silent, 0xff n/a), u8 Do Not Disturb, u8 torch, u8 find in progress, u8 possible commands (bit 0 ringer, 1 DND, 2 torch, 3 find)
0x81SUONERIA_IMPOSTAPC→Tu8 mode
0x82NON_DISTURBARE_IMPOSTAPC→Tu8 0 off, 1 on (priority only)
0x83TORCIA_IMPOSTAPC→Tu8 0 off, 1 on
0x84TROVA_AVVIAPC→Tu16 maximum seconds; in this version always ERRORE without touching anything
0x85TROVA_FERMAPC→Tempty; in this version OK doing nothing
0x8eCONTROLLI_CAMBIATIT→PC eventas the answer of CONTROLLI_STATO
Approximate position (0x90–0x9f), on comandi
0x90POSIZIONEPC→Tu8 search allowed. Answer: u8 outcome (0 known, 1 location off, 2 permission denied, 3 none known), i32 latitude and i32 longitude in thousandths of a degree, always multiples of 5, u32 age in seconds (0xffffffff unknown), u8 provider (0 network, 1 gps, 2 fused, 3 passive), stringa place name, u8 search started. The body is exactly 17 + n bytes
Table 7.4 — All message types
i
Note. Types 0x46-0x47 are reserved (freeing the encoder in long pauses: +0.07 s at resume; added only if a measurement asks). The sizes of video and audio packets are given in their chapters. Details of video, input, clipboard and panel are in chapters 8, 9 and 10; those of files, notifications and weather in chapters 11, 13 and 15.

7.4 · Errors and malformed input

Every request that fails answers ERRORE with one sentence. The PC turns it into a PhErrore. The cases to know:

CaseResult
Unknown typeERRORE “tipo sconosciuto”. The PC maps it to “old service version” (ph_componente_richiesta)
Malformed bodyERRORE with the exception's message, or “malformed request” if it has none
Different protocol versionERRORE on SALUTO
Body longer than 1 MiBthe PC ends the command thread and the component is dead; the phone's reader refuses it
Answer after the PC gave updiscarded by the PC; the PC already considers the component dead after a timeout
Event type not registered on the PCignored
Unknown type on inputignored: that channel has no answers, so there is no visible error
Table 7.5 — Errors
!
Warning. A timed-out request kills the component on the PC side by design: an answer that came late would otherwise be taken for the answer to the next request. The link then goes to PERSO and reconnects.
Chapter 8

Video

8.1 · Video on the phone: virtual displays and the encoder

Each window of a phone app is a video session. On the phone a session is a virtual display, an H.264 hardware encoder fed by it, and the app launched on that display. The code is in telefono/video: Video (commands and the channel), Sessione (one session), Codificatore (the encoder), ControlloSchermi (protected windows) and NascosteVideo (hidden APIs).

ClassRole
Videoregisters commands 0x40-0x4f, the channel video and a close action; keeps the map id → session
Sessionevirtual display, encoder, app launch, guard thread, pause, resize, close
Codificatoreone MediaCodec H.264 encoder with its input surface and the thread that reads packets
Inoltroturns encoder output into protocol packets and keeps the configuration aside until a channel exists
ControlloSchermione thread for all sessions: a window dump every second to detect protected screens
AnalisiFinestrepure parser of that dump
LiberaTaskremoves the tasks of a display and waits for it to empty
Specchioreal screen size, to bring the input of a mirror session to the real display
InputIniettore, Gesti, Pizzico: input injection (chapter 10)
Table 8.1 — Classes of telefono/video

Checks on VIDEO_APRI. Width and height must be multiples of 8 between 64 and 2560; dpi between 40 and 1000; bit rate between 100000 and 200000000; the package, if present, must match [A-Za-z0-9_.]{1,255}; the id must be unused in this connection. An fps outside 1..120 becomes 60. Anything else answers ERRORE.

The session is created in Sessione.apri in this order: resolve the app, create the encoder, create the virtual display on the encoder's surface, launch the app. A failure at any step releases what was already made.

  1. Resolve the launcher activity with the PackageManager (ACTION_MAIN + CATEGORY_LAUNCHER, restricted to the package; no implicit resolution). The class name must match a safe pattern and the package must be the one asked.
  2. Encoder. Codificatore.crea tries, in order: every hardware H.264 encoder with SPS/PPS prepended to key frames, then every hardware encoder without, then Android's default encoder. The last error goes in the message. Format: surface input, the requested bit rate and frame rate, key frame interval 10 s, priority 0 (real time), KEY_REPEAT_PREVIOUS_FRAME_AFTER 100000 µs (without it many encoders emit nothing on a still screen).
  3. Virtual display. DisplayManager.createVirtualDisplay is tried with sets of flags from the richest to the simplest and the first accepted wins. For an app, four sets: public + own-content-only + touch + destroy-with-content + trusted + own group + always unlocked; the same without always-unlocked; public + own-content-only + touch + destroy-with-content; and the last without public. For the mirror: mirror + public, mirror, mirror + own-content-only. The flags used are logged.
  4. Launch with am start-activity --display <id> -n <component> -f 0x18000000 (new task + clear task), 10 s limit; output containing Error or “Activity not started” fails the open.
  5. Guard. A thread checks every second that the app is still on the display; after it has been seen and then found missing twice in a row it sends the event VIDEO_EVENTO 1 (the app closed by itself; the session stays to be closed by the PC).
Event che cosaMeaninga, b
1the app closed itself0, 0
2protected screen on or off (FLAG_SECURE)a = 1 or 0
3the size changed on its own: defined by the protocol, never sent by this version of the phone codea × b
4encoder error: the session is dead0, 0
Table 8.2 — VIDEO_EVENTO kinds

The protected-screen state is computed once per second for all sessions at once by one dumpsys window analysis (each dump holds the WindowManager lock, so there must be only one); the event goes out only when the state changes.

8.2 · Video: sessions and recovery

A session starts on the shell side as a stream, SvFlusso in src/shell/ossatura/sv_flussi.c. It holds the PhVideoFlusso of the component, the decoder and the capture state. Opening, pause, resize and close run in order on the p_flussi pool; input on p_input; the reading thread is the one that calls sv_flusso_leggi.

windowshell streamPCcomponentephoneSessionesv_flusso_apri: 8 Mbit/s, 60 fpsVIDEO_APRI id, size, dpi, packageOK: session existsopen channel video:<id>CONFIGURAZIONE (SPS+PPS)key frame, then FOTOGRAMMIdecoded framespause, resize, key frame requests, eventscloseVIDEO_CHIUDI id, remove_taskFigure 8.1 — The life of a video session
  • Request. VIDEO_BIT_AL_SECONDO is 8000000 and VIDEO_FPS is 60. The size and density come from the window; with a density of 0 the session's own density is used, or 420 if unknown. For the mirror the size is the real screen's, scaled so that no side exceeds 1920 pixels, with sides rounded down to a multiple of 8 and at least 64 (ph_ossatura_misura_specchio).
  • Component. ph_video_apri assigns the id (an increasing counter, never reused in the connection), sends VIDEO_APRI, and on OK opens the channel video:<id>. If anything fails after the phone created the session, VIDEO_CHIUDI is sent (2000 ms) so that no virtual display is left on. The encoder starts producing when the channel opens; before that its packets are discarded and the configuration is kept aside.
  • Open job. It makes up to 3 rounds, repeated only when the session vanishes and a new one appears meanwhile; with no session the stream goes to PERSO and waits.
  • Rule of use. Whoever calls ph_video_* on a stream holds one use of the stream and of the session; whoever replaces or closes it removes the pointer first and waits for the uses to reach zero, so no call starts after ph_video_chiudi and no read runs while the stream closes.
Stream stateEntered whenLeaves when
PH_FL_APRENDOsession created or connection backopen succeeded (ATTIVO), no session (PERSO), refused (MORTO)
PH_FL_ATTIVOopen succeeded; notice APERTO the first time, RIPRESO latersession lost (PERSO), encoder error (MORTO)
PH_FL_PERSOthe link's session was losta new session exists: reopen by itself
PH_FL_MORTOthe phone refused to open, or the encoder died (event 4)never: it does not restart
Table 8.3 — Stream states (ph_fl_passo, src/shell/ossatura/logica.c)

On a drop every stream becomes PERSO, its pinch and touch are cancelled, and a running recording is stopped with “connection lost”. On the new session sv_flussi_sessione_nuova reopens every stream; the pause the shell wanted and any resize asked while the stream was absent are reapplied.

8.3 · Pause, resize and density

Pause turns a minimised window into a stream that costs nothing. The phone detaches the encoder surface from the virtual display (VirtualDisplay.setSurface(null)), so the display, the app and the encoder stay alive but no frames are produced. Measured on the test phone: resume in 0.12–0.17 s, with the phone's compositor idle during the pause and the app still alive.

  • VIDEO_PAUSA: already paused is OK with no effect; resize and key-frame requests in pause are ERRORE; input does not error but has no effect (measured: with a detached surface Android does not deliver it to the app), so the PC sends none to a paused session and, before pausing, closes every touch and pinch in progress (up or cancel). Open gestures are also closed on the phone before the surface is detached, since afterwards the cancel would be lost.
  • VIDEO_RIPRENDI: re-attaches the surface and asks for a key frame; if none arrives within about 250 ms (a still app: 12 checks of 20 ms) a redraw is forced by detaching and attaching the surface again. The first packet written after the OK is a key frame, preceded by a configuration if needed. Packets written before the pause and not yet read may still arrive after the resume.
  • VIDEO_RIDIMENSIONA: the phone creates a new encoder, resizes the display and sets the new surface, then swaps; from then no packet with the old size is written (the filter drops packets of an encoder that is no longer the current one). The first packet with the new size is a configuration. To resize a paused stream the PC resumes it first.
  • Mirror. The shell never resizes the mirror: the request is ignored for sessions with an empty package. Resize requests received while paused or while the stream is absent are remembered (size and density) and applied by the resume or the reopen.
  • Density. The density is part of the resize request, so a window can change the app's layout class without restarting it: this is the protocol side of the density rule described in chapter 12.
  • Barrier. Pause and resize run on the streams pool and first wait (bounded) for the inputs queued before them to have been sent, so a touch is never overtaken by a pause or a resize.

8.4 · Video: receiving and decoding

The channel video:<id> carries phone-to-PC packets only. The PC never writes on it; if it closes it, the encoder stops (the session lives until VIDEO_CHIUDI). A second channel for the same session closes the first (shutdown of output and input).

FieldSizeNotes
kind1 byte1 = CONFIGURAZIONE (SPS+PPS), 2 = FOTOGRAMMA; any other value breaks the stream
flags1 bytebit 0 = key frame
width2 bytessize of the video the packet belongs to
height2 bytes
time8 bytesmicroseconds, phone monotonic clock (presentationTimeUs)
length4 bytesat most 8 MiB (PH_VIDEO_MAX_PACCHETTO)
datalengthH.264, Annex B (start codes 00 00 00 01)
Table 8.4 — Video packet (18-byte header)

After the channel is opened the first packet is a configuration and the second a key frame. ph_video_leggi(stream, packet, timeout, error) returns 1 for a packet, 0 for end of stream, PH_CANALE_ERRORE or PH_CANALE_TEMPO. Reads are in 50 ms slices and are resumable (a slice that expires loses nothing). The data buffer grows in pieces of 256 KiB, so a false length does not allocate everything at once; a half packet at the end is a broken stream. The data pointer is valid until the next read.

Decoding is src/video/decodifica.c, on FFmpeg's libavcodec. The via is chosen when the decoder is created (ph_decodifica_crea).

ViaWhenNotes
PH_VIA_VAAPIautomatic, first choiceFFmpeg VA-API hardware device; hands the frame to the shell without copies (DMA-BUF)
PH_VIA_VULKANautomatic, only if VA-API is missing or fails and any non-CPU Vulkan device offers VK_KHR_video_decode_h264 as shippeddetected without environment variables: a function the driver keeps off does not count; CPU-type Vulkan devices are ignored; the frame is copied to memory (PH_ESPORTA_RIPIEGO)
PH_VIA_SOFTWARElast resort, or when GTK refuses the DMA-BUFslice threads, thread count automatic
Table 8.5 — Decoding vias (automatic order: VA-API, then Vulkan Video if the driver offers it, then software; the order is a pure function, ph_decodifica_ordine_automatico, proved without a graphics card)

The decoder is created with AV_CODEC_FLAG_LOW_DELAY and AV_CODEC_FLAG2_FAST (no frame held back for reordering). For the hardware vias extra_hw_frames is 6: the shell keeps some frames alive beyond the decoder's life (the one shown, the one waiting, one being delivered), and without extra surfaces the GPU's fixed pool would run out and decoding would stop. An explicit via fails if it is not available, with no silent fallback (this is for measuring); get_format records when FFmpeg dropped to software (at the first packet, or at the first packet after a new configuration, for example a resize), and ph_decodifica_dai then returns an error on any hardware via, the automatic one included (the check is on the via, not on whether it was explicit); the shell reacts by recreating the decoder as software, once (8.7 “When hardware decoding is not available”).

Feeding. A configuration packet is kept and prepended to the next frame (a configuration alone is not a frame). Packets are sent with the phone's time as pts and dts. A damaged packet is not fatal: the call fails and decoding continues from the next key frame; the reader then asks for a key frame, at most every 500 ms, because the picture stays broken until the next one (up to 10 s at the encoder's interval). The last configuration (at most 64 KiB) is stored and given to every new decoder, since an encoder that does not prepend headers would leave a new decoder without them.

To the shell without copies. ph_esporta (src/video/esporta.c) turns the AVFrame into a PhFotogramma, described in src/comune/fotogramma.h without FFmpeg or GTK types. The frame belongs to the receiver, which must call ph_fotogramma_rilascia exactly once, from any thread, when the picture is not needed (typically in the release function of the GdkTexture); until then file descriptors and data are valid.

ViaFormWhat happens
PH_ESPORTA_DMABUFPH_FOTO_DMABUFVA-API frame mapped to DMA-BUF: fourcc and modifier from the DRM descriptor, planes, offsets and strides; GTK shows it as a texture without any copy
PH_ESPORTA_MEMORIAPH_FOTO_MEMORIAframe already in memory (BGRA, RGBA, RGB24 with positive stride: not copied) or the needed YUV to RGB conversion only; format B8G8R8A8_PREMOLT normally
PH_ESPORTA_RIPIEGOPH_FOTO_MEMORIAa GPU frame that could not be mapped (Vulkan, or VA-API refused) was copied to memory; the shell writes it in the decision log once per stream
Table 8.6 — Export forms

Colours: BT.709 or BT.601 according to what the frame declares (undeclared: BT.709 from 720 rows up, BT.601 below), limited range unless declared; full range maps to the PIENO variants; other matrices leave the choice to GTK. An offset or stride above 32 bits is an error. In the shell, sv_flusso_memoria can force the software decoder when GTK refuses the DMA-BUF, which is logged (flusso in memoria invece che DMA-BUF) and asks for a key frame.

!
Warning. Direct hand-off of the video to the screen (offload) and rounded window corners are open points. Which via a given machine really uses is visible only in the decision log and was measured on one machine only.

8.5 · Hardware acceleration end to end

This section follows one video frame from the phone's encoder to the screen and says, at every stage, who does the work (GPU or CPU) and where the data is copied. It comes from the sources; what was measured, and where, is in 8.9 “Requirements and limits of hardware acceleration”.

Phone encoderMediaCodec H.264ADB channelAnnex B packetsFFmpeg decodeVA-API, Vulkan, CPUph_esportaPhFotogrammaGTK textureDMA-BUF or memoryGTK rendererchosen by GTKFigure 8.2 — The video chain, stage by stage
StageCodeWho worksWhat is copied
1. Encodetelefono/video/it/yasde/Codificatore.javathe phone's H.264 encoder, hardware if one is foundthe virtual display renders into the encoder's input surface: no copy made by YASDE code
2. Transportsrc/componente/video.c, src/adbCPU (TLS, ADB)each packet is read into the stream buffer (up to 8 MiB, grown in 256 KiB pieces); the decoder receives a copy of it with the stored configuration in front
3. Decodesrc/video/decodifica.cGPU with VA-API or Vulkan; CPU with the software viahardware: nothing, the picture stays in GPU memory (AV_PIX_FMT_VAAPI or AV_PIX_FMT_VULKAN); software: the picture is written in system memory
4. Exportsrc/video/esporta.csee the table of paths belowDMA-BUF: nothing; memory form: for a GPU frame a GPU-to-CPU download, then a CPU colour conversion into a new buffer
5. Texturesrc/shell/superficie/superficie.cGTK, on the GTK threadDMA-BUF: the file descriptors are handed to GTK; memory: the buffer is wrapped in a GBytes without a copy, and GTK uploads it to the GPU by itself
6. DrawGtkGraphicsOffload and the renderer GTK has chosenGPU, with the GL or Vulkan renderer GTK chooseswhat GTK does internally with a DMA-BUF (colour conversion, a direct hand-off to the screen) is up to GTK and not controlled by YASDE (see below)
Table 8.7 — The stages of the chain

1. Encoding on the phone. Codificatore.crea lists the encoders of MediaCodecList(REGULAR_CODECS) that are encoders, are not aliases, report isHardwareAccelerated() and not isSoftwareOnly(), and support video/avc, and tries them in the list's order: first each with prepend-sps-pps-to-idr-frames set to 1, then each without it, and last Android's default encoder for the type (createEncoderByType), which the code does not check to be hardware: it may be a software encoder. The format asks for surface input, the bit rate and frame rate of the request (the shell asks for 8000000 and 60), a key frame every 10 s, priority 0 and repeat-previous-frame after 100000 µs. Profile, level and bit-rate mode are not set: the encoder's own defaults apply. If no encoder can be configured the open fails with codificatore H.264 non configurabile and the last error, the phone answers ERRORE to VIDEO_APRI, and the stream goes to PH_FL_MORTO with the notice “This app's video has stopped”. The name of the chosen encoder is printed only by the test class ProvaVideo: in a normal run it is not logged, and the service's log lines are read by the PC and thrown away.

3. Decoding. prova_via (src/video/decodifica.c) uses FFmpeg's h264 decoder with AV_CODEC_FLAG_LOW_DELAY and AV_CODEC_FLAG2_FAST. For a hardware via it opens the device with av_hwdevice_ctx_create(type, NULL, NULL, 0) (type AV_HWDEVICE_TYPE_VAAPI or AV_HWDEVICE_TYPE_VULKAN: the code names no device, FFmpeg picks the default one), gives it to the codec context as hw_device_ctx, installs get_format that accepts only the via's own pixel format (AV_PIX_FMT_VAAPI or AV_PIX_FMT_VULKAN), and sets extra_hw_frames to 6 (reason in 8.4 “Video: receiving and decoding”). The hardware decoders are the FFmpeg hwaccels h264_vaapi and h264_vulkan compiled into the packaged FFmpeg (pacchetto/dentro.sh). The software via uses slice threading with an automatic thread count. A configuration packet is kept and put in front of the next frame.

4. Export. ph_esporta takes the AVFrame (it becomes the function's in every case) and returns one of three forms. Their conditions, in the order the code tests them:

ConditionFormStepsCopies per frame
the frame is not in GPU memory (no hw_frames_ctx)PH_ESPORTA_MEMORIABGRA, RGBA or RGB24 with a positive stride are wrapped as they are; any other format (the normal case, YUV from the software decoder) is converted by libswscale (SWS_BICUBIC | SWS_ACCURATE_RND) into a new BGRA buffer, with the matrix and range of the frame0 if already RGB, otherwise 1 conversion on the CPU
VA-API frame and av_hwframe_map to AV_PIX_FMT_DRM_PRIME succeedsPH_ESPORTA_DMABUFthe DRM descriptor gives the file descriptors, offsets, strides, modifier and fourcc; the mapped frame keeps the picture alive until GTK releases the texture0
a GPU frame that is not VA-API (Vulkan), or whose mapping was refusedPH_ESPORTA_RIPIEGOav_hwframe_transfer_data brings the picture to system memory, then the same conversion as above1 download GPU to CPU plus 1 CPU conversion
Table 8.8 — The forms of ph_esporta

In PH_ESPORTA_DMABUF the fourcc is the layer's format when there is one layer, or NV12 or P010 (from the frame's software format) for multi-layer descriptors; at most 4 planes; all planes must have the same modifier or the export fails; sizes up to 16384. In the PH_ESPORTA_RIPIEGO case the shell writes one decision line per stream (8.8 “Checking which path is in use”).

5. The texture (texture_da, 11.7 “The video surface”). For a memory frame: gdk_memory_texture_new with the format GDK_MEMORY_B8G8R8A8_PREMULTIPLIED, R8G8B8A8 or R8G8B8. For a DMA-BUF: GdkDmabufTextureBuilder with the fourcc, modifier, planes, offsets and strides of the frame. Before the first DMA-BUF the surface asks GTK for its list of importable formats (gdk_display_get_dmabuf_formats); if the pair fourcc and modifier is not in it, it logs a line and tries anyway. If the builder returns no texture (its error is discarded) the frame is dropped and counted as a refusal, which has consequences described in 8.7 “When hardware decoding is not available”. For a DMA-BUF texture only (memory textures are already BGRA, with the matrix applied by libswscale in the export), the colour state is given only if the program was compiled against GTK 4.16 or newer: BT.709 or BT.601 (CICP primaries, transfer and matrix 1/1/1 or 6/6/6) with narrow or full range, from what the frame declares or the height rule; for any other matrix, or if GTK does not build the colour state (one log line), GTK decides.

6. Drawing. The picture is a GtkPicture-like widget (PhImmagine) inside a GtkGraphicsOffload with offload enabled (and, from GTK 4.16, a black background). The widget appends a plain texture node because GTK 4.18 does not offload a scaled-texture node. The program never sets the renderer: GTK chooses it, and the AppRun script does not touch GSK_RENDERER. Only the development scripts set it (strumenti/app-sul-tablet.sh defaults to vulkan and sets GDK_DEBUG=offload; strumenti/foto-demo.sh uses cairo).

PathDecoderExport formCopies per frameWho draws
VA-API (first choice)GPU, VA-APIPH_ESPORTA_DMABUFnone: DMA-BUF handed to GTKGTK's renderer, chosen by GTK (on the GPU with the GL or Vulkan renderer); what GTK does internally, YUV conversion included, is not controlled by YASDE
VA-API, mapping refusedGPU, VA-APIPH_ESPORTA_RIPIEGO1 download, 1 CPU conversion, then GTK's uploadGTK's renderer, chosen by GTK, with a memory texture
Vulkan Video (only if offered as shipped and VA-API did not open)GPU, VulkanPH_ESPORTA_RIPIEGO1 download, 1 CPU conversion, then GTK's uploadGTK's renderer, chosen by GTK, with a memory texture
Software (nothing else opened)CPU, libavcodecPH_ESPORTA_MEMORIA1 CPU conversion, then GTK's uploadGTK's renderer, chosen by GTK, with a memory texture
Software after a DMA-BUF refusalCPU, libavcodecPH_ESPORTA_MEMORIA1 CPU conversion, then GTK's uploadGTK's renderer, chosen by GTK, with a memory texture
Table 8.9 — Path, decoder, export form, copies, who draws

The “then GTK's upload” part is GTK's own work with a memory texture and is not visible in the code of YASDE; the table counts only what the code of the project does.

8.6 · How the decoding path is chosen and when it falls back

The automatic order and the checks are in src/video/decodifica.c. The order is the pure function ph_decodifica_ordine_automatico(vulkan_di_fabbrica, sequence): VA-API first; Vulkan second only if vulkan_di_fabbrica is true; software always last. It is proved without a graphics card by src/video/prova/prova_ordine_via.c. ph_decodifica_crea(PH_VIA_AUTOMATICA) tries each in order with prova_via and takes the first that opens; only the last attempt fills the error text, so the reasons why VA-API or Vulkan did not open are lost. Reason for VA-API first: it hands the frame to the shell without copies, and the Vulkan via copies it (the choice of the project's owner, “route A”).

What ph_decodifica_vulkan_di_fabbrica looks at. It creates a Vulkan instance (API 1.3, no layers, no extensions), lists the physical devices, skips every device of type CPU, and returns true if any other device lists the extension VK_KHR_video_decode_h264. It reads no environment variable, so a function the driver keeps switched off does not count. It does not look at queue families or video capabilities. If the instance cannot be created it returns false. It runs every time an automatic decoder is created.

What makes a hardware via fail to open. Only two checks exist: av_hwdevice_ctx_create returning an error (the error text reads “via vaapi: accelerazione non disponibile: ”) and avcodec_open2 returning an error. Why FFmpeg refuses (no render device, no driver, a library not found) is not distinguished by the code, and the text of those errors is lost; the program reports only the outcome (8.7 “When hardware decoding is not available”).

The one thing the code does not turn into a failure. The hardware format is accepted only if FFmpeg offers it in get_format. If the device opened but the GPU cannot decode this stream (for example an unsupported profile), the callback sets ripiego_software and lets FFmpeg take its default, which is its own software decoding. This is the third case below.

Device lost in mid-session. There is no code for it. FFmpeg errors come back from ph_decodifica_dai or ph_decodifica_prendi as -1; the reader asks for a key frame at most every 500 ms and nothing else happens: the decoder object is replaced only when the stream is reopened (new session after a drop), when GTK refuses the DMA-BUF, or when a hardware decoder drops to software at its first packet or after a new configuration, which also recreates the decoder (8.7 “When hardware decoding is not available”); a device lost later is none of these. What the picture does then depends on FFmpeg and the driver and has not been tried.

Going back to hardware. A new decoder repeats the whole automatic order, hardware attempts included, so hardware is tried again whenever a stream is opened or reopened after a drop, never in the middle of a stream.

8.7 · When hardware decoding is not available

What the user sees: in all three cases a decision line is written on standard error and, at most once per link session, a toast appears on screen (8.8 “Checking which path is in use”). All three go through via_verifica (src/shell/ossatura/sv_flussi.c), which asks ph_decodifica_via for the via the decoder REALLY uses (ph_via_reale: the chosen via, or software if FFmpeg dropped to software) after the decoder is created and after every packet given to it. It writes one line per stream and per change of via. When the via is software the cause in the line comes from three facts, tested in this order: the stream's memory preference is set and the decoder is the software one (memoria and dec_software) means GTK refused the DMA-BUF; else a decoder that was born with a hardware via (dec_nato_hw) means the hardware via cannot sustain the stream; else no hardware via was available.

The toast. When the via becomes software, via_verifica calls ph_servizi_pubblica_decodifica_software (any thread), which delivers PH_SRV_EV_DECODIFICA on the GTK thread; src/shell/sistema/sistema.c shows it with ph_sistema_toast_info_lungo, title Decodifica video hardware non disponibile (“Hardware video decoding unavailable”) and body Il video usa il processore: le app sono meno fluide. Installa i driver video VA-API o Vulkan. (“Video uses the CPU: apps are less smooth. Install VA-API or Vulkan video drivers.”). It stays 9 s (DURATA_INFO_LUNGO_MS in toast.c); the other information toasts stay 3.2 s, notification toasts 5.2 s. It is sent at most ONCE per link session (sv->decod_sw_sess holds the last session that got it): not per frame, not per window, not at every re-creation of the decoder, and if a stream goes back to hardware and falls again in the same session it is not repeated. A new session after a drop can show it again. Proved by src/shell/ossatura/prova_decodifica_avviso.c; a screenshot is docs/sources/img/decoding-warning.png.

Case 1: no hardware via opens

  • Trigger. In the automatic order VA-API and, if offered, Vulkan both fail the two checks above (missing decoding drivers, a virtual machine, a card with neither VA-API nor Vulkan Video, or a missing device).
  • Steps. ph_decodifica_crea reaches the software via, prova_via opens the h264 decoder with slice threads and an automatic thread count, and the decoder is created normally. Right after, via_verifica sees software with no via logged yet for the stream.
  • Log. [decisione] hh:mm:ss.mmm decodifica col processore - causa: nessuna via hardware disponibile: prestazioni ridotte (“decoding with the processor - cause: no hardware via available: reduced performance”): the decoder was not born with a hardware via and GTK has refused nothing. The toast follows. The failed hardware attempts themselves write nothing (only the last attempt fills the error text). Only if even the software decoder cannot be created: decodifica non disponibile - il decodificatore non si e' creato (“decoding not available - the decoder was not created”), once per change of state, and on recovery decodifica di nuovo disponibile - il decodificatore si e' creato (“decoding available again”).
  • Cost. The H.264 decoding is done by the CPU, then each frame goes through a YUV to BGRA conversion on the CPU (PH_ESPORTA_MEMORIA) and GTK's upload. No figure for software decoding is recorded anywhere in the project: not measured. The tool misura_decodifica can measure it on a given machine.
  • Back to hardware. At the next decoder creation (stream opened or reopened), when the automatic order runs again; if hardware opens then, the line decodifica video - causa: via vaapi (scheda grafica) is written (the via changed).

Case 2: the GPU decodes but GTK refuses the DMA-BUF

  • Trigger. The surface cannot build a DMA-BUF texture: gdk_dmabuf_texture_builder_build returns NULL for a frame of DMA-BUF form (the error is discarded).
  • Steps. (1) That frame is dropped and counted in the statistics as discarded and as a DMA-BUF refusal. (2) ph_srv_flusso_preferisci_memoria reaches sv_flusso_memoria, which sets the atomic flag memoria of that stream; it is called on every refusal, not once. (3) At the next read leggi_uno sees the flag with dec_software still false and calls decodificatore_nuovo(sv, sf, vf, true): this is where the software parameter comes from. It is not a preference, a command-line option or an environment variable: it is the flag of the stream, set only by a refusal of GTK. (4) The old decoder is freed, a software decoder is created, the stored configuration is given to it, a key frame is requested from the phone with ph_video_chiave, and via_verifica runs.
  • Log. From the surface, once per surface: [decisione] hh:mm:ss.mmm flusso in memoria invece che DMA-BUF - causa: GTK ha rifiutato il DMA-BUF (fourcc NV12, modificatore 0x0) (“stream in memory instead of DMA-BUF - cause: GTK refused the DMA-BUF (fourcc, modifier)”; the values are those of the refused frame). From the stream, at the switch: the same first words with the cause GTK ha rifiutato il DMA-BUF: decodifica software (“GTK refused the DMA-BUF: software decoding”), then decodifica col processore - causa: GTK ha rifiutato il DMA-BUF: prestazioni ridotte (“decoding with the processor - cause: GTK refused the DMA-BUF: reduced performance”), and the toast. Before the first DMA-BUF the surface may also have written DMA-BUF provato comunque - causa: GTK non elenca fourcc … modificatore … tra i formati importabili (“DMA-BUF tried anyway - cause: GTK does not list fourcc … modifier … among the importable formats”).
  • Cost. As case 1, plus the frames lost until the key frame arrives. Not measured.
  • Back to hardware. Never inside the stream: the flag is never cleared, and it survives a reopening after a drop (the new decoder is created software again). A new window is a new stream and tries the DMA-BUF again.

Case 3: FFmpeg drops to software inside the hardware decoder

  • Trigger. The device opened, but when the stream starts FFmpeg's get_format list does not contain the via's hardware format (the GPU cannot decode this stream), so scegli_formato sets ripiego_software and returns FFmpeg's default format. This is found at the first packet, not at creation.
  • Steps. At creation via_verifica still sees the hardware via and writes decodifica video - causa: via vaapi (scheda grafica); dec_nato_hw is set. ph_decodifica_dai then sends the first packet; the fall-back flag turns ph_decodifica_via into software (ph_via_reale), and ph_decodifica_dai itself returns -1 for this packet. via_verifica is called right after it even when it fails: it writes the processor line, raises the toast, and, because the decoder was born hardware, recreates it ONCE as PH_VIA_SOFTWARE, gives it the stored configuration, requests ONE key frame from the phone and tells leggi_uno to drop the packet in hand. From then on there are no more errors at every packet and no key-frame requests every 500 ms. Frames are exported as memory frames. That this works on a GPU that cannot decode a stream is read from the code and was not run.
  • Log. [decisione] hh:mm:ss.mmm decodifica col processore - causa: la via hardware non regge il flusso: prestazioni ridotte (“decoding with the processor - cause: the hardware via cannot sustain the stream: reduced performance”), after the via vaapi line, and the toast. No flusso in memoria invece che DMA-BUF line: that one is written only when GTK really refused.
  • Cost. CPU decoding as above, plus the lost time of the failed first packets and one key frame. Not measured.
  • Back to hardware. At the next decoder creation, as in case 1.
!
Warning. Case 3 is the least certain, because no run is recorded: it depends on how a given GPU and FFmpeg behave at the first packet. All three cases write a line and raise the toast.

8.8 · Checking which path is in use

Everything the program says about video paths goes to standard error (the terminal that started the AppImage), plus the toast described above. There is no log file.

Decision lines have the form [decisione] hh:mm:ss.mmm <what> - causa: <cause> (ph_shell_decisione, src/shell/comune/consegna.c).

Line (what - cause)MeaningWhere
decodifica video - via vaapi (scheda grafica) or via vulkan (scheda grafica)“video decoding - via vaapi (graphics card)”: the via the decoder really uses, one line per stream and per change of viasv_flussi.c, via_verifica
decodifica col processore - nessuna via hardware disponibile: prestazioni ridottecase 1: no hardware via openedsv_flussi.c, via_verifica
decodifica col processore - GTK ha rifiutato il DMA-BUF: prestazioni ridottecase 2sv_flussi.c, via_verifica
decodifica col processore - la via hardware non regge il flusso: prestazioni ridottecase 3sv_flussi.c, via_verifica
flusso in memoria invece che DMA-BUF - fotogramma della scheda grafica non mappabile, copiato in memoria“stream in memory instead of DMA-BUF - GPU frame that cannot be mapped, copied to memory”: PH_ESPORTA_RIPIEGO, that is the Vulkan via, or VA-API with a refused mapping; once per streamsv_flussi.c, esporta
flusso in memoria invece che DMA-BUF - GTK ha rifiutato il DMA-BUF (fourcc %s, modificatore 0x%llx)GTK refused a DMA-BUF texture; once per surfacesuperficie.c, mostra
flusso in memoria invece che DMA-BUF - GTK ha rifiutato il DMA-BUF: decodifica softwarethe stream switched to the software decoder (case 2)sv_flussi.c, decodificatore_nuovo
DMA-BUF provato comunque - GTK non elenca fourcc %s modificatore 0x%llx tra i formati importabili“DMA-BUF tried anyway”; may precede a refusalsuperficie.c, texture_da
spazio dei colori lasciato a GTK - GTK non ha costruito lo spazio dei colori %d: %s“colour space left to GTK”: the colour state could not be builtsuperficie.c, stato_colore
fotogramma scartato - esportazione non riuscita“frame discarded - export failed”, once; then fotogrammi scartati - %u in tutto prima di questo when exports work againsv_flussi.c, esporta
decodifica non disponibile - il decodificatore non si e' creatono decoder at all, not even softwaresv_flussi.c, decodificatore_nuovo
Table 8.10 — Decision lines about the video path

Statistics. With the environment variable PH_SUPERFICIE_STAT=1 (a value starting with “1”, read when each surface is created) every surface writes every 5 s, from its reading thread: superficie N: ricevuti X (R/s), mostrati Y (R/s), scartati Z, rifiuti DMA-BUF W (“surface N: received, shown, discarded, DMA-BUF refusals”; N counts surfaces from 1 in creation order). Received and shown are the frames read and the textures put on screen with their rates since the last line; refusals above 0 mean GTK is refusing the DMA-BUF (src/shell/superficie/superficie.c).

What the lines tell. The first line of a stream names the via really in use: vaapi means the copy-free path unless a flusso in memoria invece che DMA-BUF line follows (mapping refused, or GTK refused); vulkan always means the copying path (PH_ESPORTA_RIPIEGO). The “processor” lines say the decoding is software and why. Because the line is written when the decoder is created and after each packet, a fall-back found at the first packet or after a new configuration (case 3) shows as a vaapi line followed by a processor line.

Which via a machine gets. The program itself now says it, in the first decision line of each stream. The measuring tools also print it, because they call ph_decodifica_via: finestra-prova and prototipo-gtk write decodifica: via vaapi (or vulkan, software) on standard error; misura-flussi prints the via of each stream; misura_decodifica prints it with the pixel format and the decoding time. With --via automatica (the default) they use the same order as the program. GTK's own offload messages are available with GDK_DEBUG=offload, which the development scripts set.

Forcing a path. The program has no switch for it: no preference, option or variable chooses the decoding via, and the order cannot be changed. The option exists only in the tools, as --via automatica|vaapi|vulkan|software (misura-flussi also accepts nessuna; misura_decodifica takes the via as its second argument), and an explicit via fails if it is not available. The project plan speaks of a switch for measuring the two vias: it is this one, in the tools.

ToolWhat it measures
strumenti/misura-flussi.copens one session per app on a real phone and measures, for each stream, the frames that arrive, the bandwidth, their regularity (intervals), and with decoding the via, the decoding errors and the mean decoding time; answers how many encoders in parallel the phone supports
strumenti/prototipo-gtk.ca GTK4 prototype, not the shell: composes several streams in windows, with the no-copy DMA-BUF path by default and --copia for the memory path; --giostra moves and resizes the windows by itself. It measured whether GTK composes several streams without copies and without stutter
src/video/misura_decodifica.cdecodes a raw H.264 file with the chosen via and prints frames, size, pixel format, mean and worst decoding time and frames per second
strumenti/finestra-prova.ca bare window (SDL3) that copies frames from the GPU to memory and measures click-to-image latency; not the final path
Table 8.11 — Measuring tools

8.9 · Requirements and limits of hardware acceleration

Libraries from the system. The AppImage includes a minimal FFmpeg (pacchetto/dentro.sh: decoder h264, parser, PNG encoder, MP4 muxer, --enable-hwaccel=h264_vaapi and --enable-hwaccel=h264_vulkan, with libva, libdrm and Vulkan), but the following stay with the system and are required: libva.so.2 and libva-drm.so.2 (without them the program does not start: they are needed by FFmpeg), libvulkan.so.1 (the loader: without it the program does not start) and libdrm.so.2. For hardware decoding the machine also needs a VA-API driver for the GPU (Vulkan Video: a Vulkan driver that offers VK_KHR_video_decode_h264). Source: pacchetto/LEGGIMI.md and the file SYSTEM-REQUIREMENTS.txt that the build writes.

What was measured, and where. From the project plan: on one machine with an Intel GPU (GTK 4.18.6), where Vulkan decoding is switched off by the driver as shipped, GTK4 drawing through Vulkan with the images passed from the decoder without copying gave 59 frames per second with 3 windows and regular intervals; the default renderer (GL) gave 54 even with 5 windows; with the images copied, 27 frames per second with 3 windows. Those are measurements of the prototype strumenti/prototipo-gtk.c on recorded video, not of the final program. Not yet measured: five really active apps from a real phone, and HiDPI. The same machine is where the choice of route A was made (VA-API where Vulkan Video is off).

Direct hand-off to the screen (offload). On that machine GTK never printed “Attaching … GdkDmabufTexture” with GDK_DEBUG=offload, even with forced offload and with both renderers, not in the surface demo and not in the prototype: the direct hand-off is not active. The textures are DMA-BUF (no refusals), so the video reaches the GPU without a copy in memory and only the last step is missing. Rounded corners and clipping of the real windows would prevent it anyway. Open point.

What was run, and what was not. The program has run live with video (1440p, two screens, a test of 23 Nov 2026, recorded in the project plan), but which decoding via it used was not recorded then. Not proved on real hardware: the Vulkan via, and the three software cases; the software cases also have no recorded measurement.

Known limit. With only Vulkan (VA-API absent) every frame is copied to memory (PH_ESPORTA_RIPIEGO): the copy-free path exists only with VA-API. The automatic order puts VA-API first for that reason.

i
Note. The surface also reduces the rate of a stream the GTK thread cannot follow, and logs it (frequenza fotogrammi ridotta); that is a separate mechanism, described with the surface.

8.10 · Screenshots and recordings

Screenshots and recordings use the decoded frames and the received packets, in src/video/cattura_png.c, src/video/cattura_mp4.c and src/video/cattura_nome.c; the header src/video/cattura.h exposes no FFmpeg type.

Screenshot. The reader thread serves pending screenshots before ph_esporta consumes the frame (same thread as the decoder: capture reads, never modifies). sv_flusso_screenshot queues the request, gives it 2 s, and asks for a key frame because a still screen sends nothing. GPU frames are brought to memory with av_hwframe_transfer_data, then libswscale converts any YUV 8 or 10 bit format (width and height 1 to 16384). Two destinations: a PNG file (ph_cattura_screenshot) and a PNG in memory for the clipboard (ph_cattura_png_memoria). No file is ever overwritten: creation is atomic with O_EXCL and a taken name becomes (2), (3) up to 999; a partial file is deleted on error.

Names. <app> + date + time + extension, as <app> YYYY-MM-DD HH.MM.SS.png (local time). The app part removes / \ : * ? " < > | and control characters (replaced by _), is cut to 80 bytes without splitting a UTF-8 character, loses spaces and dots at its ends, and if nothing is left it is YASDE.

Recording. The H.264 is written as received, with no re-encoding, into a fragmented MP4 (empty_moov, default_base_moof, frag_custom): the writer closes a fragment at every key frame or about every second. Why: the file is playable even if the process dies (at most the last second is lost); a classic MP4 without the final moov is unreadable. SPS and PPS go in the track description; the samples lose them, and start codes become lengths. The file is opened with O_EXCL.

RuleDetail
Startnothing is written until the first key frame (an IDR NAL with a configuration already received or in the same packet); earlier packets are dropped
Size changeafter the first key frame the size must stay the same; a change is an error and the recording is finished by the caller
Configuration changean SPS/PPS different from the one in use is an error and the frame does not enter
Timethe first key frame is time 0; a time not greater than the previous one is corrected (the previous frame keeps its duration); a forward jump is taken as true up to 30 minutes; the counters tempi_corretti count them
Write errorthe file is brought back to the last good point and closed; later calls return -1; the file stays playable
Audio tracksupported by the library (Opus, 48 kHz stereo, pre-skip 312 samples) but not used: the shell opens recordings with no audio, so YASDE recordings are video only
Table 8.12 — Recording rules

In the shell every packet, configurations included, goes to the recording before decoding. If the writer fails the recording is stopped with a message; a drop of the connection stops it too.

Chapter 9

Audio

9.1 · Audio: capture and transport

The phone captures everything it plays and sends it as Opus; the PC plays it. On the phone the code is telefono/audio: Audio (the channel), Cattura (one capture), Volume (media volume) and NascosteAudio (the hidden audio-policy APIs).

  1. Opening the channel starts the capture, closing it stops it. One audio channel at a time: a second one waits up to 2000 ms for the first to finish closing and is then refused (closed). If the service is closing, no capture starts.
  2. Loopback rule. NascosteAudio registers an AudioPolicy with a mixing rule that matches by usage: unknown, media, alarm, notification, notification event, accessibility, navigation guidance, sonification, game and assistant. While the rule is active the phone stays silent and the sounds come out of the PC; when it is removed the phone plays again by itself. The recorder is built by hand (NascosteAudio.creaRegistratore) with a context that presents itself as com.android.shell: the library helper creates it without a context, so the package would be android and the system refuses uid 2000.
  3. Format. AudioRecord 48 kHz stereo 16 bit, read in blocks of 960 frames (20 ms), encoded with a MediaCodec Opus encoder at 128 kbit/s.
  4. Time. The time of each packet is the number of samples captured so far divided by 48000, not the clock, and a lost PCM block is added to it, so a gap always shows as a jump of 20 ms or more.
  5. Queue. Packets wait in a queue of 250 (5 s) toward the PC; beyond it the oldest is dropped and the jump is visible in the time.
FieldSizeNotes
time8 bytesmicroseconds: samples captured so far / 48000 (not the clock)
length2 bytesat most 4000 on the PC side; more means a broken channel
datalengthone Opus packet
Table 9.1 — Audio packet (10-byte header)

9.2 · Media volume on the phone

The media volume must be at the maximum during capture: with volume 0 some apps do not start their audio. The change follows the rule that governs every change to the phone: the undo is registered first, the change is verified, the user's value wins.

  1. Read the current volume and the maximum (cmd media_session volume --stream 3 --get, parsed from volume is N in range [a..b]).
  2. If it is already at the maximum, do nothing. Otherwise register the entry audio-volume (order 50) with Guardiano.imposta. If it returns false, or there is no guardian, the volume is not touched and the capture goes on.
  3. Set the maximum and re-read it: a different value is an error and the volume is restored.
  4. At close: read the volume; only if it is still the maximum YASDE set, put the original back (retried once if the re-read does not match) and remove the guardian entry after the check succeeded. Otherwise it is left and logged as changed by the user. A failed check leaves the entry for the guardian.

The volume the user moves in the shell is a gain applied on the PC and does not touch the phone's volume. All commands run with a real timeout: the output is read on a separate thread so a blocked command cannot block the caller.

9.3 · Audio: playback on the PC

On the PC the audio piece is src/audio. The public header is audio.h; the parts are tested alone, without an audio device. Audio has no hardware acceleration on the PC: the Opus packets are decoded by libopus on the CPU; on the phone the Opus encoder is the one Android returns for createEncoderByType, and the code does not say whether it is hardware or software.

FileRole
pacchetti.creads packets from the channel (resumable reads: a timeout in the middle of a packet keeps the state)
decodifica.cOpus 48 kHz stereo to float, with concealment of missing packets
flusso.cdecode plus detection of lost and late packets
coda.cqueue with adaptive margin and lag recovery
uscita_pipewire.cthe PipeWire output behind a small interface (PhUscita); tests use a fake one
audio.cthe player that puts the parts together
suona.ca hand tool that plays a channel
Table 9.2 — Files of src/audio

Life. ph_audio_crea(channel, notice, ctx, error) takes the channel (it closes it even if creation fails), with volume 100 and not muted. ph_audio_avvia opens the PipeWire output (application name YASDE, 48 kHz stereo float, requested node latency 1024/48000, 3 s to start) and starts the reading thread; once only. ph_audio_ferma stops reading and output; ph_audio_distruggi also closes the channel and frees. The notice PhAudioAvviso is called once, from the reading thread or PipeWire's, when the stream ends (PH_AUDIO_FINITO: the phone closed it) or breaks (PH_AUDIO_ERRORE); it is not called when the stop was requested, and it must not call stop or destroy.

Packets in. Each packet is decoded; a jump in the time field larger than 10 ms (half a packet; less is noise) means lost packets and up to 10 of them (200 ms) are concealed with the decoder's own concealment, no more sound is invented beyond that; a packet that arrives out of order or twice is dropped and counted; 25 late packets in a row mean the phone restarted its time and the stream is re-synchronised; 100 undecodable packets in a row make the flow unrecoverable.

The queue. Between the arriving packet and the sample leaving there is a margin that absorbs network delay. It is computed from the data: for each packet the lateness (arrival time minus the time field; the two clocks are not comparable but their difference is) is measured against the most punctual of the last 10 s; the maximum lateness in that window plus a fixed 40 ms is the ideal margin. It rises at once and falls by 8 ms per second. Constants: capacity 2 s; initial target 60 ms; limits 40 and 600 ms.

  • Every half second the queue checks how much audio is really there. If it is well above the margin (more than 40 ms) it plays slightly faster, if well below slightly slower, rereading samples with linear interpolation by at most 2%: it is heard neither as a click nor as a pitch change. It stops when within 8 ms of the margin.
  • A huge excess (after a stall and a burst) beyond 250 ms is cut at once to 40 ms, with a 5 ms (240 frames) cross-fade.
  • An empty queue during playback is an underrun: the sound is faded out, the queue goes back to “filling” and restarts only with the full margin. After a hole the margin climbs again by 20 ms.
  • A stall is ignored for the estimate for at most 5 s: beyond that it is the clock that changed.

ph_audio_statistiche reports received, lost, late, invalid packets, underruns, discarded frames, the margin and the target, and PipeWire diagnostics (device delay, buffered and queued frames).

9.4 · Gain, start-up and synchronisation

Gain. ph_audio_volume(percent) (0–100, clamped) and ph_audio_muto set a gain applied on the PC to the samples, with a cubic curve (v/100)^3 like the sliders of PipeWire and PulseAudio: 0 is silence, 100 is gain 1. A ramp of 10 ms avoids clicks. Muting does not stop reading: packets are received and decoded all the time, only the gain drops. The volume is persisted by the caller (the config piece, in the phone profile), not here. The default of the shell slider is 100%.

When audio starts. sv_audio_programma (src/shell/ossatura/sv_audio.c) schedules the start SV_AUDIO_RITARDO_MS = 5000 ms after the first video stream of the session opens; the manager thread ph-gestore does the actual open. Opening goes through ph_componente_canale(c, "audio"). If the open fails or the stream ends, a new attempt is scheduled after 2, 4, 8 and 16 s (SV_AUDIO_TENTATIVI = 4 per session); decisions go to the decision log. On session teardown the audio is destroyed and the counters reset.

Synchronisation. The audio clock is exposed: ph_audio_tempo_telefono_us gives the phone time (the time field) of the sample leaving the speakers now, estimated with the latency PipeWire declares (delay plus buffered plus queued frames), or -1 if unknown. The two phone clocks (video presentation time and audio sample count) are not comparable with each other. As the code stands, no caller in the shell uses this function: video frames are shown as they arrive and there is no active audio-video synchronisation yet. The piece to measure is listed among the open points.

!
Warning. If you add synchronisation, convert the audio time to the video time line first; cattura.h says the same for recordings, and the shell would have to do the conversion.
Chapter 10

Input, clipboard and the phone's panel

10.1 · Input injection

A window of a phone app sends the user's mouse and keyboard to the phone as input events. The PC side is ph_input_* in src/componente/componente.c and the stream code in src/shell/ossatura/sv_flussi.c; the phone side is telefono/video: Input (the channel), Iniettore (the injection), Gesti (what a touch or pinch means) and Pizzico (the pinch geometry).

On the PC. sv_flusso_input accepts an event only if the stream is active and not paused and, for touch and wheel, the video size it was computed on equals the stream's current size (the phone would discard it anyway). It then switches the panel off again if the phone is “in hand” (10.4 “The phone panel: off when connected”). Mouse moves and wheel events are dropped when more than CODA_INPUT_MAX (512) jobs are waiting in the input pool, so a phone that cannot keep up does not accumulate movements; the closing phases of a gesture always pass. The window code (src/shell/finestra-app/finestra_app.c) feeds it from one drag gesture on the windows container that accepts every button; gesto_inizia_pulsante maps the GDK button with ph_fa_pulsante_tocco to the bit of pulsanti (left 1, right 2, middle 4; back, forward and others start nothing). The left button keeps everything it had: title bar and corner start a window move or resize, content sends a touch. Right and middle count only on the content of an app window (the same discards as the left: pause, lost-connection veil and buttons inside it, black bands around the image, a size that changed); on the title bar, the corner handle, the window buttons or outside the windows nothing happens, not even a change of the active window. TOCCO down and moves carry the bit of the button that started the gesture (tocco_pulsanti), up and cancel carry 0; the field travels unchanged through ph_superficie_tocco, ph_srv_flusso_tocco and sv_flusso_input to the message. One button at a time: pressing a different button while a gesture is open makes GTK reset the controller (gtk_gesture_single_handle_event), so the toolkit sends a cancel and the gesture in progress is cancelled (the touch is cancelled on the phone; a window move or resize is cancelled); the second button starts nothing. gesto_inizia_pulsante also refuses a press while a gesture is open, as a defence. Every way of losing the gesture (cancel by the toolkit, window closed, pause, pinch starting, window minimised) sends a cancel for the touch that is down, so no down is left without its up or cancel. Text that is plain ASCII goes as TESTO; text with other characters goes through the clipboard as a paste (APPUNTI_INCOLLA, 10.3 “The shared clipboard”). The send writes on the input channel under a lock held during the write: the known exception to the rule of no lock during a network write, because ADB forbids two writers on one channel.

On the phone. Input reads the channel without a buffer and puts each message in a bounded queue of 256 closures; when the queue is full the reader waits, so no event is lost. One thread executes them. Each event carries the session id and, for touch, wheel and pinch, the video size used for the coordinates; if it differs from the session's current size the event is discarded (specification 4.5). A touch-down during a pause, resize or other transition is dropped. At the end of the channel (PC gone or error) every open gesture of every session is cancelled: no finger stays down.

MessageInjected as
TOCCOa MotionEvent on the session's display: down, move, up or cancel. The left button is a finger (source touchscreen). If the pulsanti field has the right or the middle button when the gesture starts (the right wins if both), the whole gesture is a real mouse: source mouse, tool type mouse, ACTION_DOWN with BUTTON_SECONDARY or BUTTON_TERTIARY followed by ACTION_BUTTON_PRESS, moves with the button held, then ACTION_BUTTON_RELEASE and up (or cancel) with no button; setActionButton is hidden, so it is called by reflection and, if missing, the two BUTTON events are skipped. The button is decided at the press and remembered until the release; unknown bits are ignored. A cancelled mouse gesture (another session pressing, pause, resize, end of channel) sends only ACTION_CANCEL with no button and no ACTION_BUTTON_RELEASE (a release would count as a mouse-up and open the link). For the mirror the coordinates are scaled to the real screen
ROTELLAACTION_SCROLL with source mouse; AXIS_HSCROLL and AXIS_VSCROLL are the 120ths divided by 120
TASTOa KeyEvent with the code and meta state given, from the virtual keyboard map, on the session's display
TESTOeach character mapped by the virtual keyboard map to key events; a character the map cannot produce is skipped and logged as a code point
INDIETROBack down then up
PIZZICOsee the next section
Table 10.1 — How the phone injects each message

Every injected event carries the id of the session's virtual display (schermoInput: 0, the real screen, for the mirror).

10.2 · The pinch gesture

Ctrl + wheel is a zoom. The PC sends the gesture as steps and the phone makes two fingers: this lets the apps' gesture detectors see a continuous movement. The shell turns the wheel into ph_input_pizzico calls; the argument checks (phase unknown, x or y outside the video, zero size) fail with -1 without sending anything and the step is clamped to −1200..1200.

RuleValue
Fingerson a horizontal line through the centre (x, y), symmetric
Initial distance25% of the shorter side of the virtual display
Per 120 of stepthe distance is multiplied by 1.25 (−120 divides it); steps of the gesture are summed
Distance limitsbetween 5% and 90% of the shorter side
Near an edgethe centre moves inward just enough that both fingers stay inside [0, w−1] × [0, h−1]; the gesture goes on from there with the same shift
Long stepsa step beyond ±30 is split into several ACTION_MOVE (at most 30 per move, one every 8 ms)
Phasesstart puts both fingers down (and applies its step); continue moves; end lifts both (ACTION_POINTER_UP then ACTION_UP); cancel sends ACTION_CANCEL. Continue or end without an open start is discarded; a new start closes the open gesture first
Always closedafter 400 ms with no step the phone ends the gesture by itself; session close, pause and size change cancel it
With a touch in progressthe last arrival wins: a pinch start cancels the touch finger first; a touch down closes an open pinch (cancel); a touch move or up whose finger is no longer down is discarded
Pausedthe pinch is discarded and an open one is cancelled
Table 10.2 — Pinch rules (Pizzico, Gesti)

On the PC side the stream records the last pinch centre so that a pause, resize or close sends a PH_PIZZICO_ANNULLA and no finger stays down; what counts is what the phone really received, updated after each successful send, so a lost “up” is still cancelled and a cancel is not sent for a down that never left. An old jar answers an unknown type as it does for any unknown input type, with no visible error.

10.3 · The shared clipboard

Text copied on the phone is copied on the PC and the reverse. Only text: images and files are ignored. The phone side is telefono/appunti (Appunti, Regole, NascosteAppunti), the PC side is src/dati/appunti.c, on the channel appunti.

TypeNameDirectionBody
0x58APPUNTI_TESTOT→PCthe text just copied on the phone
0x59APPUNTI_IMPOSTAPC→Tthe text to put in the phone clipboard
0x5aAPPUNTI_INCOLLAPC→Tu32 session id, then the text; clipboard plus “paste” to the app of that session
Table 10.3 — Clipboard messages (text is a u32 length plus UTF-8, not a 16-bit stringa)

Never passed (in either direction, silently):

  • copies marked sensitive (ClipDescription.EXTRA_IS_SENSITIVE);
  • texts above 200000 bytes (MAX_TESTO, also PH_DATI_APPUNTI_MAX on the PC): the message is ignored;
  • copies that come from a password manager or an authenticator: the criterion is the list of known packages in Regole (a name stands for itself and its sub-packages). The Google password manager copies from Play Services, so it cannot be filtered by package and only the standard sensitive flag applies;
  • non-text content.

No echo. The phone sends APPUNTI_TESTO when its clipboard changes but not for what it has just received from the PC: an echo is the copy YASDE itself put (label yasde, source com.android.shell when the system tells it) with the same text as the last one from the PC. A real copy on the phone with the same text has another label and passes. The system notifies twice for one copy; the same timestamp and text count once, and an uncertain source is re-evaluated at the next notice. When the channel closes the phone's clipboard stays as it is.

On the PC a thread reads messages for the whole session (150 ms slices); a text is cleaned by ph_dati_pulisci (invalid UTF-8 becomes U+FFFD, NUL bytes are removed, and the length inside the message must match the bytes present) and handed to the notice; it is discarded if the cleaning grew it above the limit. When the reader ends by itself the notice is called once with a NULL text. APPUNTI_INCOLLA serves the text the virtual keyboard cannot produce (accents, emoji): afterwards the phone's clipboard keeps that text.

i
Note. Texts never go to a log, on either side.

10.4 · The phone panel: off when connected

While the apps are used from the PC the phone panel (its real screen) stays off, while the phone stays awake and unlocked; when the user takes the phone in hand the panel turns on again. The code is telefono/pannello (Pannello, TieniSveglio, AssenzaPc, InputFisico, Frequenze, ImpostazioniPannello, NascostePannello) and, on the PC, src/shell/ossatura/sv_dati.c.

TypeNameBody
0x60PANNELLO_IMPOSTAu8 0 = off, 1 = on (any other value is an error)
0x61PANNELLO_STATOempty; answer u8 on, u8 in hand
0x6ePANNELLO_EVENTOevent: u8 on, u8 reason
Table 10.4 — Panel messages
ReasonName in codeMeaningIn hand on the PC
1MOTIVO_UTENTEthe user touched the real screen or a physical key, unlocked or woke the phoneyes
2MOTIVO_CHIAMATAincoming or ongoing callyes
3MOTIVO_FINE_CHIAMATAcall endedyes
4MOTIVO_PCasked by the PCno
5MOTIVO_CHIUSURArestore at closeno
6MOTIVO_ASSENTEPC absent for 30 minutesyes: the panel stays on until the first PC input turns it off
Table 10.5 — Panel event reasons (ph_ossatura_pannello_da_evento)

How off works. PANNELLO_IMPOSTA 0 acts only on the compositor (SurfaceControl.setDisplayPowerMode, a hidden API): Android still believes the screen is on, so the apps on the virtual displays go on running and receiving input. It is refused with ERRORE during a call, when the phone is locked or its screen is off, and when the guardian is missing.

  1. Open the listener on the physical devices (InputFisico: getevent -pl once, devices chosen by capability, touchscreen with ABS_MT_POSITION_X and INPUT_PROP_DIRECT, keys by common physical keys; the shell may read /dev/input because it is in the group input). Without it the panel is not turned off. Injected events never reach /dev/input, so they cannot count as the user touching the phone.
  2. Register the restore entries first, then change: the screen timeout (pannello-timeout, order 420) if it is not already the maximum, then the panel (pannello-acceso, order 400). If any registration returns false nothing is changed; if the later step fails, the earlier ones are undone as far as they can.
  3. Raise the screen timeout to the maximum 2147483647 ms (screen_off_timeout through cmd settings, verified by re-reading): without it the apps on virtual displays stop receiving input. It stays at the maximum even during the “in hand” periods, and is restored (only if still ours) when the PC asks to turn on or at close.
  4. Turn the panel off, send the event (reason 4), then measure the refresh rate.

It comes back by itself, and the event goes out, when the user touches the real screen or presses a physical key, unlocks the phone, or a call arrives or is in progress. From then the phone is “in hand” and stays on until the PC sends PANNELLO_IMPOSTA 0 again. If the turn-on fails, the reason is remembered and the control loop retries it every second, before anything else. If Android is asleep the panel is not forced (the system turned it off; the user wakes it).

The control loop. One thread, every 1000 ms (PERIODO_MS), reads the call state, whether the screen is interactive and whether the phone is locked, each in its own try so one failing read does not stop the others, then evaluates the PC absence, then the wake-lock guard, then reports changes: a call starting turns the panel on (or marks the phone in hand), the end of a call is reported, a lock or sleep with the panel off turns it on, and an unlock or wake with the panel on is reported as reason 1. It starts at the first sign of life, and an exception in a round never kills it.

The PC decides when to turn the panel off; the phone only obeys and reports. The code is in sv_dati.c.

Onpanel on, not in handOffturned off by YASDEIn handon, user is using itconnected / first PC inputtouch, unlock, callfirst input from the PCPC asks on / drop / closeFigure 10.1 — The panel states as seen from the PC
  • At connection (decision of 24 Nov 2026): as soon as the session is up, if the panel is on and the phone is not in hand, YASDE turns it off, once, queued on the state pool because it can last seconds. If the phone refuses (locked, in a call) it is not retried; at unlock or at the end of the call the “in hand” rule takes over. If the phone is already in hand at connection the panel is not turned off. Reading the state again after a refusal is not covered by a test.
  • First input from the PC with the phone in hand and the panel on: sv_pannello_spegni_se_in_mano queues one turn-off (one at a time). After a refused turn-off it waits 2 s before trying again.
  • The popup switch “physical panel” calls sv_pannello directly.
  • Closing the last window does not turn the panel on while YASDE is connected (decision of 23 Nov 2026, in place of the specification). The panel comes on only for the user (unlock on the phone, the popup switch), a call, the end of a call, and YASDE closing or dropping (restore on the phone side).
  • Turned off or on by the PC means not in hand. State changes from 0x6e events are published as the phone state; every state read is requested after the listener is registered.
  • There is no timer on the PC that turns the panel off again after the user's inactivity. The design documents say there is; the code does not (1.5 “Known deviations from the design documents”).
!
Warning. Turning the panel off at connection was proven on a real phone on 24 Nov 2026. Still not tried live: the panel not turning on at the close of the last window, and reason 6 after an absence.

10.5 · Refresh rate while the panel is off

Turning the panel off makes the phone's compositor drop to a lower rate. A measured case (120 Hz test phone): the compositor went from 120 to 60 Hz with the panel off and the video fell from about 87 to 57 frames per second; with the remedy it climbed back to about 80. The remedy is a workaround started by the measured symptom on any phone, never by the manufacturer's name; it is isolated in one place and documented.

  1. After every turn-off the active compositor rate is measured and written in the log with the display's maximum.
  2. The wanted rate is the highest among the modes with the same resolution as the active one (Frequenze.massimaStessaRisoluzione), capped by the user's peak_refresh_rate if it is numeric and greater than 0 (Frequenze.voluta).
  3. If the active rate is below the wanted one, min_refresh_rate is set to the wanted rate, with the restore (pannello-frequenza, order 410) registered before and applied only if the value is still ours; at turn-on it is put back. If the user already has a minimum equal or higher nothing changes.
i
Note. The design documents say “set min_refresh_rate to 60 before turning off”. The code does the measured version above.

10.6 · Keeping the phone awake

A wake lock keeps the phone awake and therefore protected from locking through inactivity for as long as YASDE is connected and alive. It is in TieniSveglio, with the Android part behind the Presa interface so the logic is tested on a plain JVM. The lock is taken from the first message of the command channel (the greeting), not at service start.

Why a wake lock and not the screen timeout: the wake lock belongs to the process, so if the service dies (even with kill -9) the system releases it and the phone goes back to turning off and locking on its own times. No setting stays changed and nothing needs the guardian.

Condition (all must hold)Detail
Channel greetedthe PC has sent SALUTO
Phone not lockedthe lock would keep the lock screen lit for ever after a lock with the power key: it is released while locked and taken again at unlock; an unreadable state counts as locked
PC alivelast sign of life younger than 30 minutes (Registro.PC_ASSENTE_MS); exactly 30 minutes is already too much; a sign newer than now is an incoherent clock and counts as no
Table 10.6 — When the wake lock is held

Every doubt goes to the safe side: release. The wanted state itself expires: if aggiorna does not arrive within SCADENZA_STATO_MS (30 s, measured with its own monotonic clock) the thread treats it as “do not hold”. 30 s and not 5 because the control round and the PC's commands work under the same lock as the panel and run cmd settings with 10 s limits (up to 20 s); with 5 s a phone under load would drop the lock and fall asleep mid-session. The caller of aggiorna never waits: it only writes the wanted state; a separate thread takes and releases, outside every lock, retrying every 5 s on failure.

The lock is taken without ON_AFTER_RELEASE (the safe choice): when it is released and the user has not touched the phone for longer than their own timeout, Android does not restart the countdown from zero, it turns the screen off and locks at once.

10.7 · Signs of life and PC absence

The phone must not stay in a state “owned by YASDE” when the PC has vanished without closing. Rule: any message the phone receives from the PC on the command channel (the greeting included) is a sign of life. The service notes the time (monotonic clock, SystemClock.elapsedRealtime) before dispatching it (Smistatore.tratta → Registro.segnoDiVita).

ConstantValueWhere
PRESENZA_INTERVALLO300 s (PH_PRESENZA_INTERVALLO_S)PC: sends PRESENZA when nothing has been sent on the command channel for 5 minutes; it is needed only when there is no other traffic
PC_ASSENTE1800 s (Registro.PC_ASSENTE_MS, PH_PC_ASSENTE_S)phone: six missed PRESENZA in a row
Control round1000 msphone: absence check and wake-lock guard
Table 10.7 — Presence timing
PCcomponenteRegistrolast sign of lifePannellocontrol loop 1 sany message on the command channel30 minutes pass with no messageAssenzaPc.valuta: expired1 panel on; 2 refresh rate back; 3 timeout backPANNELLO_EVENTO on, reason 6wake lock released; service and sessions staythe PC speaks againany messagewake lock again, timeout to maximumFigure 10.2 — PC absence and return

On absence (AssenzaPc, exactly PC_ASSENTE_MS, a clock going back counts as expired) the steps are, in order: turn the panel on if YASDE had turned it off; restore the minimum refresh rate; put the user's screen timeout back (only if still ours); then send PANNELLO_EVENTO (on, reason 6). A step that fails or throws stops there and is retried at the next round, without skipping the order and without sending the event early. The wake lock is not a step: the guard releases it with the same limit. It does not close the service or the sessions. It is the safest state: the phone is exactly as every day and Android turns it off and locks it with the user's times.

On return (the first sign of life after the absence): the wake lock is taken again if the phone is not locked, and the screen timeout is raised again (the restore registered before); the panel STAYS ON until the PC sends PANNELLO_IMPOSTA 0, exactly as if the phone were in hand (reason 6 counts as in hand on the PC). A failed return is retried at the next round.

If the wake-up of a sleeping PC delays a PRESENZA, the boot clock makes the next one go out at once; a late message does not trip the 30 minutes because the window is six times the interval. The case “phone restarted by the user and the PC still running” needs no rule: the link loses the connection and starts again.

Chapter 11

The shell

11.1 · Overview and pieces

The shell is everything the user sees: the single GTK 4 window, the desktop inside it, and the windows of the phone's apps drawn as inner windows. It lives entirely under src/shell/. GTK appears nowhere else in the project, and the shell never touches the phone, the audio or the disk directly: it goes through one narrow door, the services (11.4 “The services and their backends”).

Two Italian words recur in the code. ossatura is the skeleton: the piece that owns the program, the main window and the real services. pezzo (piece) is the unit of work: one piece is one folder, with its own meson.build, its own tests and, in the shell, its own style sheet and translation file.

Piece (test name)FolderWhat it does
shell-ossaturasrc/shell/ossatura/The GtkApplication it.yasde.YASDE, the main window, the real services, the lock and connection veil, the PC/phone clipboard link, the ordered shutdown
shell-superficiesrc/shell/superficie/The widget that shows one video stream without copies (DMA-BUF) or from memory
shell-finestra-appsrc/shell/finestra-app/The inner windows of the apps: title bar, buttons, input translation, pause, screenshot and recording, Compatibility
shell-barrasrc/shell/barra/The bar at the bottom (48 px)
shell-launchersrc/shell/launcher/The app launcher with search
shell-desktopsrc/shell/desktop/Wallpaper, icons, widgets, menus and the two dialogs
shell-trasferimentosrc/shell/trasferimento/Send and receive panels, folder navigator, APK confirmation
shell-sistemasrc/shell/sistema/Notifications, toasts, phone status, volume
shell-connessionesrc/shell/connessione/First connection and pairing screen
shell-fintosrc/shell/finto/ + src/shell/comune/The fake backend, and the common piece (delivery, context, services wrapper, style)
Table 11.1 — The pieces of the shell. The test name is what strumenti/prova.sh takes

11.2 · Layers, popups and piece handlers

The root of the shell (ph_shell_radice) is a stack of layers (PhShellStrato in src/shell/shell.h). Inside a layer the last child added is on top. For absolute positions (windows, icons, context menus) a piece uses ph_shell_libero_nuovo(), a container that lets clicks through wherever it has no child.

Structure of the shellOne GtkApplicationWindow (the host window): the root holds the layers, bottom to topPH_STRATO_DESKTOPwallpaper, icons, widgetsPH_STRATO_FINESTREinner app windowsPH_STRATO_BARRAthe 48 px barPH_STRATO_PANNELLIpopups, launcher, dialogsPH_STRATO_TOASTpop-up noticesPH_STRATO_RILASCIOdrop-to-send boxPH_STRATO_VELOveil / first connectionPH_STRATO_TITOLO_HOST6 px strip, full screenEach layer is a full-area overlay: a child with a non-FILL alignment takes only its own size,and the rest of the area stays clickable for the layers below.Order of installation: desktop, windows, system, launcher, transfer, bar (the bar is last).Figure 11.1 — The layers of the shell, from the bottom up

Each piece offers a single entry point, ph_<piece>_installa(PhShell *), declared in src/shell/pezzi.h. It is called once, from the GTK thread, after ph_shell_nuova: it builds the widgets, adds them to the layers, loads the piece's CSS, registers the handlers it serves and starts listening to the services. ph_ossatura_installa_pezzi (in src/shell/ossatura/ossatura.c) installs only the pieces present in the build (the header generated at configuration time, with one flag per piece).

Pieces serve each other through PhShell handlers, never by including each other's headers: windows (open an app, list the windows, bar click, mirror), desktop (icons), notices (ph_shell_avviso), launcher, transfer, system (the three bar buttons and the hidden-notification set) and pinned apps. Events travel the other way with ph_shell_ascolta: PH_SHELL_EV_FINESTRE, PH_SHELL_EV_POPUP, PH_SHELL_EV_HOST, PH_SHELL_EV_AREA, PH_SHELL_EV_DESKTOP, PH_SHELL_EV_NASCOSTE, PH_SHELL_EV_FISSATE.

Popups follow one rule: only one is open at a time (PhShellPopup). Opening one closes the open one; a transparent veil under the popups, bar included, turns the first click outside into a close that does not reach what is below. Escape closes the open popup; with none open it goes to the active inner window, which translates it to the phone's Back when the preference esc_indietro is on (the default). F11 toggles full screen and never reaches the phone.

11.3 · Threads and delivery to the GTK thread

The shell is one GTK thread plus worker threads. The rule is written at the top of src/shell/servizi.h and in src/shell/CONTRATTI.md, and every piece obeys it.

  • One GTK thread. All widgets, PhShell and every ph_srv_* call live there.
  • The GTK thread never blocks: no network, no large file reads, no joins of threads that may hang. Requests to the phone start on backend threads and return with a callback.
  • The only road from another thread to the GTK thread is ph_shell_consegna(fn, dati, libera). It is always asynchronous, even when called from the GTK thread (the function runs in a later iteration of the main loop, never inside the call), it keeps the order of deliveries from one thread, and it frees the data afterwards. Scattered g_idle_add or g_main_context_invoke calls are forbidden in pieces.
  • Every callback and every event arrives on the GTK thread. A GCancellable cancelled from the GTK thread guarantees that the callback will not arrive any more, even if the result is already queued.
  • Snapshots. State (connection, phone, apps, notifications, transfers, volume) is read with calls that return the last snapshot. A returned pointer is valid until the GTK thread returns to the main loop; anything needed later is copied.
  • Video: one reader thread per stream, owned by the surface, calls ph_srv_flusso_leggi (reception and decoding happen there). Textures are built on the GTK thread.
Pool (in struct Sv)ThreadsWork
p_lavori3Folder listings, searches, thumbnails, file reads
p_stato1Apps, notifications, panel (in order)
p_icone1App icons, one at a time
p_scrittura1Saving profile and preferences (in order)
p_flussi1Opening, pausing, resizing and closing video streams
p_input1Input toward the phone (in order)
p_installa1APK installation and uninstallation, one at a time
Table 11.2 — The worker pools of the real services (src/shell/ossatura/servizi_veri.c, src/shell/ossatura/sv_interno.h)

Besides the pools the real services run a manager thread (ph-gestore): it is the only one that takes a borrowed session from the connection (chapter 3); pool threads only "use" the session through a counter, and the manager waits for the counter before it hands the session back.

11.4 · The services and their backends

Every piece reaches the phone, the audio, the transfers and the persistence only through PhServizi (src/shell/servizi.h). Two implementations stand behind it: the real one, written by the skeleton on top of the lower pieces, and the fake one (11.9 “The fake backend”), so any piece can be run and photographed without a phone.

Worker threadpool or stream readerph_servizi_pubblica_*backend side, any threadph_shell_consegnaidle source, default priorityGTK threadswap the snapshotListenersph_srv_ascoltaThe snapshot is replaced only on the GTK thread; listeners then re-read it.A request goes the other way: ph_srv_* on the GTK thread, queued into a pool, result back through the same road.Figure 11.2 — How a result goes from a worker thread to the GTK thread

The common piece (src/shell/comune/servizi.c) wraps a backend table (PhServiziBackend in src/shell/servizi_backend.h) and enforces the thread rules for both: events on the GTK thread, snapshots, the icon cache, cancellation, deferred saving of the profile and the life of video streams. App icons (ph_srv_icona, GTK thread only): if the package has a row in the Kora table (tabella.txt, lines <package> <kora-name>) and the file <kora-name>.png loads, that texture is returned and the phone is not asked at all (a PNG of another size is accepted, up to 1024 px a side and 2 MiB: whoever shows it scales it); otherwise the phone's icon, or none yet (the request starts by itself and PH_SRV_EV_ICONA arrives), and the initials square if it never comes. The folder is the one in the environment variable YASDE_ICONE_KORA if set and not empty, else $APPDIR/usr/share/yasde/icone-kora (inside the AppImage), else none. The table is read once, at first use (at most 256 KiB and 2000 lines; malformed lines are skipped; package up to 127 characters, name up to 95 and valid; a package twice: the first wins); each PNG is loaded at first use and kept; a PNG that fails to load is not tried again. Missing or damaged files mean the phone's icon, with no error on screen; only a missing or unreadable table writes one decision line in the log. An app that changes its icon on the phone keeps showing the Kora one. A backend call is answered with exactly one final ph_servizi_lavoro_* call per job (searches: zero or more ph_servizi_lavoro_trovati and one ph_servizi_lavoro_cerca_fine). After the final call the job is not touched again.

Event (PhSrvEvento)Meaning
PH_SRV_EV_COLLEGAMENTOConnection state, including the lock
PH_SRV_EV_TELEFONOBattery, network, physical panel
PH_SRV_EV_APP, PH_SRV_EV_ICONAApp list; an icon arrived (argument: package)
PH_SRV_EV_NOTIFICHENotifications changed
PH_SRV_EV_TRASFERIMENTITransfer queue changed
PH_SRV_EV_VOLUME, PH_SRV_EV_APPUNTIVolume; text arrived from the phone's clipboard
PH_SRV_EV_PROFILOThe profile of another phone was loaded: re-read it
PH_SRV_EV_CONTROLLI, PH_SRV_EV_METEOQuick switches; weather forecast
Table 11.3 — Events of the services

Strings given to the services are copied before the call returns. Strings coming from the phone are already safe to show (valid UTF-8, no control characters); the raw percorso and nome fields only serve to navigate and request, and only the _schermo versions are displayed. Structures of the contracts are always initialized by field name, never by position, because contracts grow by adding fields at the end.

i
Privacy at the door. the shell never receives the phone's coordinates, serial number, addresses or the mDNS instance names; it gets only forecasts and, if the phone knows it, the name of the place.

11.5 · The skeleton

The skeleton is src/shell/ossatura/. main.c only calls ph_ossatura_esegui.

  • Before any thread: preferences (ph_cfg_preferenze_carica; result -1 means defaults and never save), language (ph_lingua_inizializza), and the font scale: with scala_automatica off, the value is applied through GDK_DPI_SCALE before gtk_init, because GTK 4 has no fractional widget scale.
  • Single instance: the application id is it.yasde.YASDE; a second launch brings the existing window to the front (activate) and opens no second connection.
  • At startup (main instance only): handlers for SIGTERM and SIGINT that call g_application_quit, removal of stale temporary files (ph_cfg_pulisci_temporanei(3600)) and of old wallpaper images (ph_cfg_pulisci_sfondi).
  • On activation: real services (ph_ossatura_servizi_veri), ph_shell_nuova, the host window (ph_finestra_nuova), the pieces, and the clipboard link (ph_appunti_installa).
  • The host window is a resizable GtkApplicationWindow titled YASDE with a header bar that carries the full-screen button, default size 980×584, minimum 640×420, with the shell root as its content. F11 is caught on the window before any inner window sees it. In full screen a 6 px strip at the top (PH_STRATO_TITOLO_HOST) expands to a title row on hover.
  • Host visibility: ph_host_visibile_da_stato reads the toplevel state: minimized or suspended means not visible. The skeleton tells the shell with ph_shell_imposta_host and every video stream goes to pause.

What covers the shell is decided by ph_ossatura_vista (in src/shell/ossatura/logica.c): the first-connection screen wins when ph_shell_connessione_da_mostrare says so, otherwise the veil, otherwise nothing. Never both.

Connection stateShownContent
PH_SRV_NON_ABBINATOConnection screen, alwaysPairing code (11.6 “The pieces of the shell”)
PH_SRV_CERCO, PH_SRV_PERSOConnection screen only if no phone was ever connected in this run; otherwise the veilVeil: title and the connection's own reason; Reconnect now when the connection is lost
PH_SRV_BLOCCATOVeilLock icon, Phone locked and a fixed sentence
PH_SRV_COLLEGATO, PH_SRV_CHIUSONothing—
Table 11.4 — What covers the shell, by connection state

A phone whose screen was turned off by the system or by the power button (schermo_spento) gets the lock veil too, and its streams stop.

Ordered shutdown (ph_ossatura_chiudi, used by the program and by demo-ossatura so the demo tests the real sequence): (1) the window is hidden and destroyed; (2) ph_shell_libera destroys the root itself, so the destroy handlers of the pieces run once, with PhShell and the services still alive, and streams are closed; (3) only then ph_servizi_libera closes the connection, and the guardians restore the phone. After each step the pending main-loop work is drained. A second defence, the registry of live objects in src/shell/comune/ascoltatori.c, makes ph_srv_smetti and ph_shell_smetti harmless after release. The rule for pieces: in the root's destroy stop listening with all the *_smetti functions and keep your own reference to the widgets as long as listeners exist.

11.6 · The pieces of the shell

Short descriptions of the pieces; the real behavior is in each folder's code and in its COMPITO.md.

PieceBehavior verified in the code
Bar48 px at the bottom. Left to right: launcher button, separator, one entry per open inner window (icon or initials placeholder, indicator under it: active, open, minimized), then the system area: send, receive, volume, phone status, notifications (the last three are created by the system piece and only placed here). Clicking an entry calls ph_shell_clic_barra. A right click opens the bar menu (PH_POPUP_MENU_BARRA): close the app, pin or unpin. Pinned apps are per phone, at most PH_CFG_MAX_FISSATE (16) and stay on the bar when closed. The clock opens the calendar popup.
LauncherGrid of the phone's apps with a search field (a case-insensitive match; Enter opens the first result). The panel is centered horizontally, 60% of the area wide (at least 480, at most 960 px; if the area is narrower than 528 px it stays 24 px from the edges), its top at 6% of the height (at least 24 px) and its height that of the content, up to 76% of the height above the bar; the search field stays at the top and the grid scrolls vertically. Icons are 60 px, columns 112 px wide (as many as fit the inner width), 28 px between rows; a click outside the panel closes it (the shell's popup veil). The measures are in PH_LAUNCHER_* and ph_launcher_misure (src/shell/launcher/logica.h), applied by misure_aggiorna in launcher.c; this replaces the measures of the specification. Known limit: when the window is resized with the launcher open, the old measures hold for one frame. Click opens, drag starts a drag to the desktop (the launcher closes when the drag starts), right click offers open and add to or remove from the desktop, plus pin.
DesktopWallpaper (solid, gradient or an image taken from the phone and saved in the cache), icon grid with cells of 92×96 starting at 16,16, and widgets. The catalog in src/shell/desktop/widget.c has Clock, Calendar, Phone status, Recent notifications, Phone storage, Weather, Month calendar, Next alarm, Battery in detail, Quick switches, Frequent apps and Recent transfers. Find-my-phone is compiled out (PH_DSK_TROVA_OFFERTO is 0), and the types note and riproduzione exist in the profile format but are not in the catalog.
Inner windowTitle bar of 50 px with Back on the left, then the name, and on the right the REC marker (just before screenshot), screenshot, record, more (⋮), minimize, maximize, close, as round buttons of 30 px that show only their symbol until the pointer passes over them (Close turns coral); in very narrow windows (such as the minimum, 288 px; the room for the name is the width minus 270 px) the name has no room and is not shown. Light frame, corner radius 24 px (0 when maximized or snapped, with no shadow and no border); border and highlight line are drawn by a child (ph-finestra-app-filo) drawn over the whole frame without moving the other children, so the children stay where finestre.h puts them. A window that is not active keeps the same fill, with name and symbols dimmed and a lighter shadow. Glass. GTK has no backdrop filter, so behind the title bar only (50 px) the frame, in its own snapshot, redraws what lies under the window, blurred (Gaussian, deviation 26 px) and more saturated (1.6): the widgets drawn before it, that is the desktop layer and the windows below. Each is taken through a GtkWidgetPaintable, which reuses the drawing already made and signals when it changes; for the other windows the paintables of their children are used, not the frame's, so blurs are not nested. On top comes the CSS background of the title, a white veil at 58% (42% when the window is not active). The rest of the window is covered by the opaque content and is not blurred. The mode is decided when the frame is realized, by the one rule of the whole shell (ph_shell_vetro_decidi, see Glass surfaces below); if it is off, or the frame is not inside the shell's root, the frame keeps its almost opaque fill (94%) and the title bar is plain. The automatic tests of this glass are shell-finestra-app-vetro and shell-finestra-app-vetro-menu. Colours, radius and shadows are the --ph-vetro-* variables of src/shell/ossatura/base.css, used by finestra-app.css; resize handle of 18 px; shortcuts Ctrl+R rotate, Ctrl+W close app, Ctrl+Shift+C copy screenshot. Rules for geometry and density live in src/finestre/ (chapter 12).
Video surfaceSee the next section.
SystemNotification panel (hiding applies only inside the shell; an updated notification becomes visible again), toasts (5.2 s for a phone notification, 3.2 s for an information notice), a desktop notice through GNotification when the host window is not visible, the phone popup with the mirror switch and the physical panel switch, and the volume popup.
TransferSend and receive panels with queues, the folder navigator and the APK confirmation (chapter 13).
ConnectionCard over the default gradient: instructions and a search spinner when no phone was ever paired; a code field and a pair button when the phone does not know the PC, an expander for typing an address and port by hand, and a Search again button. The code is read at click, passed to ph_srv_abbina, and the field is emptied after every attempt. Pairing code, addresses, ports and serial numbers never reach disk or logs.
Table 11.5 — The pieces of the shell, in short

11.7 · The video surface

Each video stream is shown by one GtkPicture inside a GtkGraphicsOffload with a black background (src/shell/superficie/superficie.c). The surface owns its PhSrvFlusso, opens it, and runs one reader thread that loops on ph_srv_flusso_leggi with a 100 ms timeout.

  • Hand-over. The reader keeps at most one frame waiting: a new frame replaces the old one and releases it, and at most one ph_shell_consegna is in flight. Frames are dropped, never resolution (ph_sup_scambio_metti).
  • Without copies. A PH_FOTO_DMABUF frame becomes a GdkDmabufTextureBuilder texture (fd, offsets, strides, modifier; for YUV formats the color state from PhFotoColore, BT.709 or BT.601, limited or full range). A PH_FOTO_MEMORIA frame becomes gdk_memory_texture_new over a GBytes that wraps the data. Frames are checked first (sizes 1 to 8192, 1 to PH_FOTO_PIANI_MAX planes, valid descriptors): an invalid one is released and discarded.
  • Fallbacks are recorded. If GTK refuses a DMA-BUF, the stream goes to memory and a line is written with ph_shell_decisione: [decisione] HH:MM:SS.mmm <what> - causa: <cause> on stderr, never with personal data.
  • Under load. The surface of the foreground window never gives up by itself; the others show one frame in two, then one in four, until the queue is empty (ph_superficie_primo_piano). Resolution is never lowered.
  • States shown by the surface itself: the protected-screen message, and, when the connection is lost, the last image blurred with Reconnect now and Close.
  • Closing: ph_srv_flusso_interrompi, wait for the reader thread (at most the read timeout), then ph_srv_flusso_chiudi on the GTK thread; idempotent, and no callback arrives afterwards.
  • Counters: with the environment variable PH_SUPERFICIE_STAT set to 1, one line every 5 s on stderr per stream.
!
Not confirmed. the GTK 4.18 test on one machine never printed an "Attaching … GdkDmabufTexture" message, so the last step, direct scan-out of the frames, is not confirmed (see 21.1 “The known problems at a glance”).

11.8 · Style, resources and accessibility

Each piece has its CSS file, compiled into the executable as a GResource at /it/yasde/shell/<piece>.css and loaded by the piece's own _installa with ph_shell_stile_carica. The base style, src/shell/ossatura/base.css (compiled by the common piece as base.css), is loaded by ph_shell_nuova and holds the --ph-* color variables and the shared classes (ph-pannello, ph-dialogo, ph-menu, ph-tb, ph-riga, ph-pbtn, ph-ghost, ph-accento, ph-pillola, ph-campo, …).

  • A piece uses only classes prefixed ph-<piece>-. It is GTK CSS, not web CSS: no gap, max-width or position; sizes come from min-width, margins or code.
  • No GtkStyleContext per widget and no inline CSS, except computed colors (the user's wallpaper color, placeholder colors).
  • Icons are the mockup's SVG paths drawn in the text color (ph_shell_icona_nuova, PhShellIcona), with round line caps and joins unless the field spigoli_vivi is true (butt caps and mitered joins, GSK_LINE_CAP_BUTT / GSK_LINE_JOIN_MITER); it is true only for the seven title symbols of the inner windows, which follow docs/DESIGN_FINESTRE.md and not the mockup (checked by prova_comune.c); missing app icons become a colored square with initials (ph_shell_segnaposto_nuovo).
  • Every piece's logic test loads its CSS (ph_shell_stile_controlla) and fails on any syntax error.
  • The look is glass, not the mockup's dark colours: the mockup stays the reference for the layout only. Bar, launcher, panels, menus, dialogs and widgets are glass surfaces (next point); the host window and system dialogs follow the system theme.
  • Glass surfaces. A piece registers a widget with ph_shell_vetro_registra(sh, w, radius, type) (src/shell/shell.h, section “Vetro”; implementation in src/shell/comune/vetro.c). The shell gives it the CSS class ph-vetro-chiaro (light) or ph-vetro-scuro (dark); the classes in base.css give the veil, the edge (light: border and long shadow; dark: a thin light line on top) and the text colours. When the graphics card draws, the graphics card draws, the layered root draws behind it, inside its rounded rectangle (the same radius as its CSS), what lies in the layers below it, blurred and more saturated through GtkWidgetPaintable (light: deviation 26 px, saturation 1.6; dark: 20 px, 1.4). The rule is one for the whole shell (ph_shell_vetro_per_renderer): blur only with GskGLRenderer, GskNglRenderer or GskVulkanRenderer; the environment variable YASDE_SFOCATURA (0 or 1) overrides it (ph_shell_vetro_decidi). When blur is on the root has the class ph-vetro-attivo; without a graphics card the surfaces have an almost opaque fill, never a translucent veil without blur. Blurs are never nested: a registered surface is drawn whole in the snapshot of whoever is above it (without its own blur, with its veil, border and shadow), while a widget that draws its own blur (the frame of an inner window, marked with ph_shell_vetro_proprio) is drawn from its children. Known limits (the first and the last are written in the code, the connection card one follows from the mechanism): behind a surface only what lies in the layers below it is seen, not what lies under it in the same layer (an icon under a desktop widget stays sharp; behind the connection card the blur is covered by the screen's own background); the CSS opacity of a surface does not apply to its blur.
  • Which surfaces are glass. Dark: the bar. Light: the launcher and its menu, the system popups, the notice (toast), the transfer panels, the desktop widgets, the menus and dialogs of the desktop, the calendar and the menu of the bar, the ⋮ menu of the inner window, the connection card. Not glass: the lock veil, the “Drop to send” frame (it stays a dark veil), the icons and names on the desktop, the PC window.
  • Theme. Inside a light surface the --ph-* variables change value: text #10202E, #2F4558, #3A4D5F (three levels), accent #1F7A8C (only as a background), and new variables for text that must stay readable on light: --ph-accento-testo (accent as text), --ph-errore, --ph-avviso, plus focus, field text, ghost border and progress track; the nearest surface wins, so a dark one inside a light one restores the dark values. The full list is in base.css and in src/shell/CONTRATTI.md, section 6. Rule for the pieces: no hand-written content colour in their CSS, only --ph-* variables; a colour that is data (an icon, a category) stays with a same-line comment colore-dato: reason, and every piece's test checks it with src/shell/prova_css.h. A piece never sets background, border or shadow on a registered widget.
  • Glass tests. shell-comune-vetro (the registry and the rule), shell-finestra-app-vetro and shell-finestra-app-vetro-menu (the title bar and the ⋮ menu), shell-desktop-vetro (widgets, menu, dialogs), and each piece's own tests check that its surfaces carry the right class.
  • Cost of the blur. Measured on 24 Nov 2026 on the development tablet, fake phone, four video windows at 60 frames/s, Vulkan renderer; median / 95th percentile of the draw time: without blur 5.1 / 7.2 ms; blur on the windows only 7.1 / 10.0 ms; with the launcher open above the windows 8.5 / 12.8 ms. No frame lost; CPU time of the program about +50%.
  • Readability limit. With the 58% veil over a very dark or very bright wallpaper the secondary levels of text lose contrast (only the main text stays full), and the dark bar over a white background turns grey.
  • Accessibility: everything clickable is a real control reachable with Tab, with a visible focus ring; labels go through ph_shell_etichetta, ph_shell_espanso and ph_shell_premuto.

The renderer is not forced by the program: GTK chooses it. The development scripts that open demos on the tablet export GSK_RENDERER=vulkan unless the variable is already set.

11.9 · The fake backend

The fake backend (src/shell/finto/, finto means fake) is a simulated phone in memory, used by every demo and by the piece tests. Nothing is written to disk and no real file is sent.

  • It simulates the connection (searching, then connected after 300 ms; lock, drop and return on command), a list of apps with generated icons, notifications, battery, a folder tree with thumbnails, transfers that advance every 300 ms, synthetic video streams at 60 frames per second (in memory, or in DMA-BUF with the dmabuf option), volume, clipboard, profile and preferences, APK installation, screenshot (a real PNG) and simulated recording, and the data of the new widgets.
  • It also simulates a first connection: PhFintoInizio can start the phone as connected, as not paired (fake codes: 123456 is right, 000000 means the code screen is not open on the phone, anything else is wrong) or as searching.
  • Every command received (input, panel, …) is written on stderr with the prefix finto:.
  • Each piece has a demo, demo-<piece>, built by its meson.build. strumenti/demo-sul-tablet.sh opens it on the test tablet; strumenti/foto-demo.sh opens it on an invisible screen and saves PNG photographs, which is how a piece's look is compared with the mockup (16.1 “Tests of the PC pieces”).
  • demo-ossatura is the whole shell with the pieces present, over the fake backend.
Chapter 12

Windows and density

12.1 · The window rules

The rules of the inner windows are pure logic in src/finestre/: no graphics, no phone, no internal clock (the time arrives as a parameter, in milliseconds, non-decreasing), one thread. The shell piece src/shell/finestra-app/ only draws what these rules decide and feeds them events. The header src/finestre/finestre.h is the contract; the tests are in src/finestre/prova_finestre.c.

Coordinates are the shell's logical units (physical pixels divided by the shell scale), with the origin at the top-left corner of the usable area, which is the root minus the 48 px bar (PH_FIN_BARRA_H). Pointers are double, rectangles are integers. Return values follow the project convention: 0 or -1 with a PhErrore; a pointer or id of 0 is an error. At most PH_FIN_MAX (64) windows are open at once.

ConstantValueMeaning
PH_FIN_TITOLO_H50Window title bar
PH_FIN_CROM_H70Title bar plus technical foot (PH_FIN_PIE_H, 20 px); taken from the content only when the foot is on, otherwise only the 50 px of the title
PH_FIN_PULS30Round title buttons, centred vertically in the title bar
PH_FIN_PULS_DIST, PH_FIN_PULS_MARG_DX, PH_FIN_PULS_MARG_SX4, 14, 22Gap between two buttons; margin from the right edge to the right-hand group; margin from the left edge to Back
PH_FIN_ANGOLO18Resize handle, bottom right
PH_FIN_MIN_W × PH_FIN_MIN_H288 × 180Minimum size when resizing (288 = 22 + 7 buttons of 30 + 6 gaps of 4 + 14, plus 18 px: the seven buttons fit without overlapping, the app name has no room)
PH_FIN_VISIBILE_MIN96Pixels of a window that must stay inside the area horizontally
PH_FIN_AGG_LATO, PH_FIN_AGG_ALTO14, 10Snap distance from the side edges and from the top
PH_FIN_ASSESTA_MS300Settle time without size changes before the phone is asked
PH_FIN_DENS_PASSO20Step of the automatic effective density, in dpi
PH_FIN_FLUSSO_MIN, PH_FIN_FLUSSO_TETTO64, 2560Smallest side and default cap of the stream
PH_FIN_DENSITA_RIF160Reference dpi of a shell at scale 1
PH_FIN_DENSITA_MIN – PH_FIN_DENSITA_MAX50 – 2000Accepted densities
PH_FIN_MARGINE_AREA16Margin left per side when a default size must shrink to fit
Table 12.1 — Constants of src/finestre/finestre.h

12.2 · Order, snapping and gestures

Order, snapping and the gestures follow the mockup unless a comment in the header says SCELTA (choice).

  • Opening (ph_fin_apri): if the app already has a window it is restored, brought to the front and made active (no new window). Otherwise a cascade places it at x = 70 + n·40, y = 30 + n·30 with n the number of open windows (the mirror excluded) modulo 6, then brings it inside the area. The mirror opens at x = 640, y = 20 with no cascade. With the preference riapri_dove_eri (reopen where you were) on, position and size come from the remembered rectangle of the app.
  • Depth. Windows are kept in depth order, minimized ones included (ph_fin_ordine). Closing leaves no window active; minimizing an active window leaves none active either.
  • Dragging (title bar): the window follows the pointer. At the bottom it may go past the area until only the title bar is visible (y is limited to the area height minus the title height); at the top never, so the title stays grabbable; horizontally at least 96 px stay visible. A click without movement neither detaches nor snaps.
  • Snapping (resizable windows only): pointer within 14 px of the left or right edge gives the left or right half, within 10 px of the top gives maximize; ph_fin_gesto_anteprima returns the rectangle for the preview. A snapped window follows the area; on the first movement of a drag it detaches and recovers its previous size, keeping the pointer at the same horizontal proportion of the title.
  • Resizing (corner handle): size = original + displacement, at least 288×180, at most up to the right edge and the bar. No request goes to the phone during the gesture.
  • Maximize / restore: toggles, and restore returns to the arrangement before (also from snapped). Rotate (Ctrl+R) swaps the width and height of the content, within the area.
  • Minimize is a separate flag from the arrangement: restoring returns to what it was. A minimized window's stream is paused (ph_fa_pausa_voluta): the shell also pauses every stream when the host window is not visible, and before pausing any open touch is closed.
  • Bar click (ph_fin_clic_barra): in front goes minimized, minimized goes restored, otherwise it comes to the front.
  • When the area shrinks (host window, full screen, scale: ph_fin_imposta_host): each normal window remembers the size it was given by the user (the one at opening, or the last resize, rotation or return to resizable) and its effective size is that one, reduced only as much as needed to fit; so a window shrunk by a small area grows back when the area grows. A window that was fully inside is brought fully inside; one the user had pushed out is moved only as much as keeps the title bar and 96 px visible.
  • Registration in progress (ph_fin_imposta_registrazione): resizing, unsnapping, maximize, snap and rotate are refused and nothing is asked of the phone until it ends (moving is still allowed), because the size of a recording cannot change.

12.3 · Input translation

A window's input goes to the phone in the video's own coordinates. ph_fin_trova finds the topmost non-minimized window under a point and returns its zone: PH_FIN_ZONA_TITOLO, PH_FIN_ZONA_PULSANTE (with the button), PH_FIN_ZONA_CONTENUTO, PH_FIN_ZONA_ANGOLO or none.

  • For the content the point is converted to the video: vx = x · video_w / drawn width, always inside 0 ≤ vx < video_w and truncated by the injector. The phone also receives video_w and video_h, and drops the event if they no longer match its display.
  • At rest the image keeps the video's proportions, with bands at the sides when the area has other proportions. The shell therefore applies the same formula to the image rectangle (ph_fa_traduci_immagine with ph_superficie_rettangolo_immagine): a point in a band is not input; a touch already begun is clamped into the image, because a touch that started in a window stays its own until release.
  • In automatic density the image is drawn 1:1 in the top-left corner of the content (PhFinInfo.utile_w × utile_h physical pixels, multiples of 8); the margin to the right and below (up to 7 physical pixels) is filled with the window background and a point in it is content with valido false. The origin must also fall on a whole physical pixel (ph_fa_origine_pixel_intero).
  • Wheel: one notch is 120; a touchpad sends fractions that are accumulated without losing the remainder (ph_fa_passi_rotella). The conversion from GTK's direction to Android's is done once, by the caller.
  • Ctrl + wheel is zoom. The window turns it into a simulated pinch at the pointer position (a protocol message with steps in 120ths; chapter 10). The normal wheel is not sent in that case. The gesture opens at the first step, sends one step per event, and ends PH_FA_PIZZICO_FINE_MS (250 ms) after the last step, when Ctrl is released, when the pointer leaves, on focus loss, and before any touch. The phone always closes the gesture (by itself after 400 ms without steps). Touchpad pinch gestures (GtkGestureZoom) are also translated (a ratio of 1.25 per 120 steps), and a touchscreen pinch cancels the first finger's touch when the zoom starts; during a window move or resize zoom is refused.
  • Reserved keys (ph_fa_tasto_riservato): Ctrl+R, Ctrl+W, Ctrl+Shift+C and F11 never go to the phone. Printable characters without Ctrl and Alt are sent as text (so capitals, accents and foreign layouts arrive right); everything else is an Android key code (ph_fa_tasto_android).

12.4 · The density rule

Every app window follows one rule, like Samsung DeX: the stream is the content of the window in physical pixels (1:1), and the density is 160 times the shell scale, so one dp is about one logical pixel of the shell. The rule is in misura_di_ex in src/finestre/finestre.c and is explained in the header comment of finestre.h.

Content in physical pxw × h of the inner windowFixed density?Fixed: stream = content × density / 160pixels reduced above the cap, density keptAutomatic: stream = content, 1:1density = 160 × shell scale (steps of 20), never above the phone'sNarrower than the phone (w < Wt)density lowered so the app sees Wt pointsyesnoFigure 12.1 — How the stream size and the density of an app window are chosen (automatic rule on the right)
  • Stream. Under the cap the stream is exactly the usable content (multiples of 8, minimum 64). Above the cap PH_FIN_FLUSSO_TETTO (2560 per side; the larger side decides, both sides are scaled by the same factor) the pixels are reduced in proportion, never the density: flusso = content · density_app / 160 is only the old fixed-density rule.
  • Density. ceil20(max(50, 160 · k)) with k the shell scale (or less when above the cap), never above the phone's own density. Steps of 20 dpi (PH_FIN_DENS_PASSO). Nothing depends on a threshold: PhFinInfo.tablet (the short side of the content is at least PH_FIN_TABLET_LATO = 600 logical px) is information only and changes no calculation.
  • Minimum width. An app never sees fewer points of width than the phone's screen has (Wt, for example 384 for 1080 px at 450 dpi). With f = min(1, w / Wt), under Wt the density is the integer floor(flux_w · 160 / Wt) (rounded down, so the points seen, truncated as Android does, stay at least Wt): 384 gives 160 dpi, 288 gives 120, 240 gives 100. PhFinInfo.fattore and punti_w, punti_h report it.
  • Fixed density. If the profile has densita_app greater than 0 the user's value is used, fixed (ph_fa_densita_automatica is false and ph_fin_imposta_densita_automatica(false)): the flux is content · density / 160 and pixels shrink above the cap. The profile accepts 72–960 dpi or 0.
  • The default size of a phone-shaped window and of the mirror is the phone's screen in points (px · 160 / density: 1080×2340 at 450 dpi is 384×832, one point is one logical pixel), always portrait for phone-shaped and generic windows, reduced in proportion to fit the area (margin 16 per side, content never narrower than min(288, area)) and snapped to multiples of 8 physical pixels. Without the phone's screen the fallbacks are PH_FIN_TEL_W × PH_FIN_TEL_H (296 × 490) for phone-shaped windows and the mirror, and PH_FIN_GENERICA_W × PH_FIN_GENERICA_H (384 × 442) for generic windows.
  • When the phone is asked. ph_fin_avanza runs on every frame (a tick callback) and returns the windows whose stream size or density has been unchanged for 300 ms and differs from the last request: the shell sends it as a resize with density (ph_superficie_ridimensiona_densita). During the gesture, minimized, or while recording, nothing is asked.

12.5 · Apps that cannot be resized

An app that cannot be resized stays as it is: the phone says so (PhSrvApp.solo_verticale: the launch activity declares a portrait orientation and is not resizable), and its window keeps a phone shape.

  • No resize from the edges (puo_ridimensionare false), no maximize (puo_ingrandire), no snapping (puo_agganciare); the commands show as disabled, and calling the function anyway returns -1 without changing anything. It can still be moved, minimized, restored and closed. Rotate is refused too.
  • The information may arrive after the window opens (ph_fin_imposta_solo_verticale): an enlarged, snapped or wide window then returns to the phone shape in the same place; the stream changes size once, with the request at settled movement. On a minimized window the shape changes at once and the request leaves 300 ms after restore; while recording, the shape changes but nothing goes to the phone until the end.
  • The window sizes are recomputed (reduced in proportion) when the area shrinks, never stretched.

12.6 · Compatibility

Some apps draw themselves small, gathered in a corner, because they use the density of the phone's real screen while the window, the activity and the process see that of the virtual screen. The user decides, per app, with the Compatibility switch.

  • Where: the ⋮ menu of the window (PH_POPUP_ALTRI_COMANDI), after Rotate and before Close app, as a check item with a smaller grey line under it (For apps that look too small). Disabled during a recording and absent in the mirror.
  • State: per package, in the phone's profile (the [[compatibilita]] list, at most PH_CFG_MAX_COMPAT = 128), written only when the user changes the switch. The next time the app opens it is already on.
  • Effect (ph_fin_imposta_compatibilita): the window uses the fixed-density rule with the phone's real density D, whatever the global rule says. With f = min(1, w / Wt) the stream is (w / f, h / f) · D / 160 in multiples of 8, minimum 64. Above the cap the pixels are reduced in proportion and the density stays D (the app sees fewer points, and the surface enlarges the image): the density is never lowered, since the difference of density is what shrinks these apps. The image is not 1:1: the GPU scales it, and that is expected. A 384×832-point window at 450 dpi asks for about 1080×2340, the phone's screen.
  • On change: the window stays open, the new size and density are asked with a resize (the next ph_fin_avanza answers at once, without the settle wait). No session is reopened. It was confirmed live that the app adapts immediately.
  • Refused (-1, nothing changes): the mirror, an unknown id, and a recording in progress.

12.7 · The mirror window

The mirror is the window that shows the phone's real screen (the app with an empty package, key phone in finestre.h). It is opened from the phone status popup with Show the phone screen and closed from the same switch.

  • Fixed shape: like a non-resizable app it cannot be resized, maximized or snapped (even if created with solo_verticale false). Its proportion is that of the phone's screen as it is, landscape included. ph_fin_misura_flusso returns an error for it and ph_fin_avanza never names it: the size of the stream is decided by the phone.
  • Stream size: ph_ossatura_misura_specchio takes the phone's screen to multiples of 8 inside 64 to 1920 per side without deforming it (cap of 1920); the window first asks with SPECCHIO_FLUSSO_W × SPECCHIO_FLUSSO_H = 288 × 512 as a placeholder that the backend ignores for the mirror.
  • No density: density is 0 and the Compatibility entry is absent. If the phone rotates while the mirror is open, the window stays as it is and the image appears with bands.
  • Closing: the mirror closes without touching the recents list; closing an app window removes the app from the recents (togli_task).

12.8 · What is remembered

What is saved, and where.

WhatWhereWritten by
Remembered rectangle per app ([[finestra]], at most 64)Phone profileWindows piece, through ph_fa_ricordi_a_profilo; the mirror is never saved
Fixed density ([app] densita)Phone profileRead by the windows piece; 0 means the automatic rule
Compatibility listPhone profileWindows piece, only on user change
Opening counts ([[apertura]])Phone profileWindows piece: one count per new window of an app, not for the mirror, a raise or a restore
esc_indietro, riapri_dove_eriPreferencesRead only; the program has no interface that changes preferences
Table 12.2 — Persistent data of the windows (formats in 14.1 “Files and folders on the PC”)
i
Short keys. the app names given to finestre.h are at most PH_FIN_APP_MAX (48) bytes, shorter than a package name. The shell keeps a table package ↔ short key (a1, a2, …; phone for the mirror) in PhFaChiavi, and converts in both directions, also for the remembered rectangles.
!
Header out of date. the comment at the top of src/finestre/finestre.h (point 1 of the deviations) still says a dragged window stays above the bar; the code (src/finestre/finestre.c) lets it go down until only the title bar is visible.
Chapter 13

Files and transfers

13.1 · The file layer

Files move over the ADB connection with the sync: service (chapter 4). Three pieces share the work, from the bottom up: src/file/ (copy and listing, no queue), src/trasferimenti/ (the queue and the APK installer, no graphics) and src/shell/trasferimento/ (panels, navigator, drag and drop). The shell reaches them only through ph_srv_tr_* and ph_srv_apk_installa of the services.

Function (src/file/file.h)Behavior
ph_file_inviaPC to phone. The remote file is created or replaced (choosing a free name is the caller's job); the local modification time is kept; if cancelled or failed midway the partial file on the phone is removed.
ph_file_riceviPhone to PC. Writes <local>.parziale created exclusively (if it exists: PH_FILE_ESISTE, nothing touched) and renames at the end; never replaces a user's file, except an empty regular file the caller placed as a name reservation. The file gets the phone's modification time. Cancelled or failed: the partial file is deleted.
ph_file_elencaA folder of the phone without . and .., sorted folders first, then files, by name ignoring case. Hidden files are included; whoever displays filters them.
ph_file_infoOne path of the phone.
Table 13.1 — The copy and listing functions

Results are PhFileEsito: PH_FILE_RIUSCITO, PH_FILE_ERRORE, PH_FILE_ANNULLATO, PH_FILE_NON_TROVATO, PH_FILE_NON_CONSENTITO (Android denies access) and PH_FILE_ESISTE. Every operation opens its own sync: channel, so several can run at once from different threads. A transfer that sees no data for PH_FILE_ATTESA_MS (30 s) fails; reads proceed in slices of PH_FILE_FETTA_MS (200 ms) so that cancellation is noticed quickly.

13.2 · The transfer queue

The queue (src/trasferimenti/trasferimenti.h) has one worker thread and does one transfer at a time, in order. Its functions may be called from any thread; only ph_tr_chiudi must be called once, with no other thread using the queue.

Panel / dropGTK threadph_srv_tr_accodaservices, GTK threadph_tr_accodaqueue (one worker)ph_file_invia / ph_file_ricevisync: channel to the phonePhTrAvvisofrom the worker threadSnapshot + eventPH_SRV_EV_TRASFERIMENTIPanels updaterows in placeFigure 13.1 — The path of a transfer, from the panel to the phone and back as an event
  • Adding (ph_tr_accoda): does not block and does not talk to the phone. Send: the origin is a regular file of the PC and the destination folder is any absolute path on the phone (/sdcard means /storage/emulated/0; the phone creates the folder if missing). Receive: the origin is a file of the phone and the PC folder must exist. For N dropped files the call is made N times.
  • States (PhTrStato): waiting, in progress, completed, failed (the error is the sentence to show), cancelled. Ids start at 1, grow and are never reused.
  • Free name rule (never overwrite): if folder/name exists, name (1).ext, name (2).ext … until one is free. The extension is from the last dot, only if the dot is not the first character, at least one and at most 8 visible characters follow; so .bashrc and Makefile have none. A compression extension after .tar makes a double extension (a.tar.gz becomes a (1).tar.gz). The number goes before the extension; a name over 255 bytes is shortened before the number without splitting a UTF-8 character.
  • On the PC the name is reserved at start with an exclusive creation (O_EXCL) of an empty file that the received file replaces. A name is free only if both the destination and <dest>.parziale are (so a name has at most 255 − 9 bytes); if one appears in the meantime ph_file_ricevi answers PH_FILE_ESISTE and the queue retries with the next number, up to 20 times. On the phone the comparison ignores case, and two entries never choose the same destination even if neither has started; every entry shows a provisional name that at start can only go up in number.
  • Cancel (ph_tr_annulla, ph_tr_annulla_tutto): a waiting entry becomes cancelled at once and will not start; one in progress stops copying, the partial file disappears, and it becomes cancelled when the copy stops (if the copy had already finished it may be completed instead: look at the final state).
  • Notices (PhTrAvviso): always from the worker thread, at every state change and, while copying, at most about 10 per second per entry; the final state of every entry always arrives. What the caller does (add, cancel a waiting entry, empty) generates no notice. A notice with a null entry means the queue stopped.
  • Lost connection: the entry in progress fails with its sentence, the others stay waiting, and the queue stops (ph_tr_coda_ferma true before the notice). It stays stopped until the caller calls ph_tr_riprendi or ph_tr_svuota. In the real services, a new session resumes the waiting entries and records it with ph_shell_decisione (sv_tr_sessione_nuova in src/shell/ossatura/sv_tr.c).
  • Media scanner: after a sent file (not after a received one) the phone is told that a new file exists with a fixed command built by ph_tr_comando_scanner: the path is percent-encoded, then put between single quotes, so no character of a name can leave the quotes.
  • Shutdown: ph_tr_chiudi cancels the transfer in progress (the partial file disappears), drops the remaining entries, and after it returns the connection can be closed.

13.3 · The panels

The shell piece (src/shell/trasferimento/) has two panels, send and receive, opened by the bar buttons (ph_shell_trasferimento_apri). A dot on a bar button shows that a queue of that direction has work.

  • Send. A drop zone, a button to choose files from the PC, and the destination folder on the phone with a change button. A GtkDropTarget of GDK_TYPE_FILE_LIST on the root accepts files dropped anywhere in the window (the PH_STRATO_RILASCIO layer shows the drop box); non-local files are skipped, and folders and unreadable files are not sent, with a notice.
  • Receive. The phone's folder listing with multiple selection that stays when changing folder, a search of files and folders, and the destination folder on the PC.
  • Destinations. Send folder: the profile's cartella_invio, otherwise /storage/emulated/0/Download. Receive folder: the first valid of the profile's cartella_ricezione, the preference cartella_ricevuti, the user's Download folder, the home folder, and finally /. The last chosen folder is saved in the profile.
  • Queue rows. At most PH_TRF_ELENCO_MAX (12) rows per direction: in progress first, then waiting in queue order, then the latest finished; if the active ones do not fit, a line says how many more are waiting. Each row has a progress bar, a cross to cancel that entry and a button that cancels the whole queue of that direction. Rows update in place so scrolling and focus stay.
  • After a transfer only a notice appears; no panel opens.
  • Recent transfers widget (desktop): the last completed ones of the session, kept in memory by the common piece; filenames are never written to disk or logs.

13.4 · The folder navigator

One navigator (PhNav in src/shell/trasferimento/navigatore.c) serves three lists.

Mode (PhNavModo)What it is
PH_NAV_TEL_CARTELLEFolder chooser of the phone inside the send panel: Up, a typeable path, a folder search, the list of subfolders, New folder, Use this folder
PH_NAV_TEL_FILEReceive list: Up, path, search of files and folders, multiple selection kept across folders
PH_NAV_PC_CARTELLEFolder chooser of the PC: like the first, without search; the path is shown and also typeable; read with GIO, asynchronously
Table 13.2 — The three modes of the navigator
  • Paths. ph_trf_normalizza cleans what the user types: spaces trimmed, a leading / added, /sdcard (any case) becomes the internal storage, // and /. removed, .. resolved and never above /, trailing slashes removed. It rejects invalid UTF-8, control characters, and paths longer than PH_TRF_PERCORSO_MAX (4096). For the PC, ~ is the home folder and relative paths start from the shown folder; a missing folder falls back to home.
  • Pages. A list shows PH_TRF_PAGINA (200) entries and then a button with how many more; hidden entries (name starting with a dot, or any hidden part of a search result's path) are filtered.
  • Texts. ph_trf_testo_sicuro makes names displayable: valid UTF-8, control and invisible direction characters replaced, a length limit with an ellipsis. Sizes are shown as B, KB, MB, GB with one decimal from 1 MiB (ph_trf_dimensione), computed in floating point, rounded to tenths and printed from an integer count of tenths, so the decimal separator follows the language of the app, never the language of the PC.
  • Lifecycle. The navigator is reference counted because GIO requests always return, even after it is closed; the owner frees it with ph_nav_distruggi, which cancels everything. A cancelled services request never calls back.
  • The phone's folders are read by the real services with ph_file_elenca on the p_lavori pool; searches are run on the phone's own search channel and can be cancelled. Creating a folder uses a shell command built by ph_ossatura_comando_mkdir with the path in single quotes (a quote inside becomes '\'').

13.5 · Installing and uninstalling APKs

A dropped .apk is not sent as a file. The shell asks for confirmation (ph_trf_apk_chiedi in src/shell/trasferimento/apk.c, a non-blocking GtkAlertDialog with Cancel and Install the app), then installs it with ph_srv_apk_installa, which runs ph_inst_installa from src/trasferimenti/installa.c on the p_installa pool (one at a time). The install row appears at the top of the send list, with progress and a cross.

  • Recognition (ph_inst_riconosci): an APK is a file whose name ends in .apk (any case) and whose content is a zip with an AndroidManifest.xml entry in the central directory. Only the tail and the central directory are read (at most 32 MiB); zip64 files count as not APK. Every length read from the file is checked.
  • Steps (ph_inst_installa): APK check, copy with ph_file_invia to /data/local/tmp/yasde-apk-<8 hex digits>.apk (a random name from /dev/urandom, new at every call), pm install -r, cleanup of the temporary file. Limits: pm install 120 s, pm uninstall 30 s, cleanup 5 s.
  • The temporary file is always deleted after the copy was attempted: on success, refusal, error, cancel or lost connection. If the deletion cannot be confirmed, temporaneo_rimasto is true and the message says it will be removed at the next connection.
  • Cleanup at connection (ph_inst_pulisci): the real services of the skeleton call it whenever they get a new session (src/shell/ossatura/servizi_veri.c), before any install: rm -f /data/local/tmp/yasde-apk-*.apk (a fixed line). It cannot match the component's own files, which are jars and yasde-custode-*.
  • Refusals in plain words. ph_inst_analizza is a pure function that turns the output of pm into a PhInstRisultato: outcome, a PhInstMotivo (already installed, different signature, older version, no space, invalid APK, old Android, wrong architecture, blocked, verification, test-only, cancelled on the phone, system app, not installed, too old target, split missing, other), the INSTALL_FAILED_* code and a translated sentence with no PC path. pm exits with 0 even when it refuses, so the exit code does not count, and Success must be a whole line: an unrecognized answer is an error, never a success by chance.
  • The install is complete only if the outcome is PH_INST_RIUSCITO; the one exception is a pm that does not answer in time (error, and the message says it is unknown whether it was installed).
  • Uninstall (ph_inst_disinstalla) runs pm uninstall <package> after ph_inst_nome_pacchetto_valido (1 to 255 characters of letters, digits, _ and ., first a letter: the only check that lets a name into a command line). It removes the app's data too, and the confirmation the shell shows must say so. If pm refuses a system app the message says it.

13.6 · Temporary files

What can be left behind, and who removes it.

WhereWhatWho cleans it
Phone, /data/local/tmpyasde-apk-<hex>.apkAlways right after the copy; otherwise ph_inst_pulisci at the next connection
PC, next to the destination<name>.parziale (receive in progress)Removed on cancel or failure; never overwrites a user's file
PC, destinationAn empty reserved fileReplaced by the received file; removed if the transfer does not start, when it is still the same file (same device and inode)
PC, configuration and cache folders.name.XXXXXX temporaries of a safe writeph_cfg_pulisci_temporanei(3600) at startup removes those older than an hour
PC, cachesfondo-<n>.png wallpaper images that are named by no profileph_cfg_pulisci_sfondi at startup (see 14.1 “Files and folders on the PC”)
Table 13.3 — Temporary files and their cleanup
Chapter 14

Configuration and language

14.1 · Files and folders on the PC

The piece src/config/ is pure logic: no graphics, no phone. It holds the folders, the file formats, the safe writing and the language tables. On the PC's disk YASDE writes only in two folders, following XDG, and never anything on the phone.

FolderContent
~/.config/YASDE/ (or $XDG_CONFIG_HOME/YASDE)preferenze.toml (preferences), telefoni.toml (known phones), telefono-<serial>.toml (one profile per phone), profilo-<serial>.toml (measurements per phone; not written by the program today, see 14.4 “The measurements file”), chiave.pem (the PC's ADB key)
~/.cache/YASDE/ (or $XDG_CACHE_HOME/YASDE)Wallpaper images sfondo-<n>.png and, from the AppImage launcher, the image loader file (chapter 17)
Table 14.1 — The two folders on the PC
  • An XDG variable that is empty or holds a non-absolute path is ignored, as XDG itself says. Folders are created with mode 0700; if the folder exists it must belong to the user (otherwise writing is refused), and if it is the user's but writable by group or others those permissions are removed.
  • Safe writing (ph_cfg_scrivi_file): a temporary file in the same folder (mode 0600, created exclusively), fsync, rename onto the final name, fsync of the folder. An interruption leaves either the old file or the new one. A killed program may leave a .name.XXXXXX temporary; startup removes those older than an hour (ph_cfg_pulisci_temporanei, a value under 60 s counts as 60).
  • Known limits. If a configuration file is a symbolic link, the rename replaces it with a regular file (the target is untouched). With two instances at once the last write wins, never a half-written file. A configuration file larger than PH_CFG_MAX_FILE (1 MiB) is an error.
  • The serial number is hostile data (it comes from the phone): in a file name it enters only cleaned (ph_cfg_seriale_pulito): [A-Za-z0-9_-] kept, every other byte becomes _, at most 63 characters, and if anything was changed or cut a dash and an 8-digit FNV-1a hash of the original are appended, so AB:CD and AB.CD never share a file. Inside telefoni.toml it stays as it is, because there it is a value and never a path.

14.2 · The file formats and their keys

The format is a subset of TOML written from scratch (src/config/toml.c, toml.h): tables [name], repeated tables [[name]] for lists, quoted strings (valid UTF-8 on one line), 64-bit integers, finite decimals, booleans, and comments with #. Not supported: arrays, inline tables, multi-line strings, dates, hexadecimal integers. Limits: file PH_TOML_MAX_FILE 4 MiB, line 8192 bytes, 1024 tables, 2048 entries per table.

Table.keyType and rangeDefault
preferenze.toml
[generale] linguaauto | it | en: read and ignored (the app is English only)auto
[generale] esc_indietrotrue or false: Esc means Back on the phonetrue
[generale] avvisitrue or false: pop-up noticestrue
[generale] cartella_ricevutipath; the starting receive folder, the phone's own receive folder wins when it existsempty
[generale] widget_nascostitrue or false: hide all widgetsfalse
[generale] riapri_dove_eritrue or false: reopen windows where they werefalse
[shell] scala_automaticatrue or false: shell scale from the systemtrue
[shell] scala0.5 to 4.0, used when the automatic scale is off1.0
telefoni.toml: one [[telefono]] per phone
seriale, nome, indirizzo, vistoserial (required, no duplicates), model name, last address as host:port (IPv6 as [host]:port), last time seen in Unix seconds—
telefono-<serial>.toml: the profile of one phone
[sfondo] tiposolido | sfumato | immaginesfumato
[sfondo] colore_solidocolor #RRGGBB#1f2430
[sfondo] colore_da, colore_agradient colors#0e2638, #1a625f
[sfondo] direzionediagonale (135°) | verticale (180°) | orizzontale (90°) | diagonale-inversa (45°)diagonale
[sfondo] immaginea file name in the cache (valid name: no /, not starting with a dot, only [A-Za-z0-9._-], 1 to 127)empty
[sfondo] adattamentoriempi | adatta | allunga | centrariempi
[[icona]] app, colonna, rigadesktop icon: package, 0 to 255 each; one icon per app, at most PH_CFG_MAX_ICONE (256)—
[[widget]] tipoorologio, stato, notifiche, memoria, calendario, note, meteo, riproduzione, calendario-mese, sveglia, batteria, interruttori, trova, app-frequenti, trasferimenti; an unknown type drops the entry; at most PH_CFG_MAX_WIDGET (32)—
[[widget]] destra, altopixels from the right and top edge, 0 to 1638416
[[widget]] dimensionepiccolo | medio | grandemedio
[[widget]] stile, opzionegraphic variant 0 to 15; style-dependent value 0 to 2550, 0
[audio] volume0 to 100 (the mute is not saved)100
[cartelle] invio, ricezionelast send folder (on the phone) and receive folder (on the PC), empty if noneempty
[app] densita0 (the phone's own) or 72 to 960 dpi: a fixed density chosen by the user0
[[fissata]] apppinned apps of the bar, in order, no duplicates, at most PH_CFG_MAX_FISSATE (16)none
[[apertura]] app, volte, ultimaopening counts for Frequent apps: package, 1 to PH_CFG_MAX_VOLTE, last time in Unix seconds; at most 64 (the least used goes first)none
[meteo] nome, dettaglio, lat_centesimi, lon_centesimithe city chosen by hand: name, detail (region, country), degrees × 100 as integers (−9000..9000, −18000..18000); the section is written only if a city is chosennone
[[compatibilita]] appapps with the Compatibility switch on, at most PH_CFG_MAX_COMPAT (128)none
[[finestra]] app, x, y, larghezza, altezzaremembered window rectangle (one per app, at most 64); x and y −32768..32767, sizes 1..16384none
Table 14.2 — The keys of the three configuration files

Defaults of a new phone. With no file (or a file set aside) the desktop has three medium widgets, Clock, Phone status and Recent notifications, at 16 px from the right edge and 16, 120 and 240 px from the top. A valid file always has the last word: without any [[widget]] there are no widgets.

14.3 · Tolerant reading and set-aside files

A damaged file must never crash the program or destroy data.

  • Syntax error (unclosed quote, huge number, null byte, invalid UTF-8, line too long, a text that is not UTF-8 in the file…): the load function returns -1 with a message riga N: … (the message text is in Italian, like all internal messages) and the structure holds the defaults, never half a structure.
  • Unknown tables and keys are ignored and not rewritten at the next save. A value of the wrong type, out of range, too long or with an unknown name returns that one field to its default, without an error; a list entry with invalid required fields (or a duplicate) is dropped.
  • Missing file: defaults, return 0 (first run).
  • Unreadable file: the *_carica functions rename it to <name>.illeggibile (then .illeggibile.1 … .9; with all taken the oldest is replaced), return the defaults and return 1; the next save therefore destroys nothing. Results: 0 read or missing, 1 set aside, -1 a real error (path, permissions, failed rename). After -1 nothing must be saved, because the file was neither read nor set aside; the skeleton then uses defaults and never saves the preferences.
  • The *_da_testo functions do not touch the disk and return -1 with the line.
  • Wallpaper cleanup (ph_cfg_pulisci_sfondi, once at startup, before threads): reads every telefono-*.toml and removes from the cache the files named exactly sfondo-<1-10 digits>.png that are named by no profile. If even one profile cannot be read nothing is deleted (-2); only regular files of the user are touched, never folders or symlinks; a file modified less than 10 minutes ago stays (a choice in progress). Whoever saves a wallpaper writes the image and saves the profile that names it immediately after.
  • The city of the weather widget is the one position datum allowed on disk, because the user chose it by hand. A name that is empty or too long, a detail that is too long, or coordinates out of range mean no city, without failing the load.

14.4 · The measurements file

A second per-phone file, profilo-<serial>.toml, is handled by src/config/profilo.c (profilo.h): what was measured or observed on a phone, for choosing values next time and for a published table of tested phones. It never holds the serial number or an address; the model is the commercial name (Build.MODEL) and never the name the user gave the device.

Table.keyContent
[profilo] versione, modello, apiformat version (PH_PROF_VERSIONE = 1), model, API level
[encoder] scelto, ripiego, repeat_previous_frame_after_ignoratothe encoder chosen, the fallback used if any, whether forced redraw is needed
[misure] max_flussistreams in parallel without degradation, 1 to 64
[[sintomo]], [[workaround]]nome ([A-Za-z0-9_.-], 1 to 31), nota (at most 128, never goes into the table), data
Table 14.3 — Keys of the measurements file

A key that is absent means "not measured": no value is invented. A file of a future version (versione greater than the program's) is not touched and not renamed: load returns -1 with an empty profile, and the program must not save. Model and encoder strings accept only [A-Za-z0-9 ._+()/,-] (no colon, so no web addresses are formed).

!
Not connected. in this version no code outside src/config/ calls ph_profilo_*: the module and its tests exist, but the file is not yet written or read by the program.

14.5 · Language and the English tables

User-visible text in the code is written in Italian, in ph_t("…") calls, and the English comes from tables compiled into the executable. Since 24 November 2026 the app is English only: ph_lingua_inizializza always sets English, whatever the preference in the file and whatever the PC's environment (an old it or auto is read and ignored).

  • The functions (src/config/lingua.h): ph_t (translation in the active language, never NULL, the pointer lives as long as the program; the Italian text itself when there is no translation or the language is Italian), PH_T_ (a marker for a literal placed in a table: it translates nothing), ph_tv (translates a marked text later; not checked by the scan, only for PH_T_ texts), ph_lingua_componi (placeholders), ph_lingua_traduzione_en (for the test).
  • The argument of ph_t is always a literal (or adjacent literals). ph_t(variable) is an error of the test.
  • Placeholders are written {name} ([A-Za-z_][A-Za-z0-9_]*), not printf: a translation can reorder the words. A literal brace is {{ or }}, and % means nothing. ph_lingua_componi(buf, size, ph_t("…"), "name", value, (const char *)NULL) substitutes them (at most 16 pairs); the model is never a printf format; a NULL value is a caller error (empty string, return (size_t)-1); a result that does not fit is cut on a UTF-8 character boundary.
  • The tables. data/en/*.txt: one line per text, "italian" = "english", a subset of TOML. Files: comune.txt, config.txt, collegamento.txt, installa.txt, and shell-<piece>.txt for most shell pieces (there is none for the launcher or the fake backend; shell-comune.txt holds all the mockup's texts). The texts of the phone (app names, notifications, error sentences of the component) arrive ready and are not translated.
  • The generator (src/config/genera_traduzioni.c) runs at build time under Meson, reads the files and writes a C source with the table sorted by strcmp on the Italian text. A duplicate text (between files or inside one), an empty translation, different placeholders between the two languages, or a syntax error stops the build with the file and line. The list of files is read at configuration: a new file needs meson setup --reconfigure. A duplicate key between two files stops the build of everything.
  • The test (lingua, src/config/prova_lingua.c) scans every src/ source for ph_t("…") and PH_T_("…") calls (skipping comments, strings and characters, joining adjacent literals) and fails if a text has no English translation, if the placeholders differ, or if an argument is not a literal. Comments of .c and .h files are scanned too, so an example call in a comment must not be written.
  • The test proves itself: the generator tests run with deliberately wrong files (src/config/finti/) and must fail (should_fail), and succeed with a good one, so the failures depend on the content. lingua_funzioni tests the functions with a fake table (src/config/tabella_finta.c).
  • A text without a translation makes the lingua test of tutto fail even if its piece is not yet approved, because the scan reads all of src/: the string and its translation are added together.
Chapter 15

Weather

15.1 · What goes out and when

The PC side of the Weather widget is the only place where the YASDE program on the PC opens a connection to the Internet; everything else on the PC stays on the local network with the phone. (The phone itself may use a network service when its own geocoder names a place, see below.) The piece is src/meteo/ (contract meteo.h), and the rules below are written in its header and in src/shell/CONTRATTI.md.

  • When. Only while at least one Weather widget is on the desktop (ph_srv_meteo_osserva). With no such widget no connection is started at all, not even for the place search. There is no separate consent dialog: adding the widget is the choice.
  • Whom. api.open-meteo.com for forecasts and geocoding-api.open-meteo.com for the search of a place written by the user. Both are served over HTTPS on port 443.
  • What leaves the PC. The latitude and longitude of the phone rounded to 0.005° (about 500 m), or those of the city the user chose by hand, or the text the user typed in the place search together with language=en (the language of the shell), plus the fixed parameters of the request. No identifier, no cookie, a generic User-Agent: YASDE/2.1. The servers see the PC's IP address, as with any connection.
  • Where the rounding happens. On the phone, before anything else: the precise position never leaves the phone. The place name is produced by Android's geocoder on the phone, from the already rounded coordinates; the geocoder may itself use a network service of the phone. On the wire and in PhDatiPosizione and ph_meteo_chiedi coordinates are in thousandths of a degree, always multiples of 5; the city chosen by hand stays in hundredths in PhMeteoLuogo and in the profile, and is passed to ph_meteo_chiedi multiplied by 10. The shell never receives the phone's coordinates: only the forecast and, if the phone knows it, the place name.
  • Nothing on disk, nothing in logs. The phone's position and place name never go to disk or to any log, on the phone or on the PC, not even in error messages. The one exception on disk is the city chosen by hand (name, detail and coordinates rounded to 2 decimals in the profile), because it is the user's own choice; not even that, nor the searched text, goes into a log. An error says only its kind (service not responding, invalid answer, invalid certificate).
  • Credit. The line Weather data by Open-Meteo.com with a link to https://open-meteo.com/ is always visible in the widget, in every size and style. Under the place search list, always: Places from GeoNames, via Open-Meteo.com linking to https://www.geonames.org/. The data are under CC BY 4.0; the service is used under Open-Meteo's non-commercial terms.

15.2 · From the widget to the forecast

The chain is: widget, ph_srv_meteo_osserva, the real backend (src/shell/ossatura/sv_meteo.c), which asks the phone for the position (ph_dati_posizione, message 0x90) and then calls ph_meteo_chiedi; the answer is published with ph_servizi_pubblica_meteo and ph_servizi_pubblica_meteo_fonte and reaches the widget as PH_SRV_EV_METEO.

Weather widgetdesktop pieceph_srv_meteo_osservaservices (GTK thread)Backend (sv_meteo.c)ph_dati_posizione 0x90ph_meteo_chiediworker of src/meteoOpen-MeteoHTTPS GETPH_SRV_EV_METEOph_servizi_pubblica_meteo_*Widget redrawsforecast + attributionFigure 15.1 — The chain from the widget to the forecast and back
  • Rhythm. The backend asks again about every 5 minutes while the widget is there; the piece answers from its cache when a valid answer for the same position is younger than PH_METEO_INTERVALLO_S (30 minutes), so in practice the network is used at most once every 30 minutes per position. The cache lives in memory only and holds the last 4 positions.
  • After a failure a new connection for the same position is not started before 5 minutes, then 15, then 30; meanwhile the caller gets the previous error at once, with no connection. A success resets the count. Every started connection counts as an attempt, even if interrupted. Between the start of any two connections at least PH_METEO_AVVII_MIN_MS (5000 ms) pass. No bursts.
  • The piece does not retry by itself: whoever uses it calls ph_meteo_chiedi again, and the rules above decide whether a connection is needed.
  • Position from the phone. The phone answers at once (tens of milliseconds) and never waits for a new position or for its geocoder inside the request. If it starts a background search (ricerca_avviata), the backend asks once more after about 15 s without a new permission. The permission to start such a search is given at most once every 6 hours (sv_prova_meteo_permesso_s).
  • Outcomes of the position: known, turned off (The phone's location is turned off.), denied (YASDE is not allowed to use the phone's location.), unknown (The phone does not know its location yet.). Without a connected phone and without a chosen city the widget says No phone connected: without a location there is no forecast..
  • The city written by hand (menu of the widget, Location…): a dialog with a text field, a Search button and the results list, and None to remove the choice. The search starts only with the button or Enter, never at each key. One city per profile (per phone). Precedence: the phone's position always wins; the chosen city is used only when the phone gives no position (off, denied, none known, phone not connected). ph_srv_meteo_fonte says where the data come from.
  • Place name in the widget: from the phone's geocoder when the position is the phone's, from the chosen result when the city is manual. The title is Weather — {localita}, or just Weather without a name.
  • Unavailable service: the widget says Weather forecast not available right now. with the time of the last data if there is one.
  • Styles. The widget has six drawings (now, hours, week, compact, today, curve; the code names are PH_DSK_METEO_*), chosen from its menu and remembered in the profile.

15.3 · The weather piece

The piece is written from scratch on top of OpenSSL (already a dependency for ADB): no new library.

PartFileBehavior
HTTPSsrc/meteo/tls.cTCP socket, SNI (SSL_set_tlsext_host_name), SSL_set1_host with SSL_VERIFY_PEER: chain and host name verified, an invalid certificate is an error and never ignored. Name resolution with getaddrinfo_a (cancellable, with a deadline), non-blocking connect with poll.
Certificate authoritiessrc/meteo/tls.cThe system's: OpenSSL default paths and, if they are not enough, the first existing of /etc/ssl/certs/ca-certificates.crt, /etc/pki/tls/certs/ca-bundle.crt, /etc/ssl/ca-bundle.pem
HTTP/1.1src/meteo/http.cGET <path> HTTP/1.1, Host, User-Agent: YASDE/2.1, Accept: application/json, Connection: close. The status line must be 200; headers up to 16 KiB; the body with Content-Length or Transfer-Encoding: chunked (chunks checked; both together is refused as ambiguous). No redirects, no compression, no connection reuse.
JSONsrc/meteo/analisi.cph_meteo_analizza: a streaming reader with limited depth (16), checked lengths, numbers read independent of the system language. It takes only utc_offset_seconds, current, hourly and daily; a missing, null or wrong-typed field means "not known", not an error; hours from now on, at most PH_METEO_ORE_MAX (48); days at most PH_METEO_GIORNI_MAX (7).
Request pathsrc/meteo/meteo.cph_meteo_percorso: coordinates in thousandths, limits ±90000 and ±180000 and multiples of 5 (otherwise -1), written with three decimals and always the dot (never printf with a float, so the system language cannot change it): 41895 becomes 41.895, -5 becomes -0.005. Fixed parameters: current, hourly, daily fields, timezone=auto, timeformat=unixtime, forecast_days=7.
Place searchsrc/meteo/meteo.cph_meteo_cerca: GET /v1/search?name=&count=&language=&format=json, at most PH_METEO_LUOGHI_MAX (10) results, text of at most PH_METEO_RICERCA_TESTO_MAX (64) bytes, answer at most PH_METEO_RICERCA_RISPOSTA_MAX (64 KiB), 2 s between searches, at most 10 searches per 10 minutes, the same failed search not before 30 s. Results are rounded to hundredths.
Table 15.1 — The parts of the weather piece
  • Limits. Whole request PH_METEO_LIMITE_S (15 s), answer at most PH_METEO_RISPOSTA_MAX (512 KiB). Cancel stops the request within 1 s. No lock is held during network work.
  • Network data is hostile. The analyzer never reads or writes outside its buffers.
  • Callbacks. The result function is called from the piece's own thread; inside it only ph_meteo_chiedi may be called. ph_meteo_chiudi called inside is refused (nothing happens). After ph_meteo_annulla returns no callback arrives any more.

15.4 · How it is tested

Tests run without Internet (src/meteo/prova/, strumenti/prova.sh meteo):

  • Pure parts: the request path (including with an Italian locale active: the decimal point must stay), the analysis of a saved answer with fake values, missing fields, null, wrong types, arrays of different lengths, truncated or too deeply nested or huge JSON, absurd numbers.
  • A fake local server (a thread listening on 127.0.0.1, TLS with a test certificate generated in the test and a test authority passed to the piece only in test mode) answers with a length, chunked, slowly (deadline), too large, status 500, and a certificate with the wrong name (must be refused). src/meteo/prova/tls_finto.c is the fake TLS side.
  • Cache and frequency with a fake internal clock; cancel and close during a slow request (AddressSanitizer clean, no callback after return). The thread-sanitizer variant is built separately, because the two sanitizers do not mix.
  • The real backend's weather side is tested over fake lower pieces: src/shell/ossatura/prova_meteo_veri.c.
  • The TLS handshake to the real server was tried by hand from the AppImage (handshake and certificate check without sending anything); no real forecast request has been tried yet.
Chapter 16

Testing

16.1 · Tests of the PC pieces

Tests live with the code. One piece is one folder and has its own meson.build, which defines <piece>_dep and its test(...) entries; the tests of a piece are in its folder (prova_*.c, or a prova/ subfolder). What a piece depends on is replaced in its tests by a fake written in its own folder, so with -Dpezzo=<name> the other pieces are not even built.

  • Build flags. C17, warnings as errors (warning_level=3, werror=true in the root meson.build), tests compiled with AddressSanitizer and UndefinedBehaviorSanitizer (-Db_sanitize=address,undefined).
  • Thread sanitizer. It cannot be mixed with AddressSanitizer, so the pieces whose correctness is about threads rebuild their sources in a second variant with b_sanitize=thread (-fsanitize=thread): ADB, the component, data, transfers, the connection (collegamento-finto-tsan) and weather, each in its own meson.build.
  • Fakes. There are several, each for a different layer: src/adb/finto_telefono.c (a fake ADB daemon in C), prove/telefono_finto/telefono_finto.py (a fake ADB daemon in Python with TLS, channels, shell,v2 and sync:; it simulates neither pairing, nor exec:, nor compression), src/componente/prova/finto.c (a fake component), src/dati/prova/finto.c, src/audio/prova/finto_canale.c, src/file/finto_canale.c, src/trasferimenti/prova/finto.c and the fake TLS side of the weather piece.
  • Fake lower pieces for the real services. src/shell/ossatura/finti_sotto.c replaces connection, data, component and the rest, with fakes that "sleep like the network": the tests check that no call blocks the GTK thread, that borrowed sessions are given back, and that closing with requests in flight is clean.
  • Rules the tests must obey (from CLAUDE.md): a test must fail if the code it proves is removed (verify it); never sleep to "give time" to another thread, wait for a signal with a deadline; every new error branch has its test; an intermittent failure is never ignored nor worked around by widening a tolerance: it is captured and explained.

16.2 · Running the tests

All builds and tests run on a build server, inside the build container, never on the machine where the sources are edited and never with large files in /tmp. The one entry point is strumenti/prova.sh <piece>. The script packs the tree, sends it over SSH to the server, runs the container under a per-piece lock (two agents asking for the same piece queue up instead of deleting each other's work), writes the whole log on the server, prints the last 25 lines, and the last line is always uscita N (N is the exit code). If a run fails, the log and the test details are kept with the time in the name, so an intermittent failure is not lost on the next run.

CommandWhat it builds and runs
prova.sh adb|file|scoperta|abbinamento|componente|video|audio|dati|finestre|config|trasferimenti|collegamento|meteoOne C piece with its tests, with AddressSanitizer and UBSan
prova.sh shell-<piece>One shell piece (shell-finto, shell-ossatura, shell-superficie, shell-finestra-app, shell-barra, shell-launcher, shell-desktop, shell-trasferimento, shell-sistema, shell-connessione): runs only the shell suite, then rebuilds the same piece with -O3 and no checks (the warnings that optimization shows, and the demos for the tablet)
prova.sh tuttoAll pieces that are finished and approved (pezzi_pronti and shell_pronti in the root meson.build), with every test. Only when the work is complete: the others compile your tree
prova.sh veloceEverything together, optimized (-Dbuildtype=release), without memory checks and without tests: for speed measurements and for the executables to try on the tablet. A C piece is finished only if this also passes, because optimization shows warnings that the test build does not
prova.sh telefono, prova.sh telefono-<piece>The phone component's jar (all pieces or one), with the JVM tests of each folder
Table 16.1 — The commands of strumenti/prova.sh
Examples
$ strumenti/prova.sh config
$ strumenti/prova.sh shell-desktop
$ strumenti/prova.sh veloce

Inside the container strumenti/dentro.sh does the work. For the shell it also starts a virtual screen, gtk4-broadwayd on display :5, waiting up to 10 s for its socket instead of pausing at random. The default container image has it; with an image that lacks it the tests that need a screen end with exit code 77 and are reported as skipped. The image recipe is strumenti/Containerfile (a Debian base with the build tools, Vulkan, FFmpeg and VA-API headers, SDL3, Opus, PipeWire, GTK 4, an Italian locale to prove that numbers are read and written the same under any system language, and the broadway tools).

16.3 · Shell tests, demos and photographs

Every shell piece has a logic test without a screen (prova_<piece>.c, with leak checking) and a screen test: the piece's demo run with --prova 2000 under the virtual screen with G_DEBUG=fatal-criticals. Logic is kept apart from the widgets (pure functions in the piece's own folder, for example src/shell/superficie/logica.c) precisely so it can be tested without a screen. Logic tests ignore the leaks of third-party libraries listed in src/shell/soppressioni-lsan.txt; screen tests turn leak detection off because GTK leaves reachable memory at the end.

  • Demos. demo-<piece> runs one piece over the fake phone; demo-ossatura runs the whole shell. On the tablet: strumenti/demo-sul-tablet.sh <piece> takes the optimized demo from the server (options --misura WxH, --dmabuf, --senza-comandi); in the demo, F5 locks or unlocks, F6 drops the connection for 5 s, F7 sends a notification, F8 closes the last app.
  • Photographs. strumenti/foto-demo.sh <piece> opens the demo on an invisible screen of the tablet (a headless compositor, so the user's screen is not disturbed) and saves PNG photographs to compare with the mockup: sizes, colors, order, texts. The demo's own output is also read, and must hold no GTK critical warning.
  • Other tools in strumenti/: yasde-prova.c (a command line client for the lower pieces), finestra-prova.c (a bare window for an app, SDL3), misura-flussi.c (several video streams in parallel), prototipo-gtk.c (the GTK prototype that measured the frame path), app-sul-tablet.sh, finestra-sul-tablet.sh. They are built only with pezzo=tutto and are not part of the program.
  • Scope of tutto: it builds all pieces in pezzi_pronti plus the shell pieces in shell_pronti, so a piece still being written cannot break the build of the others; the coordinator adds a piece to those lists when it is approved.

16.4 · Tests of the phone component

The component's Java code is tested in two ways.

  • On the container's JVM, without Android (run by telefono/costruisci.sh for every piece that has a prove.sh): the piece's test classes are kept as .java.txt files and copied to a temporary folder at test time, so they never enter the jar. For example telefono/base/prove.sh runs ProvaProtocollo, ProvaSmistatore, ProvaPari and ProvaResti.
  • The build compiles the contract and the pieces' sources at Java source level 8 (-source 8 -target 8, so no lambdas or method references: anonymous classes) against android.jar of the SDK (platform 35), with -Xlint:all -Werror, and converts with D8 to telefono/yasde.jar (--min-api 34). The pieces are base, video, audio, dati, archivio, appunti, pannello, controlli plus contratto (always present).
  • On the real phone: each piece has Python scripts in its prove/ folder (for example telefono/base/prove/prova_telefono.py) that push the jar through the phone's ADB and drive it. Those use the standard adb tool already paired with the phone.

16.5 · Rules for tests on the real phone

There is one test phone, so real-phone tests run one at a time. The rules come from CLAUDE.md and exist because earlier reviews found the opposite.

  • The turn. Before touching the phone take the turn with a directory created in the user's cache (mkdir fails if it exists: wait and retry every 20 to 30 s). Remove it with rmdir only if your own mkdir succeeded in this very run (script variable "my turn" and a trap or finally that removes only one's own). If the mkdir fails or times out, the script exits: never go on without the turn, never remove someone else's.
  • Do not wake or reconnect. Never wake, unlock or reconnect the phone: if it is not awake and connected, stop and report it.
  • Touch only what you created. Note the pids of the processes launched and the names of the files written, and clean up only those (never "the first it.yasde found", never a wildcard on the guardian's scripts). Before touching anything, read-only: if the phone already runs a component or has a guardian file (another test, or the real program), exit.
  • Settings. No setting changed without a restore; the starting values are saved and compared line by line at the end. No volume or user setting written "to prepare" the test. Nothing is started on the real screen. No audible sound without the user's explicit consent.
  • Every adb command has a deadline; the cleanup runs in a finally. No serial number or address in any file: fake values (for example R5CT0000000) in examples.
  • The component restores the phone in every case: a thread that dies for an unexpected Throwable must leave the phone as it was, and a failed action that would leave an abnormal state (screen off, volume changed) is retried, not abandoned (chapter 6).

16.6 · What is not covered

The tests prove logic, formats, protocol, concurrency and the fake phones. Several things are only proven live or not at all, and the manual says so rather than imply otherwise.

  • Tried live on 24 November 2026 with the AppImage, on one machine and one phone: pairing from an empty installation, the panel turning off by itself at connection, the bar volume starting at 100%, and the Compatibility switch (the hot change is enough). Never tried live at the time of writing: every English sentence on screen, the weather (a real forecast request: only the TLS handshake was tried by hand), the pairing screen's hints when the phone does not announce itself.
  • Screen tests run on a virtual broadway screen: they prove that the widgets build and respond, not how they look on a real display, with the Vulkan renderer, or under fractional scales (125%, 150%), which have still to be tried.
  • The AppImage was checked for its contents, legal texts and dependencies by the build script, and its startup with the interface was tried live on one distribution with one phone. Its use on another distribution or glibc, and the parts that trial did not touch (MP4 recording and PNG capture with the bundled libraries, Vulkan decoding), were not verified (chapter 17).
  • Direct scan-out of video frames (offload) is not confirmed on the one machine where it was looked for (21.1 “The known problems at a glance”).
  • One phone, one Android. Behavior on other makers' phones and Android versions beyond the one tested is not covered.
Chapter 17

Building and packaging

17.1 · Meson and the project options

The PC side is built with Meson. The root meson.build declares the project yasde version 2.1.0 in C with the default options c_std=c17, warning_level=3, werror=true and buildtype=debugoptimized, adds -D_GNU_SOURCE, and then includes the pieces.

Option (meson_options.txt)Type, defaultMeaning
pezzostring, tuttoBuilds one piece (for example adb, config, shell-desktop) or everything. With one piece the others do not exist and its tests use fakes.
Table 17.1 — The only project option
  • Pieces. The list in the root file: adb, file, scoperta, abbinamento, componente, video, audio, dati, finestre, config, trasferimenti, collegamento, meteo. Each lives in src/<piece>/, has its own meson.build and defines <piece>_dep (a dependency with its static library). Common code (src/comune/: PhErrore, buffers, the neutral frame descriptor) is always built.
  • With pezzo=tutto only the pieces listed in pezzi_pronti (and the shell pieces in shell_pronti) enter: a piece still being written cannot break the whole build; the coordinator adds a piece to the list when it is approved. A shell piece named shell-<piece> builds with config and finestre (pure logic already approved), and the skeleton with all the pieces below.
  • The shell (src/shell/meson.build) needs GTK 4 at least 4.14 (gtk4), builds the common piece and the fake backend always, and the shell pieces present. The skeleton's real services are built only if all the lower pieces are there (the flag PH_OSSATURA_SERVIZI_VERI). The program is the executable yasde built from src/shell/ossatura/main.c. A header generated at configuration time holds one flag per piece.
  • Libraries. OpenSSL 3 (ADB TLS and weather), FFmpeg's libavcodec, libavutil, libavformat, libswscale and Vulkan (the video piece: decoding, PNG and MP4 capture), Opus and PipeWire (audio), GTK 4 (the shell), gdk-pixbuf (the desktop piece, wallpaper decoding), and threads. FFmpeg stays closed inside src/video/ and GTK inside src/shell/.
  • Resources. Each shell piece compiles its CSS with glib-compile-resources (--manual-register, source files such as barra.gresource.xml) as /it/yasde/shell/<piece>.css; the generated string is long, so resources are compiled apart with -Wno-overlength-strings. Translations and CSS are inside the executable: the program reads no data file at run time.
  • Translations. A generator built first (genera_traduzioni) turns the data/en/*.txt files into a C source at build time (chapter 14).
  • Phone component. Not in Meson: telefono/costruisci.sh compiles the Java with javac and D8 into telefono/yasde.jar (chapter 16). The AppImage carries the jar next to the executable, which looks for it in its own folder.

17.2 · The build container

Builds do not run on the machine where the sources are edited. They run on a build server, inside a build container, started by strumenti/prova.sh (chapter 16), which copies the sources there. The container's recipe is strumenti/Containerfile: a Debian 13 image with the compilers (GCC and Clang), Meson, Ninja, pkg-config, Valgrind, GDB, the JDK, OpenSSL, Vulkan with its validation layers and compiler for shaders, FFmpeg's development libraries, VA-API and DRM, SDL3, Opus, PipeWire, GTK 4 and the broadway virtual screen, and an Italian locale. The Android SDK (platform 35, build-tools 35.0.0) is mounted read-only into the container; a container is new for every run.

  • A build server path and the container's name are development equipment and are not part of the program; nothing in the executable or the package depends on them.
  • Builds go in build-<piece> folders next to the sources on the server: build-<piece>-veloce is the optimized variant of a shell piece (the demos for the tablet), build-veloce is the optimized whole.
  • Big files never go in /tmp.

17.3 · The AppImage

The program ships as one file, YASDE-2.1-x86_64.AppImage (Linux x86_64), plus a source archive, YASDE-2.1-sorgenti.tar, published on the same release page. The scripts are pacchetto/costruisci.sh (starts on the development machine and sends the work to the build server over SSH, to run in the build container) and pacchetto/dentro.sh (runs inside; mounted read-only: the optimized program from prova.sh veloce and the jar from prova.sh telefono). The log ends with uscita N, and the script exits with the same N. A lock prevents two builds at once; a cache of downloaded sources and of the already built FFmpeg survives between runs, the rest is redone from zero. The script checks its folder variables (PACCHETTO_LAVORO, PACCHETTO_VELOCE, PACCHETTO_TELEFONO, PACCHETTO_LOG) against a strict pattern before touching the server, and refuses ones that contain .. or overlap.

AppDir of the AppImageAppRunown folder, LD_LIBRARY_PATH, GSettingsusr/bin/yasde + yasde.jarprogram and phone componentusr/lib/GTK 4, GLib, Pango, Opus, OpenSSL…FFmpeg, libtiff, cairorebuilt here, no GPL partsgdk-pixbuf loaderswebp loader + cache templateusr/lib/gio-vuotoempty: no GIO modulesglib-2.0/schemasGTK GSettings, compiledusr/share/doc/licenses/copyright, source offer, listsLeft to the host systemglibc, Vulkan, VA-API, DRM, X11, XCB, Wayland, fontconfig, PipeWireNot includedfull icon themes (only the Kora icons of the table), other image loaders, GIO modules, GTK themes and enginesFigure 17.1 — What is inside the AppImage and what is left to the system
  • The launcher (pacchetto/AppRun) always uses its own folder (an inherited APPDIR is ignored), puts the package's libraries first in LD_LIBRARY_PATH, the package's GSettings schemas first in XDG_DATA_DIRS, points GIO_MODULE_DIR to an empty folder (no system GIO modules, which are tied to another GLib), and then execs usr/bin/yasde.
  • Image loaders. The loaders cache template has a placeholder path; AppRun resolves it at every start into ${XDG_CACHE_HOME:-$HOME/.cache}/YASDE/yasde-pixbuf-<pid>.cache, the only file the package writes on the PC, in a folder the specification allows. If the package path contains \, ", &, | or a newline, or the folder is not writable, it gives up with a warning and webp does not open (png and jpeg are inside the library). Files of past runs are removed at start: those whose pid is dead and those older than 24 hours.
  • No integration. No .desktop file is installed on the PC; the one inside the package serves only appimagetool and declares X-AppImage-Integrate=false.
  • Public documents in the package are only in English (README.txt, SOURCE-OFFER.txt, LIST.txt, SYSTEM-REQUIREMENTS.txt, open-meteo.txt, type2-runtime/NOTE.txt), with the line that the project is not affiliated with Samsung.
  • Size. About 20 MB for the AppImage and about 45 MB for the AppDir; the source archive is about 315 MB.

17.4 · Downloaded tools

Everything downloaded is fetched into the build server's work area (never into the repository), only over HTTPS, with a fixed version and a checksum verified before use.

ItemVersionHow it is verified
appimagetool1.9.1SHA-256 as declared by the release
AppImage runtime (type2-runtime)20251108SHA-256 as declared by the release; the tag's source tarball has the checksum seen at the first download (if it changes, the script stops)
FFmpeg7.1.5Tarball from ffmpeg.org; the fixed checksum was compared with the signed Debian sources index (Checksums-Sha256)
libtiff, cairoDebian trixie sourcesapt-get source (apt checks against the signed index) plus the orig checksum fixed in the script; if a version is gone from the current archive, a dated snapshot is used (inside the run only)
libfuse 3.15.0 and squashfuse 0.5.2—Versions and sums are those the runtime's own script verifies; the script rechecks them in that file
Table 17.2 — Downloaded tools and how they are checked

The sources of every included Debian library are saved in the source archive (with a SHA256SUMS file), together with those of libtiff and cairo and the FFmpeg tarball.

17.5 · Legal texts and the checks that fail the build

The package must contain nothing that forces the combined work under GPL terms, and offer the sources of what it contains. The build script fails when any of the following is not true.

  • FFmpeg is rebuilt, LGPL 2.1 or later: --disable-gpl --disable-nonfree --disable-everything --disable-autodetect --disable-programs, shared, with only what the code uses: the H.264 decoder and parser with VA-API and Vulkan (software fallback is the decoder itself), the PNG encoder, the MP4 muxer (the container goes to an I/O context written by the program, so no protocols), and swscale. The script checks for "LGPL version 2.1 or later" in the configure output and in the library, and that every soname the executable asks for exists.
  • libtiff and cairo are rebuilt from Debian's sources, with Debian's security patches, because the distribution's builds pull in libjbig and liblzo2 (GPL-2+ without exception). libtiff without jbig, lerc, lzma, zstd, webp and deflate; cairo without lzo. The sonames stay the same (libtiff.so.6, libcairo.so.2 and its siblings); cairo is replaced entirely, so the process has one version. The script fails if these libraries are not resolved from the versions built here, if libjbig, liblzo2 or libLerc end up in the package, or appear among the NEEDED entries of any file in it.
  • GPL check. The script fails if an included package has a copyright file that cites a GPL (not LGPL), or is not machine-readable, and is not in the list of reasoned exceptions inside dentro.sh (21 cases at the time of writing: dual terms, or GPL only on parts not distributed, each with its reason). The check is mechanical (the machine-readable header lines of those files) plus those hand-written exceptions.
  • Source offer. SOURCE-OFFER.txt (in the package's documentation folder) states that the sources are published next to the AppImage, in the source archive, and lists exact versions and origins. The archive must be published together with the AppImage.
  • Legal texts inside. Each library's copyright; the texts of common legal texts that those files cite (from the distribution's common texts folder) in common-texts/ (the script fails if one is missing); for FFmpeg, libtiff and cairo the texts from their sources.
  • The AppImage runtime (MIT, statically linked to libfuse3 LGPL-2.1 and squashfuse BSD-2): the sources of the tag, libfuse and squashfuse are in the archive; legal texts and notes are in type2-runtime/ in the package documentation folder. For zstd, zlib, mimalloc and musl embedded in the runtime the notices are reproduced; the exact versions cannot be derived, which is irrelevant for terms that ask only for the notice.
  • Kora icons (GPL-3, separate files). The step pacchetto/icone-kora.sh (called by dentro.sh before the final texts, and again as verifica at the end of the checks; it can also run alone) fetches the Kora theme by bikass (github.com/bikass/kora) at a fixed commit (ff8ee3ce…, 19 Nov 2026) into a copy outside the repository, reused only if it is at that commit and unmodified; a failed download stops the build, never a package without icons. Only the icons named in data/icone-kora.txt (104 rows, <Android package> <icon name>) are converted to 128×128 PNG with a transparent background (rsvg-convert, not part of the package) into usr/share/yasde/icone-kora/, with an exact copy of the table as tabella.txt and the SVG sources in sorgenti/ (real files, no links). A malformed row, an empty table, a name missing from the theme or a link leaving the theme stops the build, with the same limits as the program. In the package's documentation folder (usr/share/doc/licenses/) go the GPL-3 text of the theme and a credits file (commit, what was done, third-party marks), cited in LIST.txt, README.txt and SOURCE-OFFER.txt. The final check verifies the files: table, a PNG and an SVG for each name, PNG size, GPL-3 text and credits. Nothing of Kora is in the repository. YASDE itself is under the MIT License with the Commons Clause condition (file LICENSE of the repository); the GPL-3 applies only to these separate files.
  • Weather. open-meteo.txt (in the same documentation folder) carries the credits and terms of Open-Meteo and GeoNames data (CC BY 4.0). No certificate authority is included in the package: the program looks for the host system's (chapter 15), and the script proves, with the package's libcrypto, that the same sequence loads the authorities of the container.
  • Naming. The project name is YASDE. The script fails if a forbidden project name appears, in any capitalization, in file names, in our texts, in the strings of the executable or of the jar, with no exception, AppRun included. The script first proves the check itself: a phrase with the forbidden name in any capitalization must trigger it.
  • Dependencies. Every NEEDED of every file in the package is either included or in the list of what is left to the system; ldd reports no "not found". Required: glibc 2.38 or newer, PipeWire, libva, Vulkan and libdrm, X11 and Wayland client libraries, fontconfig, and the kernel's FUSE with fusermount3 or fusermount (or --appimage-extract-and-run; the runtime has libfuse3 linked statically). Without libpipewire-0.3.so.0, libva.so.2 and libva-drm.so.2 or libvulkan.so.1 the program does not start. The script writes into SYSTEM-REQUIREMENTS.txt only the NEEDED libraries not included and the highest symbol versions required.
  • Self tests. AppRun --help must answer, also with LD_BIND_NOW=1; png, jpeg and webp are saved and re-read with the bundled loaders, and the same test must fail without the webp loader (otherwise it proves nothing); certificate loading is proved as above.

17.6 · What the build does not prove

!
Not verified. what the build script cannot prove: the startup with the interface, real Vulkan, VA-API and PipeWire, hardware decoding with the minimal FFmpeg, MP4 recording and PNG capture with the bundled libraries, opening of TIFF images (libtiff is included only because GTK needs it; TIFFs compressed in the removed ways do not open), the AppImage on another distribution or glibc, the rebuilt runtime from the archive's sources, the compatibility of the bundled libz and libzstd with every Mesa driver loaded in the same process, and that libtiff and cairo behave correctly (only that their sonames resolve and that --help answers). The weather TLS connection to the real server was tried once by hand from the AppImage.

Packages the script installs when missing, for that run only: file (required by appimagetool), the webp pixbuf loader, and when rebuilding nasm and cmake. They belong in the container image.

Chapter 18

Conventions

18.1 · Principles of the project

The project's rules come from CLAUDE.md and from the contracts (src/*/*.h, docs/protocollo.md, src/shell/CONTRATTI.md). They were born from reviews, and a reviewer checks them first.

  • Everything is new code. No third-party code is copied; Android's source is read as documentation only.
  • PC side: C, Meson, Vulkan. Phone side: minimal Java launched with app_process; only pure Android APIs, no dependency on a maker.
  • Nothing installed on the phone, no root. Every change made to the phone has its restore.
  • Only what the specification and the mockup say. No features beyond them.
  • A piece is one folder, one agent. Whoever writes a piece touches only its folder. Contract headers, docs/protocollo.md, telefono/contratto/, the root meson.build and strumenti/ are not modified by a piece: a wrong or incomplete contract is reported and the rest goes on.
  • No personal data in the repository (it is public): no serial numbers, addresses, network names or person names in files; fake values in tests (for example R5CT0000000).
  • Language: names, comments, messages and documents are Italian in the code; the manuals and the public documents in the package are English (18.6 “Code language and user language”).

18.2 · C and the common code

The source is C17, compiled with warnings as errors, and tests run with AddressSanitizer and UndefinedBehaviorSanitizer (chapter 16). A piece is finished only if strumenti/prova.sh veloce (everything together with -O3) also passes, because optimization shows warnings the test build does not.

  • Names. Public functions are prefixed ph_ and the piece (ph_fin_* for windows, ph_cfg_* for configuration, ph_tr_* for the queue, ph_srv_* for the shell's services). Types are Ph… and constants PH_…. Shell classes are prefixed ph-<piece>-.
  • Errors. Every return value is checked. A function that can fail takes a PhErrore * (which may be NULL; it holds a sentence of up to 256 bytes saying what the function was doing) (ph_errore writes it, ph_errore_contesto prepends a context). The return convention is the same across the project: int 0 for success and -1 for an error; a pointer is NULL on error. No function calls exit or abort for an error that depends on the phone or the network.
  • Hostile data. Nothing that comes from the phone or the network may make the program read or write outside a buffer. Indexes into arrays that arrive through the services are checked against the length given; no fixed-size buffer is filled without a limit (g_strlcpy, snprintf). Text shown is already safe (valid UTF-8, no control characters).
  • Contracts grow at the end. Structures of the contracts (handlers, requests, data) are always initialized by field name ({.io = x, .apri_app = f}), never by position, because adding a field at the end would make a positional initializer an error (missing-field-initializers) for everyone.
  • Includes. No piece includes the internal header of another piece. GTK appears only under src/shell/, FFmpeg only in src/video/. The shell's pieces include none of collegamento.h, dati.h, componente.h, decodifica.h, audio.h, trasferimenti.h, file.h, adb.h; only the skeleton does, inside the real services.
  • Comments explain why, in Italian. Contracts say what a callback may call and what a function touched when it returns an error (usually nothing).
  • No commits by pieces. Whoever writes a piece does not run git commit

18.3 · Rules born from reviews

Defects found in earlier reviews, written so as not to be repeated. Each is checked by the reviewer.

RuleWhat it means in the code
Closing in parallelEvery public function that uses an object must tolerate the object's …_chiudi called by another thread at the same moment: either it finishes first, or it returns an error; never use of freed memory. A "is it closed?" check made and then dropped (lock released) does not protect: a use counter that the close waits for is needed.
CallbacksAfter a …_chiudi returns, no callback is running and none will arrive. Never call a callback while holding a lock that the receiver may want to take. The contract says what a callback may call (for example inside the queue's notice, ph_tr_chiudi is forbidden).
WaitsNo wait without a limit, except where the contract says so. No lock held during an external command, a network write or a pause.
Failing midwayIf an operation of several steps fails midway, what was already done is undone; when a function returns an error, the contract says what was touched (normally nothing).
PhoneThe restore is registered BEFORE the change and removed only AFTER the change was really undone; if Guardiano.imposta returns false the change is not made. A failed action that would leave the phone in an abnormal state (screen off, volume changed) is retried, not abandoned. A thread that dies of an unexpected Throwable must leave the phone as it was.
TestsA test fails if the code it proves is removed (verified); no sleeping to give another thread time (wait for a signal with a deadline); every new error branch has a test; an intermittent failure is captured and explained, never ignored or hidden by a wider tolerance.
Real phone testsThe turn: rmdir only if the own mkdir succeeded in this run; if it fails the script exits. Never wake, unlock or reconnect the phone. A test touches only what it created, never a wildcard, and checks beforehand, read-only, that no component or guardian file of another run is there.
Whole buildstutto and veloce run only when the work is finished, never with files half written: the others compile your tree. Never rm in data/ or in folders that are not yours.
ReportsSay what you did NOT verify. Never call clean what you did not see pass.
Table 18.1 — The rules of «Defects already seen» in CLAUDE.md

18.4 · Rules of the shell

Rules specific to the GTK shell (src/shell/CONTRATTI.md), in addition to the above.

  • One GTK thread; it never blocks; the only way from another thread is ph_shell_consegna (11.3 “Threads and delivery to the GTK thread”). g_idle_add and similar are not scattered around the pieces.
  • Whoever hands a pointer to a widget to another thread keeps a g_object_ref until delivery. Whoever sends a lot (frames) coalesces: at most one delivery in flight per stream, the last datum wins.
  • Pieces free their things when the root is destroyed, with all the *_smetti functions, and keep their own reference to the widgets as long as listeners exist (11.5 “The skeleton”).
  • Every automatic decision of the program (pause, reduced rate, resumed stream, fallback from DMA-BUF to memory) is written with ph_shell_decisione with its cause and the number that caused it; never personal data. Things the user asks for are not automatic decisions.
  • No GtkStyleContext per widget and no inline CSS (except computed colors); GTK CSS has no gap, max-width or position.
  • Everything clickable is a real control reachable with Tab.
  • Privacy in logs and disk: no serial numbers, addresses, network names or person names; nothing about calendar event titles, file names, phone location, pairing code. The pairing code, addresses and ports are never written, not even in an error message.

18.5 · Rules of the phone side

The Java side follows rules of its own (chapter 6): source level 8 (no lambdas or method references: anonymous classes), pure Android APIs, hidden ones only by reflection and gathered in one class per folder with a startup self-check that says which are missing; every channel runs on its own thread and catches everything (even Error), so a broken channel does not take down the service; every change to the phone registers its restore command in the guardian (Custode), a separate shell process that executes it if the service dies suddenly, and that deletes the jar; restore commands are self-contained shell lines with no environment variables of the service and no nested quotes; the user's value wins, and a setting is restored only if it still has the value YASDE put there.

18.6 · Code language and user language

Two languages live in the code and they never mix.

LanguageWhereExamples
ItalianIdentifiers, comments, internal messages (PhErrore sentences, stderr lines), file names, folders, configuration keys, protocol names, documents in the repository (CLAUDE.md, PIANO.md, CONTRATTI.md, COMPITO.md)ph_fin_apri, telefoni.toml, [[fissata]], PH_SRV_NON_ABBINATO
EnglishEverything the user can read: interface texts (through data/en/), the public documents in the package, the two manualsthe window titles, buttons, notices; README.txt, SOURCE-OFFER.txt
Table 18.2 — Which language where
  • Texts for the user are written in Italian in ph_t("…") and translated by a table (chapter 14); the program always runs in English. The Italian text is the key: a text without translation fails the build's test, so none can reach the user in Italian.
  • Because the code is Italian, the manuals keep identifiers as they are and explain Italian words the first time (for example ossatura, the skeleton). The check of the manuals rejects Italian sentences in running text, outside code and preformatted blocks.
  • Texts of the phone (app names, notifications, error sentences of the component) arrive ready, in the phone's language, and are not translated.
Chapter 19

Extending YASDE

19.1 · Before you start

Four common extensions, with the files each one touches. The examples follow the path of an existing feature: the Next alarm widget (message 0x7c, SVEGLIA, the Italian word for alarm clock) goes through every layer. Its type 0x7c is taken: the whole range 0x70–0x7f is fully assigned, so a new message of the same kind needs a free number, for example one of 0x91–0x9f (already registered to Dati) or 0x86–0x8d (the Controlli range). Contract files (docs/protocollo.md, src/*/*.h, telefono/contratto/, src/shell/servizi.h, src/shell/servizi_backend.h, the root meson.build) are changed by whoever coordinates the project, not by the piece's author (chapter 18): in a team, a piece's author reports what is missing.

19.2 · Adding a protocol message on both sides

Take a request that returns data, like the existing SVEGLIA (0x7c) or BATTERIA (0x7d), which you can read as models; a new one takes a free number such as 0x91. The message types are in ranges, one per area, and each range is served by one phone class.

RangeAreaPhone class (folder)
0x01–0x0fGeneric: hello, OK, error, close, presenceServizio (telefono/base/)
0x40–0x4fVideoVideo (telefono/video/)
0x50–0x5fInput (and clipboard 0x58–0x5a)Input, Appunti
0x60–0x6fPhysical panelPannello (telefono/pannello/)
0x70–0x7fPhone data (0x74–0x75 in telefono/archivio/)Dati (telefono/dati/), Archivio
0x80–0x8fQuick switchesControlli (telefono/controlli/)
0x90–0x9fApproximate positionDati
Table 19.1 — Message ranges of docs/protocollo.md
  1. Specify it in docs/protocollo.md: the type number inside the right range (§2), the direction, the request body and the OK body. Numbers are big endian, a string is a 2-byte length plus UTF-8, a message is a type byte, a 4-byte length (at most 1 MiB) and the body. Say what the phone touches, and its restore if it changes anything (the guardian rule).
  2. Phone side. Add the constant and the case in the class that owns the range (telefono/dati/it/yasde/Dati.java: the existing SVEGLIA = 0x7c is the model), the encoding of the OK body in the helper class (CampiDati.java) and the reading of the data in the class of hidden or platform calls (NascosteDati.java). If the number is outside the ranges already registered with Registro.registraComandi, register the new range in the class's registra method. A thrown exception becomes an ERRORE with its message. Source level is 8: no lambdas.
  3. A new phone class (a new area) goes in a new folder under telefono/ with a prove.sh, and its name is added to the array PEZZI in telefono/base/it/yasde/Servizio.java, which registers each class by reflection at startup; also add it to the default list in telefono/costruisci.sh.
  4. PC side, the piece (src/dati/): add PH_DT_<NAME> to the enum in src/dati/interno.h, the API and its structure in src/dati/dati.h, and the function in src/dati/nuovi.c built on ph_dati_chiedi. Read the answer with the bounds-checked reader, accept only a body of exactly the expected length, and return -1 with a fixed message otherwise: the body is hostile data. Add a free function for any allocated field.
  5. Tests on both sides. PC: the fake component (src/dati/prova/finto.c) answers the new type, and src/dati/prova/prova_dati.c proves the good answer and every refusal. Phone: a JVM test class (a .java.txt file in the piece's test folder) and, for the real phone, a script in telefono/dati/prove/ (chapter 16). Verify that each test fails if the code is removed.
  6. The services (if the shell needs it): ph_srv_tel_<name> and its callback type in src/shell/servizi.h, the entry tel_<name> in PhServiziBackend (servizi_backend.h), the wrapper that makes a job in src/shell/comune/servizi.c, the function the backend calls to deliver the result, ph_servizi_lavoro_<name> (declared in servizi_backend.h, defined in servizi.c, called for the alarm by sv_extra.c), the real implementation in the skeleton (sv_tel_sveglia in src/shell/ossatura/sv_extra.c, registered in the table in servizi_veri.c and declared in sv_interno.h), and the fake one in src/shell/finto/finto.c (and a command in its small window if the state must change).
  7. Document the change in the manual chapter that describes it, and in src/shell/CONTRATTI.md if it changes a rule.

19.3 · Adding a widget

A widget is drawn by the desktop piece (src/shell/desktop/) and shares the look of the others: same card, three sizes, translucent background.

  1. The type in the profile. Add a value at the end of PhCfgWidgetTipo in src/config/config.h (values saved before stay valid) and its name in the NOMI_WIDGET table in src/config/config.c, in the same position. Extend the config tests (reading, writing, the unknown-type rule).
  2. The catalog. Add an entry to PH_DSK_CATALOGO in src/shell/desktop/widget.c: the type, the name and the description, both inside PH_T_. A widget that is not offered yet is left out with a compile-time switch, as PH_DSK_TROVA_OFFERTO does for the find-my-phone widget.
  3. The drawing and data. Add a table of type PhDskWxVt (src/shell/desktop/interno.h) in a wx_*.c file (start, stop, update, how often to ask) and map the type to it in ph_dsk_wx_vt in src/shell/desktop/wx.c. Ask the phone only while the widget is on the desktop, using ph_dsk_wx_puo_chiedere (for example the next alarm every 5 minutes, the battery every minute, the calendar every 15 minutes), and never put titles, file names or other personal data on disk or in logs.
  4. The texts. Every new text is in ph_t or PH_T_, and its translation is added to data/en/shell-desktop.txt in the same change, after checking with grep that the key does not exist in any file of data/en/ (a duplicate key between two files stops the build).
  5. The CSS in src/shell/desktop/desktop.css, classes ph-desktop-*. The fake: give src/shell/finto/ the new data and, in src/shell/desktop/demo_hook.c, the commands to show the empty, error and "not available" states.
  6. Tests. Pure logic in logica_wx.c and src/shell/desktop/prova_desktop.c; photograph the demo (strumenti/foto-demo.sh) and compare it with the mockup.

19.4 · Adding an interface entry with its translation

An interface entry is any new text: a label, a hint, a message. The program is English only, so each Italian key in the code needs its English value, or the build's test fails.

  1. Write the text in the code with the Italian literal in ph_t("…") (or PH_T_("…") for a literal placed in a table, translated later with ph_tv). The argument is always a literal. Placeholders are {name}, composed with ph_lingua_componi, never with printf.
  2. Add the line "italian" = "english" to the piece's file data/en/shell-<piece>.txt (create it for a new piece: the list of files is read at configuration, so run meson setup --reconfigure). Same placeholders in both. Check with grep for an existing key: the shell's mockup texts are all already in data/en/shell-comune.txt and must be reused as they are.
  3. Run strumenti/prova.sh <piece> and the lingua test: it fails on a missing translation, different placeholders or a non-literal argument. Phone texts are not translated and are not written in the table.
  4. Accessibility: the label goes through ph_shell_etichetta with the text and the hint. Do not write example ph_t calls in comments, because the scan reads comments too.

19.5 · Adding a piece

A new piece is one folder, and one agent.

  1. Create src/<piece>/ with a meson.build that defines <piece>_dep (a dependency with its static library) and its test(...) entries, plus the header that is the piece's contract.
  2. Add the name to the list pezzi in the root meson.build and, only when the reviewer approves it, to pezzi_pronti. (A shell piece is added to the shell_pezzi list in src/shell/meson.build and to shell_pronti in the root; its entry point is declared in src/shell/pezzi.h and called by ph_ossatura_installa_pezzi, with a flag in the header generated at configuration time.)
  3. In its tests replace what the piece depends on with a fake in its own folder, so -Dpezzo=<piece> builds without the others.
  4. Write the tests: logic without screen, every error branch, and for threads the concurrency tests (chapter 16). Close in parallel, callbacks, waits and midway failures follow the rules in 18.3 “Rules born from reviews”.
  5. Run strumenti/prova.sh <piece> and, when it is finished, strumenti/prova.sh veloce.
  6. Add the piece to the source map of the manual (chapter 20) and to the glossary if it brings new terms; the generator stops if a source file is missing from the map.
Chapter 20

Source map

20.1 · The folders

The folders of the project, one piece per folder.

yasde/
├── meson.build  # root build file
├── meson_options.txt  # the pezzo option
├── CLAUDE.md  # project rules (Italian)
├── PIANO.md  # work plan (Italian)
├── data/en/  # English translation tables
├── docs/  # protocol and the manuals' sources
│   └── sources/  # build.py, style, script, technical/ and user/ chapters
├── mockup/  # the interface mockup
├── pacchetto/  # AppImage packaging
├── prove/telefono_finto/  # the fake ADB daemon in Python
├── src/
│   ├── comune/  # errors, buffers, neutral frame
│   ├── adb/  # ADB client
│   ├── scoperta/  # mDNS discovery
│   ├── abbinamento/  # pairing with the code
│   ├── collegamento/  # connection state machine
│   ├── componente/  # PC side of the phone component
│   ├── dati/  # phone data, search, clipboard
│   ├── file/  # copy and listing
│   ├── trasferimenti/  # queue and APK installer
│   ├── video/  # decoding, capture
│   ├── audio/  # Opus and PipeWire
│   ├── finestre/  # window rules
│   ├── config/  # folders, files, language
│   ├── meteo/  # forecasts
│   └── shell/  # GTK 4 interface
│       ├── comune/ ossatura/ finto/  # common piece, skeleton, fake backend
│       └── superficie/ finestra-app/ barra/ launcher/ desktop/ sistema/ trasferimento/ connessione/
├── strumenti/  # build and demo tools
└── telefono/  # the Java component and its tests
    ├── contratto/ base/ video/ audio/ dati/ archivio/ appunti/ pannello/ controlli/
    └── costruisci.sh
Table 20.1 — The folders of the project

20.2 · The project's files

Every source file with its line count, recounted each time the manual is generated. The map covers the C sources and headers under src/, the Java, shell and Python files of the phone component, the scripts and C tools of strumenti/ and pacchetto/, the root meson.build and the manual generator. If a file is missing from the map, or the map lists one that no longer exists, generation stops. The per-piece meson.build files, the COMPITO.md task files, CSS, resource and translation files are not counted.

FileLinesRole
Root and generator
meson.build45Root build file: project options, the list of pieces, the pieces ready for «tutto»
Manuals
docs/sources/build.py727Generates the two manuals: functions for text, tables and SVG figures, numbering, source map counting, checks
Common code
src/comune/buffer.c51Growing byte buffer
src/comune/buffer.h24Contract of the buffer
src/comune/errore.c33PhErrore: writing and prefixing messages
src/comune/errore.h22Error convention of the whole project
src/comune/fotogramma.h82The neutral video frame (DMA-BUF or memory), pure C
src/comune/prova_comune.c28Tests of the common code
ADB client
src/adb/adb.h106Contract: connection, channels, shell, flow control
src/adb/chiave.c268The PC's RSA key, self-signed certificate for TLS, ADB public key format
src/adb/connessione.c1,152ADB connection: TCP, CNXN/STLS, TLS 1.3, reader thread, channels, flow control
src/adb/interno.h49Internal: protocol packets
src/adb/pacchetto.c60Packet header reading and writing
src/adb/shell.c93The shell,v2 service: packets, output, exit code
src/adb/finto_telefono.c644Fake ADB daemon on localhost for tests
src/adb/finto_telefono.h68Contract of the fake daemon
src/adb/prova_canali.c695Tests: channels, flow control, delayed acknowledgement
src/adb/prova_chiave.c118Tests: key and certificate
src/adb/prova_pacchetti.c70Tests: packet format
src/adb/prova_velocita.c80Throughput measurement
src/adb/prova_vera.c134Check against a real phone
Discovery and pairing
src/scoperta/scoperta.h42Contract of the mDNS (DNS-SD) discovery, written from scratch
src/scoperta/scoperta.c674mDNS queries and answers
src/scoperta/scoperta_interno.h62Internal parts for tests
src/scoperta/cerca.c29Hand tool: lists the phones found in 5 s
src/scoperta/prova_scoperta.c446Tests of the discovery
Pairing
src/abbinamento/abbinamento.h16Contract: pairing with the six-digit code
src/abbinamento/abbinamento.c323Pairing sequence: TLS, SPAKE2, key exchange
src/abbinamento/spake2.h40SPAKE2 on edwards25519, Android's variant
src/abbinamento/spake2.c450SPAKE2 implementation
src/abbinamento/prova_spake2.c73Tests of SPAKE2
Connection
src/collegamento/collegamento.h281Contract: states, borrowed sessions, concurrency rules
src/collegamento/collegamento.c1,171State machine with its own thread: search, connect, component, guardian, retry
src/collegamento/prova/finto.c672Fake lower pieces for the connection tests
src/collegamento/prova/finto.h100Contract of those fakes
src/collegamento/prova/lingua.c67Fake language functions for the tests
src/collegamento/prova/prova_collegamento.c1,578Tests of the state machine, with the thread-sanitizer variant
Files
src/file/file.h69Contract: copy and listing with sync:
src/file/file.c908Send, receive, list, stat
src/file/finto_canale.c476Fake channel for tests
src/file/finto_canale.h44Contract of the fake channel
src/file/prova_file.c714Tests of the file layer
src/file/prova_vera.c123Check against a real phone
Transfers and installation
src/trasferimenti/trasferimenti.h200Contract of the queue and the free-name rule
src/trasferimenti/trasferimenti.c971The transfer queue and its worker thread
src/trasferimenti/installa.h145Contract of install and uninstall
src/trasferimenti/installa.c558APK recognition, copy, pm, cleanup, analysis of pm output
src/trasferimenti/prova/finto.c354Fake lower pieces for the queue tests
src/trasferimenti/prova/finto.h49Contract of the fake
src/trasferimenti/prova/finto_installa.c192Fake phone for the install tests
src/trasferimenti/prova/finto_installa.h34Contract of that fake
src/trasferimenti/prova/prova_installa.c599Tests of install and uninstall
src/trasferimenti/prova/prova_trasferimenti.c1,384Tests of the queue
The component, PC side
src/componente/componente.h213Contract: start of the service, command channel, video sessions, input
src/componente/componente.c873Startup, command channel, events, heartbeat
src/componente/interno.h125Internal details
src/componente/lettura.c23Resumable reading from a channel
src/componente/messaggi.c117Pure part of the protocol: writing and reading messages
src/componente/video.c417Video sessions: open, read H.264 packets, resize, keyframe, close
src/componente/prova/finto.c983Fake component (a phone-side simulator in C)
src/componente/prova/finto.h84Contract of the fake
src/componente/prova/prova_componente.c1,662Tests of the component
src/componente/prova/prova_messaggi.c198Tests of the message format
Phone data
src/dati/dati.h393Contract: apps, icons, state, notifications, storage, calendar, alarm, battery, switches, position, search, clipboard
src/dati/interno.h127Internal: message types
src/dati/richieste.c690Requests 0x70–0x75 and events 0x7e–0x7f
src/dati/nuovi.c489Month calendar, alarm, battery, quick switches, position
src/dati/cerca.c239File search on the cerca channel
src/dati/appunti.c208Shared clipboard channel
src/dati/canale.c91Message reading from a channel, safe against a hostile phone
src/dati/utf8.c127Cleaning of strings that come from the phone
src/dati/prova/finto.c530Fake component for the data tests
src/dati/prova/finto.h58Contract of the fake
src/dati/prova/prova_dati.c2,683Tests of the data layer
Video
src/video/decodifica.h65Contract of H.264 decoding (FFmpeg, hardware accelerated)
src/video/decodifica.c256Decoder with VA-API or Vulkan and a software fallback
src/video/esporta.h53Contract: decoded frame to the neutral frame
src/video/esporta.c252DMA-BUF export without copies, or memory
src/video/esporta_interno.h17Internal parts of the export
src/video/colore.c34Color choices and checks on shared planes
src/video/colore_interno.h17Internal color parts
src/video/cattura.h175Contract: screenshot (PNG) and recording (MP4)
src/video/cattura_interno.h26Internal parts of capture
src/video/cattura_nome.c132File names of captures, created without overwriting
src/video/cattura_png.c214Frame to RGB to PNG
src/video/cattura_mp4.c831Fragmented MP4 recording without recoding
src/video/misura_decodifica.c120Measurement tool for decoding
src/video/prova/aiuti.h164Test helpers
src/video/prova/prova_cattura_mp4.c309Tests of MP4 recording
src/video/prova/prova_cattura_ostili.c675Tests with hostile input for capture
src/video/prova/prova_cattura_png.c340Tests of PNG capture
src/video/prova/prova_esporta.c290Tests of the frame export
src/video/prova/prova_ordine_via.c33Tests of the automatic order of the decoding vias
Audio
src/audio/audio.h89Contract: receive Opus packets, decode and play with PipeWire
src/audio/audio.c241The player: channel reading, decoding, queue, output
src/audio/pacchetti.c58Reading of audio packets (time, length, data)
src/audio/decodifica.c62Opus decoding, 48 kHz stereo
src/audio/flusso.c110Packet to queue: decoding and gap recognition
src/audio/coda.c544Decoded audio queue with an adaptive margin
src/audio/uscita_pipewire.c194PipeWire playback stream
src/audio/suona.c201Hand tool: plays a stream or a 440 Hz tone
src/audio/interno.h132Internal parts
src/audio/prova/aiuti.h96Test helpers
src/audio/prova/finto_canale.c126Fake audio channel
src/audio/prova/finto_canale.h23Contract of the fake
src/audio/prova/prova_audio.c311Tests of the player
src/audio/prova/prova_coda.c422Tests of the queue
src/audio/prova/prova_decodifica.c152Tests of decoding
src/audio/prova/prova_pacchetti.c130Tests of packet reading
Window rules
src/finestre/finestre.h506Contract: order, snapping, gestures, stream size, density, input translation
src/finestre/finestre.c1,359The rules (pure logic)
src/finestre/prova_finestre.c2,693Tests of the rules
Configuration and language
src/config/config.h437Contract: folders, files, preferences, phone profile
src/config/config.c891Reading and writing of the three configuration files, cleanup
src/config/config_interno.h30Internal parts
src/config/percorsi.c368XDG folders, safe write
src/config/toml.h83Contract of the TOML subset
src/config/toml.c668Reader and writer of the TOML subset
src/config/profilo.h135Contract of the measurements file
src/config/profilo.c439Reading and writing of the measurements file
src/config/lingua.h85Contract: ph_t and placeholders
src/config/lingua.c77Active language and lookup
src/config/lingua_testo.c178Placeholder composition and comparison
src/config/lingua_tabella.h18Shape of the generated table
src/config/genera_traduzioni.c155Build-time generator of the English table
src/config/tabella_finta.c10Fake table for the language tests
src/config/prova_config.c1,895Tests of configuration
src/config/prova_lingua.c314Scan of every ph_t call in the sources
src/config/prova_lingua_funzioni.c189Tests of the language functions
src/config/prova_profilo.c417Tests of the measurements file
Weather
src/meteo/meteo.h244Contract: forecasts, place search, rules of privacy and frequency
src/meteo/meteo.c733Requests, cache, frequency rules, request paths
src/meteo/analisi.c802JSON reader for the forecast and the place search
src/meteo/http.c349Minimal HTTP/1.1 client
src/meteo/tls.c560HTTPS with OpenSSL: name resolution, connection, certificate check
src/meteo/tls.h57Contract of the TLS layer
src/meteo/interno.h46Internal parts
src/meteo/prova/prova_meteo.c2,446Tests of the weather piece
src/meteo/prova/prova_tls.c741Tests of TLS
src/meteo/prova/tls_finto.c227Fake TLS server for tests
src/meteo/prova/tls_finto.h25Contract of the fake server
Shell contracts
src/shell/servizi.h808THE contract: the only door to the phone, audio, transfers, persistence
src/shell/servizi_backend.h310How to write a backend of the services
src/shell/shell.h409The shell context: delivery, layers, popups, handlers, style, icons, glass surfaces
src/shell/superficie.h146Contract of the video surface widget
src/shell/prova_css.h385Common detector of hand-written colours in the pieces' CSS, used by their tests
src/shell/pezzi.h23Entry points of the pieces
src/shell/fotogramma.h7Includes the neutral frame
Shell: common piece
src/shell/comune/consegna.c88Delivery to the GTK thread, monotonic clock, decision log
src/shell/comune/shell.c719The shell context: layers, popups, handlers
src/shell/comune/servizi.c2,619Wrapper of a backend: events, snapshots, jobs, cancel
src/shell/comune/stile.c299Loading and checking of CSS, icons
src/shell/comune/vetro.c393Glass surfaces: registry, blur behind them
src/shell/comune/prova_vetro.c794Tests of the glass
src/shell/comune/ascoltatori.c101Listener lists and the registry of live objects
src/shell/comune/interno.h71Internal parts
src/shell/comune/prova_comune.c467Tests of the common piece
Shell: skeleton
src/shell/ossatura/main.c7The program's main
src/shell/ossatura/ossatura.c212Application, startup, ordered shutdown
src/shell/ossatura/ossatura.h57Internal parts
src/shell/ossatura/finestra.c240The host window, full screen, host state
src/shell/ossatura/velo.c169Lock and connection veil
src/shell/ossatura/appunti.c112PC and phone clipboard link
src/shell/ossatura/logica.c291Pure logic: veil content, what covers the shell, host visibility, stream state machine
src/shell/ossatura/logica.h122Contract of that logic
src/shell/ossatura/servizi_veri.c646Core of the real services: connection, manager thread, pools, profile, shutdown
src/shell/ossatura/sv_interno.h350Internal model of the real services
src/shell/ossatura/sv_dati.c344Phone data, state, panel
src/shell/ossatura/sv_extra.c701Calendar, alarm, battery, switches, position
src/shell/ossatura/sv_file.c544Folder listing, search, folders, thumbnails, reading
src/shell/ossatura/sv_flussi.c1,529Video streams: open, pause, resize, input, screenshot, recording
src/shell/ossatura/sv_audio.c174Audio and volume
src/shell/ossatura/sv_tr.c183The transfer queue's session life
src/shell/ossatura/sv_abbina.c174Pairing from the shell
src/shell/ossatura/sv_meteo.c776Weather observation and place search
src/shell/ossatura/demo.c465Demo of the whole shell over the fake backend
src/shell/ossatura/finti_sotto.c1,217Fake lower pieces that sleep like the network
src/shell/ossatura/finti_sotto.h106Contract of those fakes
src/shell/ossatura/prova_ossatura.c328Tests of the skeleton's logic
src/shell/ossatura/prova_servizi_veri.c1,140Tests of the real services over fakes
src/shell/ossatura/prova_meteo_veri.c685Tests of the real weather side
src/shell/ossatura/prova_decodifica_avviso.c319Tests of the on-screen warning about CPU video decoding
Shell: video surface
src/shell/superficie/superficie.c1,057The widget: reader thread, textures, blur, protected screen
src/shell/superficie/logica.c417Frame swap, rhythm, format maps, exact rectangle
src/shell/superficie/logica.h225Contract of that logic
src/shell/superficie/demo.c316Demo with three surfaces
src/shell/superficie/prova_superficie.c625Tests of the surface's logic
Shell: inner windows
src/shell/finestra-app/finestra_app.c2,928Inner windows: title bar, buttons, input, pause, capture, Compatibility
src/shell/finestra-app/logica.c449Keys, short names, pinch state machine, translation of points
src/shell/finestra-app/logica.h211Contract of that logic
src/shell/finestra-app/finestra_app_demo.h83Demo hooks
src/shell/finestra-app/demo.c1,354Demo of the windows
src/shell/finestra-app/prova_finestra_app.c1,085Tests of the windows' logic
Shell: bar
src/shell/barra/barra.c1,088The bar widget
src/shell/barra/logica.c230Pure logic of the bar
src/shell/barra/logica.h93Contract of that logic
src/shell/barra/demo.c502Demo of the bar
src/shell/barra/prova_barra.c299Tests of the bar's logic
Shell: launcher
src/shell/launcher/launcher.c919The launcher widget
src/shell/launcher/launcher_interno.h56Internal parts
src/shell/launcher/logica.c110Search filter
src/shell/launcher/logica.h66Contract of that logic
src/shell/launcher/demo.c265Demo of the launcher
src/shell/launcher/prova_demo.c299Helper of the demo test
src/shell/launcher/prova_demo.h17Contract of that helper
src/shell/launcher/prova_launcher.c263Tests of the launcher's logic
Shell: desktop
src/shell/desktop/desktop.c794The desktop: layers, menus, drag and drop
src/shell/desktop/sfondo.c129Wallpaper drawing and loading
src/shell/desktop/immagine.c199Wallpaper image decoding and reduction
src/shell/desktop/icone.c523Icon grid
src/shell/desktop/dialoghi.c1,109The wallpaper and widget dialogs
src/shell/desktop/widget.c833Widget catalog and cards
src/shell/desktop/wx.c128Table of the newer widget types
src/shell/desktop/wx_calendario.c469Month calendar widget
src/shell/desktop/wx_controlli.c371Quick switches widget
src/shell/desktop/wx_elenchi.c232Frequent apps and recent transfers widgets
src/shell/desktop/wx_meteo.c441Weather widget
src/shell/desktop/wx_telefono.c188Alarm and battery widgets
src/shell/desktop/orologio.c298Clock widget
src/shell/desktop/meteo_disegno.c470Weather icons and drawings
src/shell/desktop/meteo_luogo.c312Place search dialog of the weather
src/shell/desktop/logica.c1,024Pure logic of the desktop
src/shell/desktop/logica.h309Contract of that logic
src/shell/desktop/logica_wx.c777Pure logic of the newer widgets
src/shell/desktop/logica_wx.h142Contract of that logic
src/shell/desktop/logica_meteo.c420Pure logic of the weather widget
src/shell/desktop/logica_meteo.h91Contract of that logic
src/shell/desktop/interno.h277Internal parts
src/shell/desktop/demo.c284Demo of the desktop
src/shell/desktop/demo_hook.c1,128Demo commands for the widgets
src/shell/desktop/prova_desktop.c1,694Tests of the desktop's logic
Shell: system area
src/shell/sistema/sistema.c188Installation of the system piece
src/shell/sistema/notifiche.c391Notification panel
src/shell/sistema/toast.c166Toasts and desktop notices
src/shell/sistema/telefono.c256Phone status popup
src/shell/sistema/volume.c171Volume popup
src/shell/sistema/pulsanti.c213The three bar buttons
src/shell/sistema/logica.c438Pure logic of the system piece
src/shell/sistema/logica.h129Contract of that logic
src/shell/sistema/interno.h111Internal parts
src/shell/sistema/demo.c143Demo of the system piece
src/shell/sistema/prova_sistema.c458Tests of the system piece's logic
Shell: transfer
src/shell/trasferimento/trasferimento.c862The send and receive panels, drop target
src/shell/trasferimento/navigatore.c1,247Folder and file navigator
src/shell/trasferimento/navigatore.h64Contract of the navigator
src/shell/trasferimento/elenco.c301Queue rows
src/shell/trasferimento/elenco.h32Contract of the rows
src/shell/trasferimento/percorsi.c448Pure logic: paths, free names, sizes, pages, completed transfers
src/shell/trasferimento/percorsi.h104Contract of that logic
src/shell/trasferimento/apk.c48APK installation confirmation
src/shell/trasferimento/apk.h17Contract of the confirmation
src/shell/trasferimento/interno.h58Internal parts
src/shell/trasferimento/demo.c105Demo of the transfer piece
src/shell/trasferimento/prova.c186Test helper
src/shell/trasferimento/prova.h12Contract of that helper
src/shell/trasferimento/prova_trasferimento.c462Tests of the transfer piece's logic
Shell: first connection
src/shell/connessione/connessione.c485The first connection and pairing screen
src/shell/connessione/connessione.h25Contract of the screen
src/shell/connessione/logica_connessione.c242Pure logic: what to show in each state
src/shell/connessione/logica_connessione.h100Contract of that logic
src/shell/connessione/demo.c466Demo of the screen
src/shell/connessione/prova_connessione.c262Tests of the screen's logic
Shell: fake backend
src/shell/finto/finto.c2,552The fake phone: connection, apps, notifications, folders, transfers, widgets
src/shell/finto/finto.h204Contract of the fake and of the demo program
src/shell/finto/interno.h105Internal parts
src/shell/finto/comandi.c355The small window of fake-phone commands
src/shell/finto/flusso_finto.c900Synthetic video streams
src/shell/finto/superficie_finta.c495Fake surface for tests
src/shell/finto/demo_finto.c128Demo of the fake backend
src/shell/finto/prova_finto.c2,033Tests of the fake backend
Packaging
pacchetto/AppRun64AppImage launcher: libraries, schemas, loaders
pacchetto/costruisci.sh53Runs the packaging on the build server
pacchetto/icone-kora.sh218Packaging step: Kora icons as PNG, sources, GPL-3 text and credits
pacchetto/dentro.sh722Packaging inside the container: tools, FFmpeg, libtiff, cairo, checks, AppImage
pacchetto/yasde.desktop9Desktop entry used only by appimagetool
pacchetto/prova_pixbuf.c43Packaging test: image loaders
pacchetto/prova_tls.c45Packaging test: certificate authorities with the package's OpenSSL
pacchetto/prova_tls_rete.c41Packaging test: TLS handshake over the network
Development tools
strumenti/prova.sh28Builds and tests a piece on the build server
strumenti/dentro.sh77The same, inside the container
strumenti/Containerfile17Recipe of the build container
strumenti/prepara-server.sh37Sets up an empty build server: container image and Android SDK
strumenti/sdk.sh14Downloads the Android SDK; run by prepara-server.sh
strumenti/meson.build29Builds the tools below
strumenti/yasde-prova.c496Command line client for the lower pieces
strumenti/finestra-prova.c524Bare window for one app (SDL3)
strumenti/misura-flussi.c849Measures several video streams in parallel
strumenti/prototipo-gtk.c1,195GTK prototype that measured the frame path
strumenti/demo-sul-tablet.sh36Opens a piece's demo on the tablet
strumenti/foto-demo.sh52Opens a demo on an invisible screen and photographs it
strumenti/app-sul-tablet.sh47Opens the real program on the tablet
strumenti/finestra-sul-tablet.sh23Opens the bare window on the tablet
Phone: build
telefono/costruisci.sh23Compiles the component's jar and runs the JVM tests
Phone: contract
telefono/contratto/it/yasde/Registro.java155Meeting point between the service and the pieces
telefono/contratto/it/yasde/GestoreCanale.java9Handler of a channel
telefono/contratto/it/yasde/GestoreComandi.java9Handler of a range of commands
telefono/contratto/it/yasde/Guardiano.java15The restore guardian's interface
Phone: base
telefono/base/it/yasde/Servizio.java411The service: app_process entry, socket, channel dispatch
telefono/base/it/yasde/Protocollo.java105Message types and reading/writing
telefono/base/it/yasde/Smistatore.java46Dispatch of the command channel
telefono/base/it/yasde/Custode.java384The guardian: a separate shell process that restores the phone
telefono/base/it/yasde/Resti.java137Leftovers of old sessions: finding and removing
telefono/base/it/yasde/Pari.java29Who may connect to the service socket
telefono/base/it/yasde/Nascoste.java44Single point for hidden APIs and their startup check
telefono/base/prove.sh12JVM tests
telefono/base/prove/prova_telefono.py504Real-phone test
Phone: video and input
telefono/video/it/yasde/Video.java193Video channel and commands 0x40–0x4f
telefono/video/it/yasde/Sessione.java594A session: virtual screen, encoder, the app on it
telefono/video/it/yasde/Codificatore.java241Hardware H.264 encoder and its reader thread
telefono/video/it/yasde/Inoltro.java43Rules of what leaves on the video channel
telefono/video/it/yasde/Input.java214Input channel
telefono/video/it/yasde/Iniettore.java295Builds and injects input events
telefono/video/it/yasde/Gesti.java203State of gestures in progress
telefono/video/it/yasde/Pizzico.java176Geometry and state machine of the pinch
telefono/video/it/yasde/Specchio.java19Real screen measures for the mirror
telefono/video/it/yasde/ControlloSchermi.java82Protected-screen watch
telefono/video/it/yasde/AnalisiFinestre.java86Reads the window dump for protected windows
telefono/video/it/yasde/LiberaTask.java34Close with task removal
telefono/video/it/yasde/Barriera.java32Barrier on an execution queue
telefono/video/it/yasde/Binario.java16Protocol string reading
telefono/video/it/yasde/NascosteVideo.java315Hidden APIs of video and input
telefono/video/it/yasde/ProvaVideo.java99Isolated test of a session
telefono/video/prove.sh34JVM tests
telefono/video/prove/prova_gesti.py153Real-phone test: gestures
telefono/video/prove/prova_mouse.py131Real-phone test: right and middle mouse buttons
telefono/video/prove/prova_pausa.py78Real-phone test: pause
telefono/video/prove/prova_pausa_prod.py205Real-phone test: pause in production
telefono/video/prove/prova_rotella.py96Real-phone test: wheel
telefono/video/prove/prova_schermi.py112Real-phone test: screens
telefono/video/prove/prova_video.py583Real-phone test: video
telefono/video/prove/prova_zoom.py135Real-phone test: zoom
Phone: audio
telefono/audio/it/yasde/Audio.java193Audio channel
telefono/audio/it/yasde/Cattura.java313One capture: loopback, Opus
telefono/audio/it/yasde/NascosteAudio.java317Hidden APIs of audio
telefono/audio/it/yasde/Volume.java89Media volume through a shell command
telefono/audio/prove.sh14JVM tests
telefono/audio/prove/prova_audio.py536Real-phone test
telefono/audio/prove/bin_a_ogg.py114Converts captured audio packets to Ogg Opus
Phone: data
telefono/dati/it/yasde/Dati.java218Commands 0x70–0x7d, 0x90 and events
telefono/dati/it/yasde/CampiDati.java420Pure part: fields, encoding, limits
telefono/dati/it/yasde/NascosteDati.java1,010What the data layer asks Android
telefono/dati/it/yasde/AnalisiBatteria.java41Parses dumpsys battery
telefono/dati/it/yasde/AnalisiNotifiche.java273Parses notifications from the dump
telefono/dati/it/yasde/LetturaUnica.java75A blocking read on its own thread with a deadline
telefono/dati/it/yasde/LogicaPosizione.java308Pure part of the position: recency, rounding to 0.005°
telefono/dati/prove.sh9JVM tests
telefono/dati/prove/prova_dati.py332Real-phone test
telefono/dati/prove/prova_posizione.py152Real-phone test: position
telefono/dati/prove/prova_widget.py108Real-phone test: widget data
telefono/dati/prove/prova_widget2.py161Real-phone test: newer widget data
telefono/dati/prove/conta_verticali.py95Counts portrait-only apps
telefono/dati/prove/sonda_riproduzione.sh17Probe: playback information
telefono/dati/prove/sonda_widget.sh17Probe: widget data
Phone: archive, clipboard
telefono/archivio/it/yasde/Archivio.java210Thumbnails and storage
telefono/archivio/it/yasde/Cerca.java171Search channel
telefono/archivio/it/yasde/Percorrenza.java143Breadth-first walk of a folder
telefono/archivio/it/yasde/ConfrontoNomi.java34Name comparison for search
telefono/archivio/it/yasde/BinarioArchivio.java46Protocol reading for this piece
telefono/archivio/prove.sh9JVM tests
telefono/archivio/prove/prova_archivio.py275Real-phone test
telefono/appunti/it/yasde/Appunti.java290Clipboard channel
telefono/appunti/it/yasde/Regole.java201Pure part: message format, never-pass rules, echo suppression
telefono/appunti/it/yasde/NascosteAppunti.java297Hidden APIs of the clipboard
telefono/appunti/prove.sh17JVM tests
telefono/appunti/prove/prova_appunti.py486Real-phone test
Phone: panel and switches
telefono/pannello/it/yasde/Pannello.java825Physical panel commands
telefono/pannello/it/yasde/TieniSveglio.java250Keeps the phone awake while the PC is alive
telefono/pannello/it/yasde/AssenzaPc.java141Rule of the PC's absence
telefono/pannello/it/yasde/InputFisico.java187Notices a touch or key on the real screen
telefono/pannello/it/yasde/EventiEvdev.java34Reads kernel input events
telefono/pannello/it/yasde/Frequenze.java31Rate chosen with the panel off
telefono/pannello/it/yasde/ImpostazioniPannello.java66System settings through a shell command
telefono/pannello/it/yasde/ShellPannello.java54Shell commands with a real deadline
telefono/pannello/it/yasde/NascostePannello.java514Hidden APIs of the panel
telefono/pannello/prove.sh27JVM tests
telefono/pannello/prove/prova_pannello.py648Real-phone test
telefono/pannello/prove/prova_sveglio.py491Real-phone test: staying awake
telefono/controlli/it/yasde/Controlli.java470Quick switches and find-my-phone commands 0x80–0x8f
telefono/controlli/it/yasde/Trova.java389Find my phone (switched off)
telefono/controlli/it/yasde/Telefono.java72What the switches ask of the phone
telefono/controlli/it/yasde/TelefonoAndroid.java360The real phone for the switches
telefono/controlli/it/yasde/ComandiShell.java68Restore lines for the guardian
telefono/controlli/it/yasde/ShellControlli.java54Shell commands with a deadline
telefono/controlli/it/yasde/AnalisiNonDisturbare.java93Parses the Do Not Disturb state
telefono/controlli/it/yasde/NascosteControlli.java154The one hidden API of this piece
telefono/controlli/prove.sh20JVM tests
telefono/controlli/prove/prova_controlli.py579Real-phone test
Table 20.2 — The project's files

20.3 · The project in numbers

The same files, grouped by what they are.

PartWhereLinesContents
Shell, programsrc/shell/ (not tests, demos, fake)36,105The GTK 4 interface
Shell, fake backend, demos and testssrc/shell/22,986Fake phone, demos, logic and screen tests
PC piecessrc/*/24,054ADB, discovery, pairing, connection, component, data, files, transfers, video, audio, windows, configuration, weather
PC piece tests and fakessrc/*/26,968Tests and fakes of the pieces above
Phone componenttelefono/*/it/12,397Java source of the component
Phone tests and probestelefono/6,150Python and shell tests
Packagingpacchetto/1,195AppImage scripts and checks
Tools and buildroot, strumenti/, telefono/costruisci.sh4,219Meson root, build scripts, development tools
Total134,074
Table 20.3 — The project in numbers
Chapter 21

Known problems

21.1 · The known problems at a glance

Only real problems, taken from the open points of the project plan and from the code. Each one says what is known, what is not, and where to look. None of them blocks the program.

ProblemStateWhere
Direct scan-out (offload) of the video not confirmedOpen: to understand before a releasesrc/shell/superficie/superficie.c
1:1 image at a fractional scale (125%, 150%)Function exists, not wired into the windowssrc/shell/finestra-app/finestra_app.c
Blur behind the glass surfaces costs drawing time; off unless the renderer is GL, NGL or VulkanKnown: with four video windows the median draw time goes from 5.1 to 7.1 ms with the blur on the windows only and to 8.5 ms with the launcher open above them (95th percentile 7.2 → 10.0 → 12.8 ms; measured once, CPU about +50%); with any other renderer (for example CPU drawing, GskCairoRenderer) the surfaces have an almost opaque fill. Readability: over a very dark or very bright wallpaper the secondary text on the 58% veil loses contrastsrc/shell/comune/vetro.c, src/shell/finestra-app/finestra_app.c
Relative XDG_CACHE_HOME in the AppImage launcherKnown, not blockingpacchetto/AppRun
In-memory cache on some systemsKnown: the wallpaper is lost at every reboot theresrc/config/percorsi.c
Switched-off features: Find my phone, Quick notes, Now playingDeliberatesrc/shell/desktop/widget.c
Restores lost when the wireless debugging restartsOpen point, mitigatedtelefono/base/
Never tried liveA list of things proven only by testschapter 16
Phone panel with no idle time; audio and video not in sync; Vulkan decoding copies framesOpen: to decideFunctions that are off
Documents that disagree with the codeA listthis chapter
Table 21.1 — The known problems at a glance

21.2 · Direct scan-out of the video

On one machine with an Intel GPU (GTK 4.18.6, a real screen, with GDK_DEBUG=offload, even with force-offload, with the Vulkan and the GL renderers) GTK never writes the line "Attaching … GdkDmabufTexture": the direct pass of the images to the screen does not appear active, neither in the surface demo nor in the prototype measured at the beginning (strumenti/prototipo-gtk.c: same result).

  • The textures are DMA-BUF (zero refusals): the video reaches the graphics card without copies in memory; only the last step is missing.
  • It does not depend on our widget tree (the prototype behaves the same). What is not known: whether it is the machine or the compositor, or a rule of GTK that does not say its reason.
  • A hint for the real windows: rounded corners with clipping (finestra-app.css, GTK_OVERFLOW_HIDDEN) would prevent it anyway.
  • Not urgent: the fluidity measured today is already reached without this step.

21.3 · The 1:1 image at fractional scales

Windows are sized so that the image is 1:1 with the physical pixels. At a fractional shell scale the widget's size is rounded to whole logical pixels (1000 physical pixels at 1.5 is 667 logical, which is 1000.5 physical), so the image is not exactly 1:1 and is resampled. Scales 1 and 2 are not affected.

  • The surface has the answer: ph_superficie_misura_esatta (src/shell/superficie/superficie.h) draws the image in a rectangle of non-integer size inside its allocation (ph_sup_rettangolo_esatto in src/shell/superficie/logica.c), and ph_fa_origine_pixel_intero computes an origin on a whole physical pixel.
  • Only the surface demo calls ph_superficie_misura_esatta today: the inner windows of the real program do not. The windows must also be tried on a small screen and at scales 125% and 150% before a release.

21.4 · Smaller issues

  • Relative XDG. With XDG_CACHE_HOME relative, or a non-absolute HOME, pacchetto/AppRun uses the value as it is; the program does not (it ignores a relative XDG variable, as the specification says), so the two may disagree on the cache folder.
  • Memory-backed cache. On the tablet used for tests ~/.cache lives in memory and is emptied at every reboot, so the wallpaper image saved there is lost each time (and a profile that names it then points to nothing; ph_cfg_pulisci_sfondi only removes files, it does not repair the profile). To evaluate.
  • The product name and trademarks. The name "Samsung DeX" belongs to Samsung; a non-affiliation line is present in the manuals and in the package. It is not a legal opinion.
  • Pairing screen hint. When the phone does not announce itself on the network the screen stays at Looking for phones on the network… without saying what to check (in a live test the phone had to have its wireless debugging switched off and on). Hints after a few seconds without results were proposed, and the answer is awaited.

21.5 · Functions that are off

Some functions exist in the code and are off.

FunctionStateDetail
Find my phoneNot offeredThe widget is not in the catalog (PH_DSK_TROVA_OFFERTO is 0); on the phone the command is switched off by a constant and touches nothing (message TROVA_AVVIA answers an error). Measured reasons: an audio track cannot be created from the shell process, and the switch to "ring" raises Android's saved ringer volume from 0 to 1 with no return. A future evolution, to take up with a test phone that is not the user's.
Quick notesNot offeredThe type note is in the profile format but not in the catalog (it was left for after the app worked).
Now playing, recent calls, networkNot madeNow playing needs a test with a real playback; the other two were to be evaluated for feasibility with pure Android, without root.
Audio in a window recordingNot wiredRecordings hold only video. src/video/cattura.h already accepts an Opus audio track, and the contract has the con_audio option, but the real services accept it and ignore it (src/shell/ossatura/sv_flussi.c): the step that brings the audio packets to the recording is missing.
Breaking away from FFmpegTo evaluateFFmpeg is confined to src/video/ precisely so it can be replaced later.
Idle time of the physical panelMissingThe idle time foreseen by the specification (4.7) and by docs/protocollo.md §2.9 does not exist in the code: the panel is turned off again only at the first input from the PC with the phone "in hand". Either the function is missing or the protocol must be corrected: the user's decision.
Audio and video syncNot activeph_audio_tempo_telefono_us is not used by the shell: frames are shown as soon as they arrive.
Vulkan decoding copies framesOpen: to evaluateThe automatic order is VA-API first, then Vulkan: Vulkan decoding is used only where VA-API is missing or fails (for example a driver that offers only Vulkan Video), and there every frame is copied to memory (src/video/esporta.c, PH_ESPORTA_RIPIEGO): the copy-free path holds only with VA-API. It contradicts the architecture choice of never taking the copying path, and the measurements (27 frames per second with copies). To evaluate: export without copies also from Vulkan. On the machine tried VA-API is used, so it is not seen there.
Text sizeOpenThe size of texts in app windows (DeX uses 90%) is to be judged live.
Technical measurements fileNot connectedsrc/config/profilo.c has no caller outside its tests (chapter 14).
Decoder not replaced when the device is lost in mid-streamTo evaluateA decoder born with a hardware via that FFmpeg drops to software (at the first packet, or after a new configuration such as a resize) is now recreated once as software (decision line and toast). A device lost in the middle of a session is not handled in the same way: it gives only decoding errors and key-frame requests every 500 ms, the decoder is not recreated and the via is not changed. Read from the code (src/video/decodifica.c, src/shell/ossatura/sv_flussi.c), never run.
Table 21.2 — Functions that are off or incomplete

21.6 · Restores lost when the debugging restarts

When the wireless debugging is switched off and on, the phone's init system kills the whole process group, the service and its guardian, and nothing restores. A process of ours cannot survive that without root. Leftovers seen once after real sessions: jars and guardian scripts in /data/local/tmp, one with a volume restore never executed.

  • Remedy in place: the next service's startup runs the pending restores and removes the leftovers (telefono/base/it/yasde/Resti.java, telefono/base/it/yasde/Custode.java). The pending restore is run only if the setting still has the value YASDE put there.
  • Open points: a guardian script of an old session with the same pid as the new service, if it was not run at that startup, is overwritten (it should be renamed); and the PC is not told about a restore that was never executed (a contract to write).
  • Open point: reduce what YASDE changes durably, preferring what Android undoes by itself when the process dies (the screen timeout at its maximum, and the maximum media volume, are to be measured). The PC also sends a presence message every 5 minutes, and after 30 minutes without a sign of life the phone stops keeping itself awake (chapter 6).

21.7 · Never tried live

What the project's own record says has not been seen working in the real program.

  • Tried live on 24 November 2026 with the AppImage, on one machine and one phone: pairing from an empty installation, the panel turning off at connection, the bar volume at 100%, Compatibility. The AppImage with the interface was tried on one distribution; the others are not. Never tried live: every English sentence on screen (error sentences too), the pairing screen's three instruction lines, a wrong pairing code, a code pasted with spaces, authorization revoked from the phone, and wireless debugging switched off and on with the app open.
  • The Compatibility switch was confirmed live with one app (Onecta by Daikin drawn at the right size in a phone-shaped window; the hot change is enough). The weather has not been tried live with a real forecast request.
  • The AppImage on another distribution and with another glibc, and everything the build script cannot see (17.6 “What the build does not prove”).
  • Behavior at fractional scales and on small screens (21.3 “The 1:1 image at fractional scales”).
  • One phone only: other makers and Android versions are not covered.

21.8 · Documents that disagree with the code

Places where the written documents and the code do not agree. The code is right.

WhereWhat it saysWhat the code does
src/finestre/finestre.h, head comment, point 1A dragged window stays above the bar.It may go down until only the title bar is visible (src/finestre/finestre.c).
src/shell/CONTRATTI.md, decisions of 23 NovemberThe bar has no pinned favorites.Pinned apps exist: PhShellGestoreFissate in src/shell/shell.h, up to 16 per phone.
meson_options.txt, the pezzo descriptionLists pieces up to transfers.The pieces are more (see the root meson.build).
src/shell/finestra-app/COMPITO.md, opening sizes296×470 and 380×420 from the mockup.The default is the phone's screen in points (12.4 “The density rule”).
data/en/shell-trasferimento.txt, one key"This version of YASDE cannot install apps on the phone yet."Apps are installed (13.5 “Installing and uninstalling APKs”); the key is a leftover, not used by any ph_t call.
docs/protocollo.md, VIDEO_APRIDoes not cite the limits.telefono/video/it/yasde/Video.java imposes density 40 to 1000, bitrate and frame-rate limits.
docs/protocollo.md, VIDEO_EVENTOEvent 3 exists.The phone never sends it.
telefono/pannello/it/yasde/Pannello.java, comment at line 32The wake lock starts at startup.It starts from the greeting (SALUTO).
src/adb/adb.hCites the adbkey format.The file is chiave.pem.
The specificationTwo guardians.The code has one (Custode).
pacchetto/LEGGIMI.md, line 169Cites libfuse.so.2.The AppImage has libfuse3 inside and asks only for fusermount3 or fusermount.
src/config/config.h, the example of widget typesLists eight types.The code accepts fifteen (14.2 “The file formats and their keys”).
Table 21.3 — Documents that disagree with the code
Chapter 22

Glossary

22.1 · English terms

Terms used in the manual, in alphabetical order.

AppImage
The single-file package of YASDE (YASDE-2.1-x86_64.AppImage) with the program, the phone component and the libraries. See 17.3 “The AppImage”.
AppRun
The AppImage's launcher script: sets libraries, schemas and image loaders, then starts the program. See 17.3 “The AppImage”.
Automatic density
The rule that gives every app window a stream equal to its physical pixels and a density of 160 times the shell scale. See 12.4 “The density rule”.
Backend
A realization of the services: the real one in the skeleton, or the fake one. See 11.4 “The services and their backends”.
Broadway
GTK's virtual screen (gtk4-broadwayd), used by the screen tests in the build container. See 16.2 “Running the tests”.
Compatibility
The per-app window switch that gives the app the phone's real density. See 12.6 “Compatibility”.
Component
The Java code that runs on the phone, started with app_process (chapter 6).
Contract
A header or document that fixes how two pieces talk (for example servizi.h or the protocol document). A piece does not change a contract by itself. See 18.1 “Principles of the project”.
Delivery
Passing a function to the GTK thread with ph_shell_consegna. See 11.3 “Threads and delivery to the GTK thread”.
Decoding path (via)
The way an H.264 stream is decoded: PH_VIA_VAAPI, PH_VIA_VULKAN or PH_VIA_SOFTWARE. See 8.6 “How the decoding path is chosen and when it falls back”.
DMA-BUF
A buffer shared with the graphics card, which lets a decoded frame reach the screen without a copy in memory. See 11.7 “The video surface”.
DRM PRIME
The FFmpeg pixel format AV_PIX_FMT_DRM_PRIME that describes a frame as DMA-BUF file descriptors; a VA-API frame is mapped to it without copying. See 8.5 “Hardware acceleration end to end”.
Fake backend
A simulated phone in memory used by demos and tests. See 11.9 “The fake backend”.
Guardian
The phone-side shell process that restores the phone's settings if the service dies (chapter 6).
Host window
The one real GTK window of the program, which contains the whole shell. See 11.5 “The skeleton”.
Inner window
The window of a phone app drawn inside the host window. See 12.1 “The window rules”.
Layer
One level of the shell's stack: desktop, windows, bar, panels, toasts, drop, veil, host title. See 11.2 “Layers, popups and piece handlers”.
Modifier (DMA-BUF)
A 64-bit code that tells how the planes of a DMA-BUF are laid out in memory (tiling, compression); it travels with the fourcc and the file descriptors from ph_esporta to GTK. See 8.5 “Hardware acceleration end to end”.
Mirror
The inner window that shows the phone's real screen. See 12.7 “The mirror window”.
Pairing
Authorizing the PC on the phone with the six-digit code (chapter 5).
Offload (scan-out)
Handing a DMA-BUF texture straight to the display hardware instead of drawing it with the renderer, requested with GtkGraphicsOffload; GTK decides, and it was not seen active on the one machine tried (an Intel GPU, GTK 4.18.6). See 8.9 “Requirements and limits of hardware acceleration”.
Piece
One folder with its build file, its contract and its tests. See 16.1 “Tests of the PC pieces”.
Popup
A panel, menu or dialog of the shell; only one is open at a time. See 11.2 “Layers, popups and piece handlers”.
Pool
A group of worker threads of the real services with one role. See 11.3 “Threads and delivery to the GTK thread”.
Profile
The per-phone file telefono-<serial>.toml (desktop, folders, pinned apps…). See 14.2 “The file formats and their keys”.
VA-API
The Linux interface (libva) to the video decoding hardware of a GPU; the first choice of the decoding order, and the only one that gives the frame to the shell without copies. See 8.6 “How the decoding path is chosen and when it falls back”.
Vulkan Video
The Vulkan extension VK_KHR_video_decode_h264 for decoding on the GPU; the second choice, used only if offered as shipped, and it copies every frame to memory. See 8.6 “How the decoding path is chosen and when it falls back”.
Snapshot
The last state received for something (connection, apps, notifications…), replaced only on the GTK thread. See 11.4 “The services and their backends”.
Surface
The widget that shows one video stream. See 11.7 “The video surface”.
Veil
The full-area cover for the lock and the lost connection. See 11.5 “The skeleton”.
Widget (desktop)
A card on the desktop (clock, weather…), drawn by the desktop piece (not a GTK widget). See 19.3 “Adding a widget”.

22.2 · Italian names in the code

The code is Italian: identifiers, files, configuration keys and comments keep Italian names, and the manual quotes them as they are. These are the recurring ones with their translation.

abbinamento
Pairing: the piece src/abbinamento/ and the code-based pairing.
avvisi
Notices: pop-up messages; also the preference avvisi.
barra
The bar at the bottom of the host window (src/shell/barra/).
cartella_invio, cartella_ricezione
Send folder and receive folder, in the profile.
cattura
Capture: screenshot and recording (src/video/cattura.h).
collegamento
Connection: the state machine that keeps the relationship with one phone (src/collegamento/).
componente
The component on the phone, and its PC side (src/componente/).
coda
Queue (transfers; audio).
consegna
Delivery: ph_shell_consegna.
custode
Guardian: the phone-side restore process (Custode).
dati
Data: src/dati/, the phone's apps, state, notifications, storage…
fissata
Pinned: an app fixed on the bar ([[fissata]]).
finestra, finestre
Window, windows (src/finestre/).
finto
Fake (as in the fake backend, src/shell/finto/).
flusso
Stream: a video stream, or the stream size of a window.
immagine
Image.
lingua
Language.
meteo
Weather.
ossatura
Skeleton: the main window and program piece (src/shell/ossatura/).
pannello
Panel: the phone's physical screen panel (telefono/pannello/).
pezzo
Piece: the unit of work, and the build option pezzo.
prova, prove
Test, tests (prova_*.c, strumenti/prova.sh).
ricezione
Receive: phone to PC file transfer.
scoperta
Discovery: finding phones with mDNS (src/scoperta/).
servizi
Services: the shell's only door (src/shell/servizi.h).
sfondo
Wallpaper.
sveglia
Alarm clock.
superficie
Surface (the video surface).
tutto
All: the value of the build option pezzo that builds every approved piece.
veloce
Fast: the optimized whole build, without checks, for measurements.
velo
Veil.