Vai al contenuto principale
Ricetta numero 132

Ricettario · Capitolo 10 · Output e integrazione

Una scheda di laboratorio con video su schermo e in EPUB

Due risorse video con i loro file MP4: la stampa mostra di ciascuna il primo fotogramma con un codice QR, renderToHtml e postext-epub riproducono i file.

In questa pagina
  • Esempio in inglese: non c’è ancora un’edizione italiana
  • Formato 210 × 297 mm
  • 2 colonne, Intercolonna di 7 mm
  • Source Serif 4 9,4/13,2
  • Red Hat Display
  • Red Hat Mono
  • 2 pagine
  • Livello
  • Postext 1.65.0
  • Impaginato in 144 ms
  • 239 righe di codice

In breve

Una scheda di fisica con due brevi filmati di un pendolo. Sulla carta ogni filmato è un’immagine fissa con un codice da inquadrare; sullo schermo e nell’e-book i filmati si riproducono sulla pagina.

Che cosa comporrai

La scheda di laboratorio 4.2 di Bench Physics, un quaderno A4 per studenti dai 16 ai 18 anni, sul periodo di un pendolo. Una fascia color ruggine contiene il titolo e i campi per nome, gruppo e data. Al piede della prima pagina due clip dello stesso pendolo, lasciato andare da 10° e da 80°, stanno affiancate. Sulla carta ogni clip è il suo primo fotogramma, con un segno di riproduzione e un codice QR che apre l’MP4. Nell’edizione a schermo accanto alle pagine, e nell’EPUB che scrive il pen, le stesse due risorse si riproducono nel player video del lettore. La seconda pagina contiene il procedimento, una tabella da compilare, i periodi esatti calcolati dal codice e quattro domande con i riquadri per le risposte.

Questa ricetta risponde a

  • Come riproducono i video del libro l’edizione HTML e l’EPUB, e come nascondo il pulsante di download?
  • Come metto un video in un libro stampato in modo che il lettore possa aprirlo dalla pagina?

La risposta breve

script.js · righe 32–61nel codice completo
const clip = (id, file, poster, caption, altText) => ({
  id, typeId: 'video', kind: 'video', createdAt: 0, updatedAt: 0, caption: t(caption),
  note: t({ en: '8.00 s, 25 frames per second · Postext Cookbook, CC BY 4.0',
    es: '8,00 s, 25 fotogramas por segundo · Postext Cookbook, CC BY 4.0' }),
  altText: t(altText), placement: { position: 'bottom', span: 'column' },
  video: { source: 'file', fileId: file, format: 'mp4', width: 640, height: 360, duration: 8,
    url: asset(file), // the production address: printed as the QR code, linked from the PDF
    poster: { fileId: poster, format: 'jpeg', width: 640, height: 360 }, // the first frame
  },
});
const videoStyle = {
  playMark: { shape: 'rounded', position: 'top-left', size: mm(7), inset: mm(3),
    background: col('ink'), color: col('paper') },
  qr: { position: 'bottom-right', size: mm(19), inset: mm(2.5), // 111 characters: 45 modules
    color: col('ink'), background: col('paper'), radius: mm(1) },
  // The HTML5 player of a file honours every option. download: false writes
  // controlslist="nodownload": it hides the button, and the file stays at its address.
  player: { download: false, loop: true, muted: true, preload: 'auto',
    pictureInPicture: false, remotePlayback: false },
};
const clips = [
  clip('small', 'pendulum-small.mp4', 'pendulum-small-poster.jpg',
    { en: 'Released from rest at 10°.', es: 'Soltado desde el reposo a 10°.' },
    { en: 'A rust bob on a dark string hangs a few degrees off the vertical, under a short bar.',
      es: 'Una lenteja roja cuelga de un hilo oscuro a pocos grados de la vertical.' }),
  clip('large', 'pendulum-large.mp4', 'pendulum-large-poster.jpg',
    { en: 'Released from rest at 80°.', es: 'Soltado desde el reposo a 80°.' },
    { en: 'The same pendulum pulled out almost level with its pivot, a pale arc below it.',
      es: 'El mismo péndulo, casi a la altura de su eje, sobre un arco pálido.' }),
];

Ingredienti

