FreeRDP
Loading...
Searching...
No Matches
h264_webcodecs.c
1
17
18/*
19 * The H.264 decompress callback runs on the graphics channel thread (a Web Worker) and must
20 * return the picture synchronously, while VideoDecoder delivers frames asynchronously on the
21 * event loop of the thread that owns it. The worker therefore proxies each job to the main
22 * browser thread with emscripten_proxy_sync_with_ctx() and sleeps until the main thread has
23 * decoded the frame, copied it into the I420 planes and called emscripten_proxy_finish().
24 *
25 * The planes keep the decoded sample values (no colour conversion in the browser), so
26 * h264.c converts them and combines the AVC444 main and auxiliary pictures as it does for
27 * every other backend.
28 *
29 * Browsers return I420 or NV12 for 4:2:0 and I444 for 4:4:4, which are copied as they are.
30 * Some (Firefox) return RGB frames instead, converted with the colour description of the
31 * stream; h264_webcodecs.js turns those back into full resolution Y'CbCr planes, see
32 * h264_wc_copy. The chroma planes are therefore always allocated at full resolution.
33 */
34
35#include <freerdp/config.h>
36
37#include <stdio.h>
38#include <string.h>
39
40#include <emscripten.h>
41#include <emscripten/proxying.h>
42#include <emscripten/threading.h>
43
44#include <winpr/assert.h>
45#include <winpr/string.h>
46#include <freerdp/log.h>
47
48#include "h264.h"
49
50#define H264_WC_NEEDS_BUFFER 2 /* picture decoded but larger than the planes */
51#define H264_WC_YUV444 3 /* picture copied as full resolution 4:4:4 planes */
52
53typedef struct
54{
55 int handle;
56 BOOL hevc; /* H.265: NAL types and codec string differ, the rest is the same */
57 BOOL hevc444; /* the HEVC stream is 4:4:4 */
58 BYTE* params; /* last parameter set NAL units (H.264 SPS/PPS, HEVC VPS/SPS/PPS),
59 * each with a 4 byte start code */
60 size_t paramsSize;
61 BYTE* yuv; /* Y, U and V planes in one allocation */
62 UINT32 width;
63 UINT32 height;
64 UINT32 stride[3];
65 BYTE* plane[3];
66} H264_CONTEXT_WEBCODECS;
67
68typedef struct
69{
70 int handle;
71 const BYTE* src;
72 UINT32 size;
73 int key;
74 const char* codec;
75 BYTE* const* plane;
76 const UINT32* stride;
77 int gbr; /* RGB frames hold Y'CbCr samples labelled as GBR, see h264_wc_copy */
78 UINT32 maxWidth;
79 UINT32 maxHeight;
80 UINT32 dim[2]; /* decoded width and height */
81 int rc; /* 1: 4:2:0 picture copied, 3: 4:4:4 picture copied, 0: no picture, 2: planes too
82 * small, <0: error */
83} h264_wc_job;
84
85/* in h264_webcodecs.js */
86extern void h264_wc_js_open(void* ctx, int* handle, const char* probe);
87extern void h264_wc_js_close(int handle);
88extern void h264_wc_js_decode(void* ctx, int handle, const BYTE* src, UINT32 size, int key,
89 const char* codec, BYTE* y, BYTE* u, BYTE* v, UINT32 ys, UINT32 cs,
90 int gbr, UINT32 maxWidth, UINT32 maxHeight, UINT32* dim, int* rc);
91extern void h264_wc_js_copy(void* ctx, int handle, BYTE* y, BYTE* u, BYTE* v, UINT32 ys, UINT32 cs,
92 int gbr, int* rc);
93
94EMSCRIPTEN_KEEPALIVE void freerdp_h264_wc_finish(em_proxying_ctx* ctx)
95{
96 emscripten_proxy_finish(ctx);
97}
98
99typedef struct
100{
101 int handle;
102 const char* probe; /* codec string the browser must support */
103} h264_wc_open;
104
105static void main_open(em_proxying_ctx* ctx, void* arg)
106{
107 h264_wc_open* open = arg;
108 h264_wc_js_open(ctx, &open->handle, open->probe);
109}
110
111static void main_close(void* arg)
112{
113 h264_wc_js_close(*(int*)arg);
114}
115
116static void main_decode(em_proxying_ctx* ctx, void* arg)
117{
118 h264_wc_job* job = arg;
119 h264_wc_js_decode(ctx, job->handle, job->src, job->size, job->key, job->codec, job->plane[0],
120 job->plane[1], job->plane[2], job->stride[0], job->stride[1], job->gbr,
121 job->maxWidth, job->maxHeight, job->dim, &job->rc);
122}
123
124static void main_copy(em_proxying_ctx* ctx, void* arg)
125{
126 h264_wc_job* job = arg;
127 h264_wc_js_copy(ctx, job->handle, job->plane[0], job->plane[1], job->plane[2], job->stride[0],
128 job->stride[1], job->gbr, &job->rc);
129}
130
131WINPR_ATTR_NODISCARD
132static BOOL on_main(void (*fn)(em_proxying_ctx*, void*), void* arg)
133{
134 return emscripten_proxy_sync_with_ctx(emscripten_proxy_get_system_queue(),
135 emscripten_main_runtime_thread_id(), fn, arg) == 1;
136}
137
138/* Finds the next Annex B NAL unit; trailing zero bytes belong to the next start code. */
139WINPR_ATTR_NODISCARD
140static BOOL next_nal(const BYTE* data, size_t size, size_t* offset, const BYTE** nal,
141 size_t* length)
142{
143 size_t pos = *offset;
144 if ((size < 3) || (pos == SIZE_MAX - size))
145 return FALSE;
146 while ((pos <= size - 3ull) &&
147 !((data[pos] == 0) && (data[pos + 1] == 0) && (data[pos + 2] == 1)))
148 pos++;
149 if (pos >= size - 3ull)
150 return FALSE;
151
152 const size_t start = pos + 3;
153 pos = start;
154 while ((pos <= size - 3ull) &&
155 !((data[pos] == 0) && (data[pos + 1] == 0) && (data[pos + 2] == 1)))
156 pos++;
157 size_t end = (pos <= size - 3ull) ? pos : size;
158 while ((end > start) && (data[end - 1] == 0))
159 end--;
160 *offset = end;
161 *nal = &data[start];
162 *length = end - start;
163 return TRUE;
164}
165
166/* H.264 and HEVC number their NAL unit types differently */
167#define H264_NAL_SLICE 1
168#define H264_NAL_IDR 5
169#define H264_NAL_SPS 7
170#define H264_NAL_PPS 8
171#define HEVC_NAL_BLA_W_LP 16 /* 16 to 21 start a random access point (IRAP) */
172#define HEVC_NAL_CRA 21
173#define HEVC_NAL_VPS 32 /* 0 to 31 are slices (VCL) */
174#define HEVC_NAL_SPS 33
175#define HEVC_NAL_PPS 34
176
177WINPR_ATTR_NODISCARD
178static BYTE nal_type(const H264_CONTEXT_WEBCODECS* sys, const BYTE* nal)
179{
180 return sys->hevc ? (nal[0] >> 1) & 0x3F : nal[0] & 0x1F;
181}
182
183WINPR_ATTR_NODISCARD
184static BOOL nal_is_slice(const H264_CONTEXT_WEBCODECS* sys, BYTE type)
185{
186 return sys->hevc ? (type < HEVC_NAL_VPS) : ((type == H264_NAL_SLICE) || (type == H264_NAL_IDR));
187}
188
189WINPR_ATTR_NODISCARD
190static BOOL nal_is_key(const H264_CONTEXT_WEBCODECS* sys, BYTE type)
191{
192 return sys->hevc ? ((type >= HEVC_NAL_BLA_W_LP) && (type <= HEVC_NAL_CRA))
193 : (type == H264_NAL_IDR);
194}
195
196/* a sequence parameter set starts a new set of saved parameters */
197WINPR_ATTR_NODISCARD
198static BOOL nal_is_sps(const H264_CONTEXT_WEBCODECS* sys, BYTE type)
199{
200 return sys->hevc ? ((type == HEVC_NAL_VPS) || (type == HEVC_NAL_SPS)) : (type == H264_NAL_SPS);
201}
202
203WINPR_ATTR_NODISCARD
204static BOOL nal_is_parameter_set(const H264_CONTEXT_WEBCODECS* sys, BYTE type)
205{
206 return nal_is_sps(sys, type) || (type == (sys->hevc ? HEVC_NAL_PPS : H264_NAL_PPS));
207}
208
209/* parameter sets too short to be used are dropped (the H.264 SPS is read for the codec) */
210WINPR_ATTR_NODISCARD
211static BOOL nal_is_saved(const H264_CONTEXT_WEBCODECS* sys, BYTE type, size_t length)
212{
213 if (!nal_is_parameter_set(sys, type))
214 return FALSE;
215 if (sys->hevc)
216 return length >= 3;
217 return (type != H264_NAL_SPS) || (length >= 4);
218}
219
220/* Remembers the parameter sets: they may arrive separately from the picture (MS-RDPEVOR),
221 * and a decoder that is created again after an error needs them with the next IDR picture. */
222WINPR_ATTR_NODISCARD
223static BOOL save_parameters(H264_CONTEXT_WEBCODECS* sys, const BYTE* data, size_t size, BOOL hasSps)
224{
225 size_t total = hasSps ? 0 : sys->paramsSize;
226 size_t offset = 0;
227 const BYTE* nal = nullptr;
228 size_t length = 0;
229 while (next_nal(data, size, &offset, &nal, &length))
230 {
231 if (length == 0)
232 continue;
233 if (nal_is_saved(sys, nal_type(sys, nal), length))
234 total += 4 + length;
235 }
236
237 BYTE* params = malloc(total);
238 if (!params)
239 return FALSE;
240 size_t pos = 0;
241 if (!hasSps && (sys->paramsSize > 0))
242 {
243 memcpy(params, sys->params, sys->paramsSize);
244 pos = sys->paramsSize;
245 }
246 offset = 0;
247 while (next_nal(data, size, &offset, &nal, &length))
248 {
249 if (length == 0)
250 continue;
251 if (!nal_is_saved(sys, nal_type(sys, nal), length))
252 continue;
253 const BYTE startCode[] = { 0, 0, 0, 1 };
254 memcpy(&params[pos], startCode, sizeof(startCode));
255 memcpy(&params[pos + 4], nal, length);
256 pos += 4 + length;
257 }
258 WINPR_ASSERT(pos == total);
259 free(sys->params);
260 sys->params = params;
261 sys->paramsSize = total;
262 return TRUE;
263}
264
265/* avc1.PPCCLL from profile_idc, constraint flags and level_idc of the first SPS */
266static void codec_h264(const H264_CONTEXT_WEBCODECS* sys, char* codec, size_t size)
267{
268 (void)_snprintf(codec, size, "avc1.42e01f");
269 if ((sys->paramsSize > 7) && ((sys->params[4] & 0x1F) == H264_NAL_SPS))
270 (void)_snprintf(codec, size, "avc1.%02x%02x%02x", sys->params[5], sys->params[6],
271 sys->params[7]);
272}
273
274/* copies up to max bytes of the RBSP: the payload without emulation prevention bytes */
275WINPR_ATTR_NODISCARD
276static size_t nal_rbsp(const BYTE* data, size_t length, BYTE* rbsp, size_t max)
277{
278 size_t count = 0;
279 size_t zeros = 0;
280 for (size_t x = 0; (x < length) && (count < max); x++)
281 {
282 if ((zeros >= 2) && (data[x] == 3))
283 {
284 zeros = 0;
285 continue;
286 }
287 zeros = (data[x] == 0) ? zeros + 1 : 0;
288 rbsp[count++] = data[x];
289 }
290 return count;
291}
292
293/* hvc1.[A-C]<profile_idc>.<compatibility flags, bit reversed>.<L|H><level_idc>[.<constraint
294 * flag bytes, trailing zeros omitted>] from the general profile_tier_level of the first SPS
295 * (ISO/IEC 14496-15 annex E) */
296static void codec_hevc(const H264_CONTEXT_WEBCODECS* sys, char* codec, size_t size)
297{
298 (void)_snprintf(codec, size, "hvc1.1.6.L93.B0"); /* Main profile, level 3.1 */
299
300 size_t offset = 0;
301 const BYTE* nal = nullptr;
302 size_t length = 0;
303 while (next_nal(sys->params, sys->paramsSize, &offset, &nal, &length))
304 {
305 if ((length < 2) || (nal_type(sys, nal) != HEVC_NAL_SPS))
306 continue;
307
308 /* after the 2 byte NAL header: sps_video_parameter_set_id, sps_max_sub_layers_minus1
309 * and sps_temporal_id_nesting_flag (1 byte), then profile space, tier and profile_idc
310 * (1), compatibility flags (4), constraint flags (6) and level_idc (1) */
311 BYTE ptl[13] = WINPR_C_ARRAY_INIT;
312 if (nal_rbsp(&nal[2], length - 2, ptl, sizeof(ptl)) < sizeof(ptl))
313 return;
314
315 const char* spaces[] = { "", "A", "B", "C" };
316 const UINT32 flags = ((UINT32)ptl[2] << 24) | ((UINT32)ptl[3] << 16) |
317 ((UINT32)ptl[4] << 8) | (UINT32)ptl[5];
318 UINT32 reversed = 0;
319 for (size_t x = 0; x < 32; x++)
320 reversed |= ((flags >> x) & 1u) << (31 - x);
321
322 char buffer[64] = WINPR_C_ARRAY_INIT;
323 int len = _snprintf(buffer, sizeof(buffer), "hvc1.%s%u.%" PRIX32 ".%c%u",
324 spaces[ptl[1] >> 6], (unsigned)(ptl[1] & 0x1F), reversed,
325 (ptl[1] & 0x20) ? 'H' : 'L', (unsigned)ptl[12]);
326 size_t constraints = 6;
327 while ((constraints > 0) && (ptl[5 + constraints] == 0))
328 constraints--;
329 for (size_t x = 0; (x < constraints) && (len > 0) && ((size_t)len < sizeof(buffer)); x++)
330 len += _snprintf(&buffer[len], sizeof(buffer) - (size_t)len, ".%02X",
331 (unsigned)ptl[6 + x]);
332 if ((len > 0) && ((size_t)len < size))
333 (void)_snprintf(codec, size, "%s", buffer);
334 return;
335 }
336}
337
338WINPR_ATTR_NODISCARD
339static BOOL ensure_planes(H264_CONTEXT_WEBCODECS* sys, UINT32 width, UINT32 height)
340{
341 if (sys->yuv && (width <= sys->width) && (height <= sys->height))
342 return TRUE;
343 width = MAX(width, sys->width);
344 height = MAX(height, sys->height);
345 if ((width == 0) || (height == 0) || (width > 16384) || (height > 16384))
346 return FALSE;
347
348 /* same padding as the encoder planes in h264.c; relaxes bounds checks in the converters.
349 * The chroma planes have full resolution for 4:4:4 pictures, 4:2:0 ones use part of them. */
350 const UINT32 ystride = width + 32 - width % 16;
351 const UINT32 cstride = ystride;
352 const size_t lines = height + 32 - height % 16;
353 const size_t ysize = (size_t)ystride * lines;
354 const size_t csize = ysize;
355 BYTE* yuv = winpr_aligned_calloc(ysize + 2 * csize, 1, 16);
356 if (!yuv)
357 return FALSE;
358 winpr_aligned_free(sys->yuv);
359 sys->yuv = yuv;
360 sys->width = width;
361 sys->height = height;
362 sys->stride[0] = ystride;
363 sys->stride[1] = cstride;
364 sys->stride[2] = cstride;
365 /* h264_wc_js_copy expects the planes in this order, in one buffer */
366 sys->plane[0] = yuv;
367 sys->plane[1] = &yuv[ysize];
368 sys->plane[2] = &yuv[ysize + csize];
369 return TRUE;
370}
371
372WINPR_ATTR_NODISCARD
373static int webcodecs_decompress(H264_CONTEXT* WINPR_RESTRICT h264,
374 const BYTE* WINPR_RESTRICT pSrcData, UINT32 SrcSize)
375{
376 WINPR_ASSERT(h264);
377 WINPR_ASSERT(pSrcData || (SrcSize == 0));
378
379 H264_CONTEXT_WEBCODECS* sys = h264->pSystemData;
380 WINPR_ASSERT(sys);
381
382 if (emscripten_is_main_browser_thread())
383 return -1; /* the main thread cannot block for its own asynchronous decode */
384
385 BOOL hasSlice = FALSE;
386 BOOL hasIdr = FALSE;
387 BOOL hasSps = FALSE;
388 BOOL hasPps = FALSE;
389 size_t offset = 0;
390 const BYTE* nal = nullptr;
391 size_t length = 0;
392 while (next_nal(pSrcData, SrcSize, &offset, &nal, &length))
393 {
394 if (length == 0)
395 continue;
396 const BYTE type = nal_type(sys, nal);
397 hasSlice |= nal_is_slice(sys, type);
398 hasIdr |= nal_is_key(sys, type);
399 hasSps |= nal_is_sps(sys, type);
400 hasPps |= nal_is_parameter_set(sys, type);
401 }
402 if ((hasSps || hasPps) && !save_parameters(sys, pSrcData, SrcSize, hasSps))
403 return -1;
404 if (!hasSlice)
405 return 0; /* parameter sets only, no picture */
406
407 char codec[64] = WINPR_C_ARRAY_INIT;
408 if (sys->hevc)
409 codec_hevc(sys, codec, sizeof(codec));
410 else
411 codec_h264(sys, codec, sizeof(codec));
412
413 /* a key picture without in-band parameter sets gets the saved ones */
414 const BYTE* src = pSrcData;
415 UINT32 size = SrcSize;
416 BYTE* combined = nullptr;
417 if (hasIdr && !hasSps && (sys->paramsSize > 0))
418 {
419 if (sys->paramsSize > UINT32_MAX - SrcSize)
420 return -1;
421 size = (UINT32)sys->paramsSize + SrcSize;
422 combined = malloc(size);
423 if (!combined)
424 return -1;
425 memcpy(combined, sys->params, sys->paramsSize);
426 memcpy(&combined[sys->paramsSize], pSrcData, SrcSize);
427 src = combined;
428 }
429
430 int rc = -1;
431 h264_wc_job job = { .handle = sys->handle,
432 .src = src,
433 .size = size,
434 .key = hasIdr,
435 .codec = codec,
436 .plane = sys->plane,
437 .stride = sys->stride,
438 .gbr = sys->hevc444,
439 .rc = -1 };
440 if (!ensure_planes(sys, MAX(h264->width, 16), MAX(h264->height, 16)))
441 goto fail;
442 job.maxWidth = sys->width;
443 job.maxHeight = sys->height;
444 if (!on_main(main_decode, &job))
445 goto fail;
446 if (job.rc == H264_WC_NEEDS_BUFFER)
447 {
448 job.rc = -1;
449 if (!ensure_planes(sys, job.dim[0], job.dim[1]) || !on_main(main_copy, &job))
450 goto fail;
451 }
452 rc = job.rc;
453 if (rc < 0)
454 WLog_Print(h264->log, WLOG_WARN, "WebCodecs %s decode failed (%d)",
455 sys->hevc ? "HEVC" : "H.264", rc);
456 if ((rc != 1) && (rc != H264_WC_YUV444))
457 goto fail;
458 h264->yuv444 = (rc == H264_WC_YUV444);
459 rc = 1;
460
461 for (size_t x = 0; x < 3; x++)
462 {
463 h264->pYUVData[x] = sys->plane[x];
464 h264->iStride[x] = sys->stride[x];
465 }
466 h264->YUVWidth = job.dim[0];
467 h264->YUVHeight = job.dim[1];
468fail:
469 free(combined);
470 return rc;
471}
472
473static void webcodecs_uninit(H264_CONTEXT* h264)
474{
475 WINPR_ASSERT(h264);
476
477 H264_CONTEXT_WEBCODECS* sys = h264->pSystemData;
478 if (!sys)
479 return;
480 if ((sys->handle > 0) && !emscripten_is_main_browser_thread())
481 (void)emscripten_proxy_sync(emscripten_proxy_get_system_queue(),
482 emscripten_main_runtime_thread_id(), main_close, &sys->handle);
483 else if (sys->handle > 0)
484 main_close(&sys->handle);
485 for (size_t x = 0; x < 3; x++)
486 h264->pYUVData[x] = nullptr;
487 winpr_aligned_free(sys->yuv);
488 free(sys->params);
489 free(sys);
490 h264->pSystemData = nullptr;
491}
492
493WINPR_ATTR_NODISCARD
494static BOOL webcodecs_init(H264_CONTEXT* h264)
495{
496 WINPR_ASSERT(h264);
497
498 /* decoder only; the main thread cannot wait for the asynchronous VideoDecoder */
499 if (h264->Compressor || emscripten_is_main_browser_thread())
500 return FALSE;
501
502 H264_CONTEXT_WEBCODECS* sys = calloc(1, sizeof(*sys));
503 if (!sys)
504 return FALSE;
505 sys->hevc = h264->hevc;
506 sys->hevc444 = h264->hevc && h264->hevc444;
507
508 /* H.264 Constrained Baseline 3.1 / HEVC Main 3.1: every decoder of the codec handles them.
509 * HEVC 4:4:4 needs a Main 4:4:4 (Range Extensions) decoder, which most browsers only have
510 * with a GPU that decodes it. */
511 const char* probe = "avc1.42e01f";
512 if (sys->hevc)
513 probe = sys->hevc444 ? "hvc1.4.10.L120.9E.08" : "hvc1.1.6.L93.B0";
514 h264_wc_open open = { .handle = 0, .probe = probe };
515 if (!on_main(main_open, &open) || (open.handle <= 0))
516 {
517 WLog_Print(h264->log, WLOG_DEBUG, "the browser cannot decode %s with WebCodecs",
518 sys->hevc ? (sys->hevc444 ? "HEVC 4:4:4" : "HEVC") : "H.264");
519 free(sys);
520 return FALSE;
521 }
522 sys->handle = open.handle;
523 h264->pSystemData = sys;
524 return TRUE;
525}
526
527const H264_CONTEXT_SUBSYSTEM g_Subsystem_WebCodecs = { "WebCodecs", webcodecs_init,
528 webcodecs_uninit, webcodecs_decompress,
529 nullptr };