Tipo
Source Serif 4, Red Hat Display, Red Hat Mono (SIL OFL 1.1)
Risorse
  • pendulum-large-poster.jpg
  • pendulum-large.mp4
  • pendulum-small-poster.jpg
  • pendulum-small.mp4
  • Video 1: a pendulum 1 m long released from 10°, 8 s at 25 frames per second, rendered from an RK4 solution of the pendulum equation (1 ms steps) with Python and encoded with ffmpeg (Postext Cookbook, CC BY 4.0)
  • Video 2: the same pendulum released from 80°, rendered and encoded the same way (Postext Cookbook, CC BY 4.0)
  • The first frame of Video 1, its printed poster (Postext Cookbook, CC BY 4.0)
  • The first frame of Video 2, its printed poster (Postext Cookbook, CC BY 4.0)

Preparazione

#1 · Dai a ogni clip un indirizzo di produzione e un file

Il codice è nella risposta breve qui sopra. Una clip tua ha due indirizzi. video.url è dove la troverà il libro pubblicato: il codice QR lo stampa e il PDF vi collega il poster, quindi qui è l’indirizzo jsDelivr della clip, quello che un telefono può aprire oggi. video.fileId indica il file stesso, tenuto fuori dal documento come una bitmap, per gli output che possono contenerlo o riprodurlo da un’altra posizione (vedi Formato del documento › Video). Le opzioni del player in videoStyle.player valgono per ogni clip: si ripetono in loop, partono senza audio, si caricano per intero (27 e 61 KB) e non offrono download, picture in picture né trasmissione, così le clip restano sulla scheda.

#2 · Impagina l’edizione a schermo dalla stessa sorgente

script.js · righe 172–180nel codice completo
const [PANE_W, PANE_H] = [400, 640]; // px
const screen = {
  page: { width: px(PANE_W), height: px(PANE_H), dpi: 122, // so the 9.4 pt text is 16 px
    margins: { top: px(28), bottom: px(28), left: px(22), right: px(22), mirror: false } },
  layout: { layoutType: 'single' }, bodyText: { textAlign: 'left' }, // ragged in a narrow pane
  headings: { levels: [{ level: 1, span: 'column', breakBefore: { enabled: false },
    fontSize: px(28), lineHeight: px(32), fontWeight: 800, marginBottom: px(16),
    advancedDesign: { enabled: false } }] }, // the title alone: the band and fields are print's
  header: { elements: [] }, footer: { elements: [] } };

L’edizione a schermo vive nella configurazione come htmlViewer.overrides, che canvas e PDF ignorano. A 122 dpi ogni misura data in punti risulta circa un quarto più grande che a 96, quindi il testo da 9,4 pt si legge a 16 px nel pannello e didascalie, riquadri e tabelle crescono con esso. L’apertura mantiene il titolo e lascia cadere la fascia e i campi, che appartengono alla carta.

#3 · Riproduci le clip nel pannello

script.js · righe 333–340nel codice completo
// A shadow root keeps the page's styles out, so the pane shows the lines as they were measured.
const pane = desk.querySelector('#screen').attachShadow({ mode: 'open' });
pane.innerHTML = renderToHtml(buildDocument({ markdown, resources },
  applyHtmlViewerOverrides(config())), { mode: 'single', padding: 0, background: '#ffffff',
  resourceImageUrl: imageUrl, // the posters, until a clip plays
  resourceVideoUrl: (fileId) => asset(fileId) }); // the file each <video> plays: the asset here
const top = (el) => el.getBoundingClientRect().top; // open the pane on the first player
pane.host.scrollTop = top(pane.querySelector('video')) - top(pane.host) - 48;

renderToHtml compone ogni risorsa video come un <video> HTML5 con le opzioni del player come attributi: controls, muted, loop, playsinline, preload="auto", disablepictureinpicture, disableremoteplayback e controlslist="nodownload". Quest’ultimo nasconde solo il pulsante. Chiunque abbia l’indirizzo può comunque salvare il file, quindi consideralo ordine, non protezione. resourceVideoUrl passa al backend un indirizzo riproducibile per ogni fileId, come fa resourceImageUrl per i poster. Qui è la risorsa pubblicata; un sito che tiene i caricamenti altrove restituisce il suo URL, o un URL blob dei byte. Senza, il player ripiega su video.url, e senza nessuno dei due il pannello mostra il poster.

#4 · Metti le clip in un EPUB a layout fisso

script.js · righe 290–310nel codice completo
const bytesOf = async (url) => new Uint8Array(await (await fetch(url)).arrayBuffer());
const media = new Map(await Promise.all(clips.map(async ({ video }) =>
  [video.fileId, { bytes: await bytesOf(asset(video.fileId)), mediaType: 'video/mp4' }])));
// Every face as bytes (gotcha: epub-embeds-given-fonts): the files loadFonts loaded, latin
// for each face and greek for the text face, limited to the Greek block and listed after
// latin, so a reading system tries it first for θ and π.
const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
  ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
const fonts = await Promise.all([...faces.map((face) => [face, 'latin']),
  ...faces.filter(({ family }) => family === TEXT)
    .map((face) => [{ ...face, unicodeRange: 'U+0370-03FF' }, 'greek'])]
  .map(async ([face, subset]) => ({ ...face, format: 'woff2', bytes: await bytesOf(
    `https://cdn.jsdelivr.net/npm/@fontsource/${fontsourceId(face.family)}@5/files/`
    + `${fontsourceId(face.family)}-${subset}-${face.weight}-${face.style}.woff2`) })));
const epub = await renderToEpub([doc], { layout: 'fixed', fonts,
  metadata: { title: doc.metadata.title, creators: ['Postext Cookbook'], language: LANG,
    rights: 'CC BY 4.0', modified: new Date('2026-10-05T00:00:00Z') }, // the same bytes each run
  // The clips as video/mp4 and the posters as pictures; the book packs both under media/.
  resourceBytes: (fileId) => media.get(fileId)
    ?? { bytes: imageBytes(fileId), mediaType: 'image/jpeg' },
});

La scheda è costruita attorno a due clip affiancate e a riquadri vuoti da compilare, quindi il layout fisso la conserva: ogni pagina come stampata, con un player dove c’era il poster. Anche un EPUB fluido riprodurrebbe le clip, una sotto l’altra alla larghezza del testo. resourceBytes risponde video/mp4 per ogni clip e un JPEG per ogni poster, e il writer li impacchetta sotto media/ e images/. L’EPUB conserva solo gli attributi che il suo schema conosce (controls, autoplay, muted, loop, playsinline, preload), quindi il pulsante di download e il resto restano al sistema di lettura. Il file supera EPUBCheck senza errori né avvisi.

#5 · Componi θ e π in canvas, PDF ed EPUB

Source Serif 4 tiene le lettere greche in un file Fontsource a parte, greek, accanto a latin. kitFonts(FONTS) trova le lettere greche nel testo e carica quel file per ogni carattere della famiglia, e fontsourceProvider lo incorpora nel PDF accanto al file latin per ogni carattere che compone θ o π, quindi le due lettere non richiedono codice. L’EPUB incorpora solo i font che gli passa il pen, quindi il passo 4 elenca i file greek del carattere del testo dopo quelli latin, ciascuno limitato al blocco greco dal suo unicodeRange.

#6 · Calcola la tabella nel codice

script.js · righe 65–86nel codice completo
// The arithmetic-geometric mean gives the elliptic integral K of the exact period in a few steps.
const T0 = 2 * Math.PI * Math.sqrt(1 / 9.81); // s: L = 1 m, g = 9.81 m/s²
const agm = (a, b) => (Math.abs(a - b) < 1e-15 ? a : agm((a + b) / 2, Math.sqrt(a * b)));
const period = (degrees) => T0 / agm(1, Math.cos((degrees * Math.PI) / 360));
const num = (x, digits) => x.toFixed(digits).replace('.', t({ en: '.', es: ',' }));
const cell = (content, align = 'right') => ({ content, align, verticalAlign: 'middle' });
const table = (id, caption, head, rows, columnWidths) => ({ id, typeId: 'table', kind: 'table',
  createdAt: 0, updatedAt: 0, caption: t(caption), placement: { position: 'here' },
  table: { model: { headerRowCount: 1, columnWidths, rows: [head.map((h, i) =>
    ({ ...cell(h, i ? 'right' : 'left'), isHeader: true })), ...rows] } } });
const periods = table('periods', { en: 'Exact periods of a pendulum 1.00 m long.',
  es: 'Periodos exactos de un péndulo de 1,00 m.' },
['Amplitude|Amplitud', 'T (s)', 'T/T~0~', 'Longer by|Aumento'].map((h) =>
  t({ en: h.split('|')[0], es: h.split('|').at(-1) })),
[5, 10, 20, 30, 45, 60, 80, 90].map((d) => [cell(`${d}°`, 'left'), cell(num(period(d), 3)),
  cell(num(period(d) / T0, 3)), cell(`${num((period(d) / T0 - 1) * 100, 2)} %`)]),
[1.2, 1, 1, 1.1]);
const blank = cell(' \n '); // two empty lines: room to write
const data = table('data', { en: 'Your measurements.', es: 'Tus medidas.' },
  t({ en: ['Clip', 'Swings in 8 s', 'T (s)'], es: ['Vídeo', 'Oscilaciones en 8 s', 'T (s)'] }),
  [10, 80].map((d, i) => [cell(`${t({ en: 'Video', es: 'Vídeo' })} ${i + 1} · ${d}°`, 'left'),
    blank, blank]), [1.2, 1.5, 0.8]);

Il periodo esatto richiede l’integrale ellittico completo K, e la media aritmetico-geometrica lo dà in pochi passi: T = T~0~ / AGM(1, cos ½θ~0~). La tabella stampa tre decimali con la virgola decimale in spagnolo, e le righe di 10° e 80° corrispondono alle clip: 2,010 s e 2,282 s, lo 0,2 % e il 13,8 % più lunghi di T~0~ = 2,006 s. In 8 s sono poco meno di quattro oscillazioni complete per la prima clip e tre e mezza per la seconda.

La ricetta completa

Sandbox
// ═══ Postext Cookbook · Nº 132 · A lab sheet whose clips play on screen and in the EPUB ════
// https://postext.dev/en/cookbook/pendulum-lab-video-players
// Code: MIT · Text: original (CC BY 4.0) · Clips: rendered in code (CC BY 4.0)
// Fonts: Source Serif 4, Red Hat Display, Red Hat Mono (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocument, buildDocumentWithFonts, prepareFonts, renderPageToCanvas, renderToHtml,
  applyHtmlViewerOverrides, registerResourceImage, defaultResourceTypes, resourceVideoLink,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
import { renderToEpub, readEpub } from 'https://esm.sh/postext-epub';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'pendulum-lab-video-players';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { // the clips' own colours: a cream ground, the rust bob, warm black ink
  ink: '#22201b', // text, the play mark, the QR modules, table heads
  rust: '#a8432b', // the accent: the band, labels, list numbers (the bob's red, darker)
  cream: '#f6f1e4', rule: '#cbc2ae', // box fills, a shade deeper than the clips; hairlines
  muted: '#68625a', paper: '#ffffff' }; // muted: running heads, notes, prompts
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.rust }) // defaults: rust
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [TEXT, DISPLAY, MONO] = ['Source Serif 4', 'Red Hat Display', 'Red Hat Mono'];
const [TOP, INNER, OUTER, BAND, LEAD] = [22, 20, 17, 84, 13.2]; // mm, A4; LEAD in pt
const px = (value) => ({ value, unit: 'px' }); // the screen edition's sizes
const at = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x, y }, size });
const label = (size, color = 'rust') => ({ fontFamily: MONO, fontSize: pt(size), fontWeight: 600,
  letterSpacing: pt(size * 0.16), textTransform: 'uppercase', color: col(color) });

// #region answer: two clips of the book's own: a poster and a QR code, or a player
const clip = (id, file, poster, caption, altText) => ({
  id, typeId: 'video', kind: 'video', createdAt: 0, updatedAt: 0, caption: t(caption),
  note: t({ en: '8.00 s, 25 frames per second · Postext Cookbook, CC BY 4.0',
    es: '8,00 s, 25 fotogramas por segundo · Postext Cookbook, CC BY 4.0' }),
  altText: t(altText), placement: { position: 'bottom', span: 'column' },
  video: { source: 'file', fileId: file, format: 'mp4', width: 640, height: 360, duration: 8,
    url: asset(file), // the production address: printed as the QR code, linked from the PDF
    poster: { fileId: poster, format: 'jpeg', width: 640, height: 360 }, // the first frame
  },
});
const videoStyle = {
  playMark: { shape: 'rounded', position: 'top-left', size: mm(7), inset: mm(3),
    background: col('ink'), color: col('paper') },
  qr: { position: 'bottom-right', size: mm(19), inset: mm(2.5), // 111 characters: 45 modules
    color: col('ink'), background: col('paper'), radius: mm(1) },
  // The HTML5 player of a file honours every option. download: false writes
  // controlslist="nodownload": it hides the button, and the file stays at its address.

Lo script.js composto funziona così com’è: incollalo nello script modulo di qualsiasi pagina, oppure apri la ricetta su CodePen. Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)

Varianti

#Fai partire da sola una clip

Il player di un video si sovrappone a videoStyle.player. La riproduzione automatica parte sempre senza audio, come chiedono i browser.

 ];
+clips[0].video.player = { autoplay: true }; // the 10° clip starts as the pane opens

#Mostra a schermo il poster stampato

Con html: 'poster' l’edizione HTML compone il poster con il segno di riproduzione e il codice QR, collegato all’indirizzo di produzione, al posto del player.

 const videoStyle = {
+  html: 'poster',

#Usa un video di YouTube o Vimeo

source: 'youtube' con l’indirizzo del video incorpora il player di YouTube da youtube-nocookie.com (privacy è attivo per impostazione predefinita). Quel player rispetta meno opzioni: controlli, schermo intero, riproduzione automatica, audio disattivato e loop, e quello di Vimeo aggiunge il menu della velocità e il picture in picture; nessuno dei due offre il download. Un EPUB non può incorporare il player di una pagina web, quindi lì il video è il suo poster collegato al video. Le opzioni e la loro portata sono elencate in Configurazione › Stile dei video.

Errori frequenti

Errore frequente

renderToEpub incorpora solo i font che gli passi

Le varianti caricate dal browser non sono file che postext-epub possa leggere: passa in options.fonts i byte di ogni variante usata dalle pagine (gli stessi file woff2 di Fontsource caricati dalla pagina). Una variante omessa viene segnalata come missingFont, e il sistema di lettura compone quel testo con un carattere suo, che in un layout fisso non entra più nelle righe con cui la pagina è stata composta. Incorpora solo varianti la cui licenza lo permette. Esportazione in EPUB →

Errore frequente

I file di Fontsource coprono le lettere, non i simboli

Il kit incorpora il file latin di Fontsource di un carattere, più il suo file latin-ext per č, ł, † e il suo file greek per α, χ (nelle famiglie che ne hanno uno: Lora e Gelasio no), quando il testo li compone, a schermo e nel PDF. Simboli come →, ≈, ✓ e ★ non sono in nessuno di quei file e spariscono nel PDF: disegnali, componili come matematica o scegli un carattere i cui file li contengano. Font incorporati nel PDF →

Gli MP4 sono H.264. Chrome, Edge, Safari e Firefox li riproducono, e così il Chrome for Testing usato dalla cattura. Un Chromium compilato senza i suoi codec proprietari, l’impostazione predefinita open source, no; codifica le clip in WebM (format: 'webm') se per i tuoi lettori conta.

Crediti

Testo
Testo originale, CC BY 4.0
Immagini
  • Video 1: a pendulum 1 m long released from 10°, 8 s at 25 frames per second, rendered from an RK4 solution of the pendulum equation (1 ms steps) with Python and encoded with ffmpeg · Postext Cookbook · CC BY 4.0
  • Video 2: the same pendulum released from 80°, rendered and encoded the same way · Postext Cookbook · CC BY 4.0
  • The first frame of Video 1, its printed poster · Postext Cookbook · CC BY 4.0
  • The first frame of Video 2, its printed poster · Postext Cookbook · CC BY 4.0
Font
Source Serif 4 (SIL OFL 1.1) · Red Hat Display (SIL OFL 1.1) · Red Hat Mono (SIL OFL 1.1)
SandboxPDF