@yume-chan/scrcpy 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CHANGELOG.json +43 -0
  2. package/CHANGELOG.md +21 -0
  3. package/LICENSE +21 -0
  4. package/README.md +88 -0
  5. package/bin/scrcpy-server +0 -0
  6. package/bin/version.d.ts +1 -0
  7. package/bin/version.js +1 -0
  8. package/esm/client.d.ts +36 -0
  9. package/esm/client.d.ts.map +1 -0
  10. package/esm/client.js +209 -0
  11. package/esm/client.js.map +1 -0
  12. package/esm/codec.d.ts +34 -0
  13. package/esm/codec.d.ts.map +1 -0
  14. package/esm/codec.js +37 -0
  15. package/esm/codec.js.map +1 -0
  16. package/esm/connection.d.ts +37 -0
  17. package/esm/connection.d.ts.map +1 -0
  18. package/esm/connection.js +103 -0
  19. package/esm/connection.js.map +1 -0
  20. package/esm/decoder/index.d.ts +4 -0
  21. package/esm/decoder/index.d.ts.map +1 -0
  22. package/esm/decoder/index.js +4 -0
  23. package/esm/decoder/index.js.map +1 -0
  24. package/esm/decoder/tinyh264/index.d.ts +20 -0
  25. package/esm/decoder/tinyh264/index.d.ts.map +1 -0
  26. package/esm/decoder/tinyh264/index.js +86 -0
  27. package/esm/decoder/tinyh264/index.js.map +1 -0
  28. package/esm/decoder/tinyh264/worker.d.ts +2 -0
  29. package/esm/decoder/tinyh264/worker.d.ts.map +1 -0
  30. package/esm/decoder/tinyh264/worker.js +3 -0
  31. package/esm/decoder/tinyh264/worker.js.map +1 -0
  32. package/esm/decoder/tinyh264/wrapper.d.ts +21 -0
  33. package/esm/decoder/tinyh264/wrapper.d.ts.map +1 -0
  34. package/esm/decoder/tinyh264/wrapper.js +67 -0
  35. package/esm/decoder/tinyh264/wrapper.js.map +1 -0
  36. package/esm/decoder/types.d.ts +28 -0
  37. package/esm/decoder/types.d.ts.map +1 -0
  38. package/esm/decoder/types.js +2 -0
  39. package/esm/decoder/types.js.map +1 -0
  40. package/esm/decoder/web-codecs/index.d.ts +22 -0
  41. package/esm/decoder/web-codecs/index.d.ts.map +1 -0
  42. package/esm/decoder/web-codecs/index.js +75 -0
  43. package/esm/decoder/web-codecs/index.js.map +1 -0
  44. package/esm/index.d.ts +9 -0
  45. package/esm/index.d.ts.map +1 -0
  46. package/esm/index.js +9 -0
  47. package/esm/index.js.map +1 -0
  48. package/esm/message.d.ts +93 -0
  49. package/esm/message.d.ts.map +1 -0
  50. package/esm/message.js +92 -0
  51. package/esm/message.js.map +1 -0
  52. package/esm/options/1_16/index.d.ts +107 -0
  53. package/esm/options/1_16/index.d.ts.map +1 -0
  54. package/esm/options/1_16/index.js +211 -0
  55. package/esm/options/1_16/index.js.map +1 -0
  56. package/esm/options/1_16/sps.d.ts +22 -0
  57. package/esm/options/1_16/sps.d.ts.map +1 -0
  58. package/esm/options/1_16/sps.js +254 -0
  59. package/esm/options/1_16/sps.js.map +1 -0
  60. package/esm/options/1_18.d.ts +19 -0
  61. package/esm/options/1_18.d.ts.map +1 -0
  62. package/esm/options/1_18.js +23 -0
  63. package/esm/options/1_18.js.map +1 -0
  64. package/esm/options/1_21.d.ts +10 -0
  65. package/esm/options/1_21.d.ts.map +1 -0
  66. package/esm/options/1_21.js +23 -0
  67. package/esm/options/1_21.js.map +1 -0
  68. package/esm/options/1_22.d.ts +43 -0
  69. package/esm/options/1_22.d.ts.map +1 -0
  70. package/esm/options/1_22.js +40 -0
  71. package/esm/options/1_22.js.map +1 -0
  72. package/esm/options/common.d.ts +30 -0
  73. package/esm/options/common.d.ts.map +1 -0
  74. package/esm/options/common.js +16 -0
  75. package/esm/options/common.js.map +1 -0
  76. package/esm/options/index.d.ts +6 -0
  77. package/esm/options/index.d.ts.map +1 -0
  78. package/esm/options/index.js +6 -0
  79. package/esm/options/index.js.map +1 -0
  80. package/esm/push-server.d.ts +6 -0
  81. package/esm/push-server.d.ts.map +1 -0
  82. package/esm/push-server.js +23 -0
  83. package/esm/push-server.js.map +1 -0
  84. package/esm/utils.d.ts +4 -0
  85. package/esm/utils.d.ts.map +1 -0
  86. package/esm/utils.js +14 -0
  87. package/esm/utils.js.map +1 -0
  88. package/package.json +61 -0
  89. package/scrcpy.LICENSE +203 -0
  90. package/scripts/fetch-server.cjs +28 -0
  91. package/src/client.ts +275 -0
  92. package/src/codec.ts +35 -0
  93. package/src/connection.ts +123 -0
  94. package/src/decoder/index.ts +3 -0
  95. package/src/decoder/tinyh264/index.ts +112 -0
  96. package/src/decoder/tinyh264/types.d.ts +137 -0
  97. package/src/decoder/tinyh264/worker.ts +2 -0
  98. package/src/decoder/tinyh264/wrapper.ts +89 -0
  99. package/src/decoder/types.ts +35 -0
  100. package/src/decoder/web-codecs/index.ts +98 -0
  101. package/src/index.ts +8 -0
  102. package/src/message.ts +105 -0
  103. package/src/options/1_16/index.ts +322 -0
  104. package/src/options/1_16/sps.ts +300 -0
  105. package/src/options/1_18.ts +41 -0
  106. package/src/options/1_21.ts +34 -0
  107. package/src/options/1_22.ts +80 -0
  108. package/src/options/common.ts +61 -0
  109. package/src/options/index.ts +5 -0
  110. package/src/push-server.ts +26 -0
  111. package/src/utils.ts +16 -0
@@ -0,0 +1,123 @@
1
+ import { Adb, AdbBufferedStream, AdbSocket } from "@yume-chan/adb";
2
+ import type { Disposable } from "@yume-chan/event";
3
+ import type { ValueOrPromise } from "@yume-chan/struct";
4
+ import { delay } from "./utils.js";
5
+
6
+ export interface ScrcpyClientConnectionOptions {
7
+ control: boolean;
8
+
9
+ /**
10
+ * Write a byte on start to detect connection issues
11
+ */
12
+ sendDummyByte: boolean;
13
+
14
+ /**
15
+ * Send device name and size
16
+ */
17
+ sendDeviceMeta: boolean;
18
+ }
19
+
20
+ export abstract class ScrcpyClientConnection implements Disposable {
21
+ protected device: Adb;
22
+
23
+ protected options: ScrcpyClientConnectionOptions;
24
+
25
+ public constructor(device: Adb, options: ScrcpyClientConnectionOptions) {
26
+ this.device = device;
27
+ this.options = options;
28
+ }
29
+
30
+ public initialize(): ValueOrPromise<void> { }
31
+
32
+ public abstract getStreams(): ValueOrPromise<[videoSteam: AdbBufferedStream, controlStream: AdbSocket | undefined]>;
33
+
34
+ public dispose(): void { }
35
+ }
36
+
37
+ export class ScrcpyClientForwardConnection extends ScrcpyClientConnection {
38
+ private async connect(): Promise<AdbSocket> {
39
+ return await this.device.createSocket('localabstract:scrcpy');
40
+ }
41
+
42
+ private async connectAndRetry(): Promise<AdbSocket> {
43
+ for (let i = 0; i < 100; i++) {
44
+ try {
45
+ return await this.connect();
46
+ } catch (e) {
47
+ await delay(100);
48
+ }
49
+ }
50
+ throw new Error(`Can't connect to server after 100 retries`);
51
+ }
52
+
53
+ private async connectVideoStream(): Promise<AdbBufferedStream> {
54
+ const socket = await this.connectAndRetry();
55
+ const stream = new AdbBufferedStream(socket);
56
+ if (this.options.sendDummyByte) {
57
+ // server will write a `0` to signal connection success
58
+ await stream.read(1);
59
+ }
60
+ return stream;
61
+ }
62
+
63
+ public async getStreams(): Promise<[videoSteam: AdbBufferedStream, controlStream: AdbSocket | undefined]> {
64
+ const videoStream = await this.connectVideoStream();
65
+ let controlStream: AdbSocket | undefined;
66
+ if (this.options.control) {
67
+ controlStream = await this.connectAndRetry();
68
+ }
69
+ if (this.options.sendDeviceMeta) {
70
+ // 64 bytes device name + 2 bytes video width + 2 bytes video height
71
+ await videoStream.read(64 + 2 + 2);
72
+ }
73
+ return [videoStream, controlStream];
74
+ }
75
+ }
76
+
77
+ export class ScrcpyClientReverseConnection extends ScrcpyClientConnection {
78
+ private streams!: ReadableStreamDefaultReader<AdbSocket>;
79
+
80
+ private address!: string;
81
+
82
+ public override async initialize(): Promise<void> {
83
+ try {
84
+ // try to unbind first
85
+ await this.device.reverse.remove('localabstract:scrcpy');
86
+ } catch {
87
+ // ignore error
88
+ }
89
+
90
+ const queue = new TransformStream<AdbSocket>();
91
+ this.streams = queue.readable.getReader();
92
+ const writer = queue.writable.getWriter();
93
+ this.address = await this.device.reverse.add('localabstract:scrcpy', 27183, {
94
+ onSocket: (packet, stream) => {
95
+ writer.write(stream);
96
+ },
97
+ });
98
+ }
99
+
100
+ private async accept(): Promise<AdbSocket> {
101
+ return (await this.streams.read()).value!;
102
+ }
103
+
104
+ public async getStreams(): Promise<[videoSteam: AdbBufferedStream, controlStream: AdbSocket | undefined]> {
105
+ const videoStream = new AdbBufferedStream(await this.accept());
106
+ let controlStream: AdbSocket | undefined;
107
+ if (this.options.control) {
108
+ controlStream = await this.accept();
109
+ }
110
+ if (this.options.sendDeviceMeta) {
111
+ // 64 bytes device name + 2 bytes video width + 2 bytes video height
112
+ await videoStream.read(64 + 2 + 2);
113
+ }
114
+ return [videoStream, controlStream];
115
+ }
116
+
117
+ public override dispose() {
118
+ // Don't await this!
119
+ // `reverse.remove`'s response will never arrive
120
+ // before we read all pending data from `videoStream`
121
+ this.device.reverse.remove(this.address);
122
+ }
123
+ }
@@ -0,0 +1,3 @@
1
+ export * from './types.js';
2
+ export * from './tinyh264/index.js';
3
+ export * from './web-codecs/index.js';
@@ -0,0 +1,112 @@
1
+ import { WritableStream } from "@yume-chan/adb";
2
+ import { PromiseResolver } from "@yume-chan/async";
3
+ import { AndroidCodecLevel, AndroidCodecProfile } from "../../codec.js";
4
+ import type { VideoStreamPacket } from "../../options/index.js";
5
+ import type { H264Configuration, H264Decoder } from "../types.js";
6
+ import { createTinyH264Wrapper, type TinyH264Wrapper } from "./wrapper.js";
7
+
8
+ let cachedInitializePromise: Promise<{ YuvBuffer: typeof import('yuv-buffer'), YuvCanvas: typeof import('yuv-canvas').default; }> | undefined;
9
+ function initialize() {
10
+ if (!cachedInitializePromise) {
11
+ cachedInitializePromise = Promise.all(
12
+ [import('yuv-buffer'), import('yuv-canvas')]
13
+ ).then(([YuvBuffer, { default: YuvCanvas }]) => ({
14
+ YuvBuffer, YuvCanvas
15
+ }));
16
+ }
17
+
18
+ return cachedInitializePromise;
19
+ }
20
+
21
+ export class TinyH264Decoder implements H264Decoder {
22
+ public readonly maxProfile = AndroidCodecProfile.Baseline;
23
+
24
+ public readonly maxLevel = AndroidCodecLevel.Level4;
25
+
26
+ private _renderer: HTMLCanvasElement;
27
+ public get renderer() { return this._renderer; }
28
+
29
+ private _frameRendered = 0;
30
+ public get frameRendered() { return this._frameRendered; }
31
+
32
+ private _writable: WritableStream<VideoStreamPacket>;
33
+ public get writable() { return this._writable; }
34
+
35
+ private _yuvCanvas: import('yuv-canvas').default | undefined;
36
+ private _initializer: PromiseResolver<TinyH264Wrapper> | undefined;
37
+
38
+ public constructor() {
39
+ initialize();
40
+
41
+ this._renderer = document.createElement('canvas');
42
+
43
+ this._writable = new WritableStream<VideoStreamPacket>({
44
+ write: async (packet) => {
45
+ switch (packet.type) {
46
+ case 'configuration':
47
+ this.configure(packet.data);
48
+ break;
49
+ case 'frame':
50
+ if (!this._initializer) {
51
+ throw new Error('Decoder not initialized');
52
+ }
53
+
54
+ const wrapper = await this._initializer.promise;
55
+ wrapper.feed(packet.data.slice().buffer);
56
+ break;
57
+ }
58
+ }
59
+ });
60
+ }
61
+
62
+ private async configure(config: H264Configuration) {
63
+ this.dispose();
64
+
65
+ this._initializer = new PromiseResolver<TinyH264Wrapper>();
66
+ const { YuvBuffer, YuvCanvas } = await initialize();
67
+
68
+ if (!this._yuvCanvas) {
69
+ this._yuvCanvas = YuvCanvas.attach(this._renderer);;
70
+ }
71
+
72
+ const { encodedWidth, encodedHeight } = config;
73
+ const chromaWidth = encodedWidth / 2;
74
+ const chromaHeight = encodedHeight / 2;
75
+
76
+ this._renderer.width = config.croppedWidth;
77
+ this._renderer.height = config.croppedHeight;
78
+ const format = YuvBuffer.format({
79
+ width: encodedWidth,
80
+ height: encodedHeight,
81
+ chromaWidth,
82
+ chromaHeight,
83
+ cropLeft: config.cropLeft,
84
+ cropTop: config.cropTop,
85
+ cropWidth: config.croppedWidth,
86
+ cropHeight: config.croppedHeight,
87
+ displayWidth: config.croppedWidth,
88
+ displayHeight: config.croppedHeight,
89
+ });
90
+
91
+ const wrapper = await createTinyH264Wrapper();
92
+ this._initializer.resolve(wrapper);
93
+
94
+ const uPlaneOffset = encodedWidth * encodedHeight;
95
+ const vPlaneOffset = uPlaneOffset + chromaWidth * chromaHeight;
96
+ wrapper.onPictureReady(({ data }) => {
97
+ this._frameRendered += 1;
98
+ const array = new Uint8Array(data);
99
+ const frame = YuvBuffer.frame(format,
100
+ YuvBuffer.lumaPlane(format, array, encodedWidth, 0),
101
+ YuvBuffer.chromaPlane(format, array, chromaWidth, uPlaneOffset),
102
+ YuvBuffer.chromaPlane(format, array, chromaWidth, vPlaneOffset)
103
+ );
104
+ this._yuvCanvas!.drawFrame(frame);
105
+ });
106
+ }
107
+
108
+ public dispose(): void {
109
+ this._initializer?.promise.then(wrapper => wrapper.dispose());
110
+ this._initializer = undefined;
111
+ }
112
+ }
@@ -0,0 +1,137 @@
1
+ declare module 'tinyh264' {
2
+ export function init(): void;
3
+ }
4
+
5
+ declare module 'yuv-buffer' {
6
+ /**
7
+ * Validate and fill out a YUVFormat object structure.
8
+ *
9
+ * At least width and height fields are required; other fields will be
10
+ * derived if left missing or empty:
11
+ * - chromaWidth and chromaHeight will be copied from width and height as for a 4:4:4 layout
12
+ * - cropLeft and cropTop will be 0
13
+ * - cropWidth and cropHeight will be set to whatever of the frame is visible after cropTop and cropLeft are applied
14
+ * - displayWidth and displayHeight will be set to cropWidth and cropHeight.
15
+ *
16
+ * @param {YUVFormat} fields - input fields, must include width and height.
17
+ * @returns {YUVFormat} - validated structure, with all derivable fields filled out.
18
+ * @throws exception on invalid fields or missing width/height
19
+ */
20
+ export function format(fields: YUVFormat): YUVFormat;
21
+
22
+ /**
23
+ * Allocate a new YUVPlane object big enough for a luma plane in the given format
24
+ * @param {YUVFormat} format - target frame format
25
+ * @param {Uint8Array} source - input byte array; optional (will create empty buffer if missing)
26
+ * @param {number} stride - row length in bytes; optional (will create a default if missing)
27
+ * @param {number} offset - offset into source array to extract; optional (will start at 0 if missing)
28
+ * @returns {YUVPlane} - freshly allocated planar buffer
29
+ */
30
+ export function lumaPlane(format: YUVFormat, source: Uint8Array, stride: number, offset: number): YUVPlane;
31
+
32
+ /**
33
+ * Allocate a new YUVPlane object big enough for a chroma plane in the given format,
34
+ * optionally copying data from an existing buffer.
35
+ *
36
+ * @param {YUVFormat} format - target frame format
37
+ * @param {Uint8Array} source - input byte array; optional (will create empty buffer if missing)
38
+ * @param {number} stride - row length in bytes; optional (will create a default if missing)
39
+ * @param {number} offset - offset into source array to extract; optional (will start at 0 if missing)
40
+ * @returns {YUVPlane} - freshly allocated planar buffer
41
+ */
42
+ export function chromaPlane(format: YUVFormat, source: Uint8Array, stride: number, offset: number): YUVPlane;
43
+
44
+ /**
45
+ * Allocate a new YUVFrame object big enough for the given format
46
+ * @param {YUVFormat} format - target frame format
47
+ * @param {YUVPlane} y - optional Y plane; if missing, fresh one will be allocated
48
+ * @param {YUVPlane} u - optional U plane; if missing, fresh one will be allocated
49
+ * @param {YUVPlane} v - optional V plane; if missing, fresh one will be allocated
50
+ * @returns {YUVFrame} - freshly allocated frame buffer
51
+ */
52
+ export function frame(format: YUVFormat, y: YUVPlane, u: YUVPlane, v: YUVPlane): YUVFrame;
53
+
54
+ /**
55
+ * Duplicate a frame using new buffer memory.
56
+ * @param {YUVFrame} frame - input frame to copyFrame
57
+ * @returns {YUVFrame} - freshly allocated and filled frame buffer
58
+ */
59
+ export function copyFrame(frame: YUVFrame): YUVFrame;
60
+
61
+ /**
62
+ * List the backing buffers for the frame's planes for transfer between
63
+ * threads via Worker.postMessage.
64
+ * @param {YUVFrame} frame - input frame
65
+ * @returns {Array} - list of transferable objects
66
+ */
67
+ export function transferables(frame: YUVFrame): (ArrayBuffer | SharedArrayBuffer)[];
68
+
69
+
70
+ /**
71
+ * Represents metadata about a YUV frame format.
72
+ * @typedef {Object} YUVFormat
73
+ * @property {number} width - width of encoded frame in luma pixels
74
+ * @property {number} height - height of encoded frame in luma pixels
75
+ * @property {number} chromaWidth - width of encoded frame in chroma pixels
76
+ * @property {number} chromaHeight - height of encoded frame in chroma pixels
77
+ * @property {number} cropLeft - upper-left X coordinate of visible crop region, in luma pixels
78
+ * @property {number} cropTop - upper-left Y coordinate of visible crop region, in luma pixels
79
+ * @property {number} cropWidth - width of visible crop region, in luma pixels
80
+ * @property {number} cropHeight - height of visible crop region, in luma pixels
81
+ * @property {number} displayWidth - final display width of visible region, in luma pixels
82
+ * @property {number} displayHeight - final display height of visible region, in luma pixels
83
+ */
84
+ export interface YUVFormat {
85
+ width: number;
86
+ height: number;
87
+ chromaWidth: number;
88
+ chromaHeight: number;
89
+ cropLeft: number;
90
+ cropTop: number;
91
+ cropWidth: number;
92
+ cropHeight: number;
93
+ displayWidth: number;
94
+ displayHeight: number;
95
+ }
96
+
97
+ /**
98
+ * Represents underlying image data for a single luma or chroma plane.
99
+ * Cannot be interpreted without the format data from a frame buffer.
100
+ * @typedef {Object} YUVPlane
101
+ * @property {Uint8Array} bytes - typed array containing image data bytes
102
+ * @property {number} stride - byte distance between rows in data
103
+ */
104
+ export interface YUVPlane {
105
+ bytes: Uint8Array;
106
+ stride: number;
107
+ }
108
+
109
+ /**
110
+ * Represents a YUV image frame buffer, with enough format information
111
+ * to interpret the data usefully. Buffer objects use generic objects
112
+ * under the hood and can be transferred between worker threads using
113
+ * the structured clone algorithm.
114
+ *
115
+ * @typedef {Object} YUVFrame
116
+ * @property {YUVFormat} format
117
+ * @property {YUVPlane} y
118
+ * @property {YUVPlane} u
119
+ * @property {YUVPlane} v
120
+ */
121
+ export interface YUVFrame {
122
+ format: YUVFormat;
123
+ y: YUVPlane;
124
+ u: YUVPlane;
125
+ v: YUVPlane;
126
+ }
127
+ }
128
+
129
+ declare module 'yuv-canvas' {
130
+ import { YUVFrame } from 'yuv-buffer';
131
+
132
+ export default class YUVCanvas {
133
+ public static attach(canvas: HTMLCanvasElement): YUVCanvas;
134
+
135
+ public drawFrame(data: YUVFrame): void;
136
+ }
137
+ }
@@ -0,0 +1,2 @@
1
+ import { init } from 'tinyh264';
2
+ init();
@@ -0,0 +1,89 @@
1
+ import { PromiseResolver } from '@yume-chan/async';
2
+ import { AutoDisposable, EventEmitter } from '@yume-chan/event';
3
+
4
+ let worker: Worker | undefined;
5
+ let workerReady = false;
6
+ const pendingResolvers: PromiseResolver<TinyH264Wrapper>[] = [];
7
+ let streamId = 0;
8
+
9
+ export interface PictureReadyEventArgs {
10
+ renderStateId: number;
11
+
12
+ width: number;
13
+
14
+ height: number;
15
+
16
+ data: ArrayBuffer;
17
+ }
18
+
19
+ const pictureReadyEvent = new EventEmitter<PictureReadyEventArgs>();
20
+
21
+ export class TinyH264Wrapper extends AutoDisposable {
22
+ public readonly streamId: number;
23
+
24
+ private readonly pictureReadyEvent = new EventEmitter<PictureReadyEventArgs>();
25
+ public get onPictureReady() { return this.pictureReadyEvent.event; }
26
+
27
+ public constructor(streamId: number) {
28
+ super();
29
+
30
+ this.streamId = streamId;
31
+ this.addDisposable(pictureReadyEvent.event(this.handlePictureReady, this));
32
+ }
33
+
34
+ private handlePictureReady(e: PictureReadyEventArgs) {
35
+ if (e.renderStateId === this.streamId) {
36
+ this.pictureReadyEvent.fire(e);
37
+ }
38
+ }
39
+
40
+ public feed(data: ArrayBuffer) {
41
+ worker!.postMessage({
42
+ type: 'decode',
43
+ data: data,
44
+ offset: 0,
45
+ length: data.byteLength,
46
+ renderStateId: this.streamId,
47
+ }, [data]);
48
+ }
49
+
50
+ public override dispose() {
51
+ super.dispose();
52
+ worker!.postMessage({
53
+ type: 'release',
54
+ renderStateId: this.streamId,
55
+ });
56
+ }
57
+ }
58
+
59
+ export function createTinyH264Wrapper(): Promise<TinyH264Wrapper> {
60
+ if (!worker) {
61
+ worker = new Worker(new URL('./worker.js', import.meta.url));
62
+ worker.addEventListener('message', (e) => {
63
+ const { data } = e;
64
+ switch (data.type) {
65
+ case 'decoderReady':
66
+ workerReady = true;
67
+ for (const resolver of pendingResolvers) {
68
+ resolver.resolve(new TinyH264Wrapper(streamId));
69
+ streamId += 1;
70
+ }
71
+ pendingResolvers.length = 0;
72
+ break;
73
+ case 'pictureReady':
74
+ pictureReadyEvent.fire(data);
75
+ break;
76
+ }
77
+ });
78
+ }
79
+
80
+ if (!workerReady) {
81
+ const resolver = new PromiseResolver<TinyH264Wrapper>();
82
+ pendingResolvers.push(resolver);
83
+ return resolver.promise;
84
+ }
85
+
86
+ const decoder = new TinyH264Wrapper(streamId);
87
+ streamId += 1;
88
+ return Promise.resolve(decoder);
89
+ }
@@ -0,0 +1,35 @@
1
+ import type { WritableStream } from '@yume-chan/adb';
2
+ import type { Disposable } from "@yume-chan/event";
3
+ import type { AndroidCodecLevel, AndroidCodecProfile } from "../codec.js";
4
+ import type { VideoStreamPacket } from "../options/index.js";
5
+
6
+ export interface H264Configuration {
7
+ profileIndex: number;
8
+ constraintSet: number;
9
+ levelIndex: number;
10
+
11
+ encodedWidth: number;
12
+ encodedHeight: number;
13
+
14
+ cropLeft: number;
15
+ cropRight: number;
16
+
17
+ cropTop: number;
18
+ cropBottom: number;
19
+
20
+ croppedWidth: number;
21
+ croppedHeight: number;
22
+ }
23
+
24
+ export interface H264Decoder extends Disposable {
25
+ readonly maxProfile: AndroidCodecProfile | undefined;
26
+ readonly maxLevel: AndroidCodecLevel | undefined;
27
+
28
+ readonly renderer: HTMLElement;
29
+ readonly frameRendered: number;
30
+ readonly writable: WritableStream<VideoStreamPacket>;
31
+ }
32
+
33
+ export interface H264DecoderConstructor {
34
+ new(): H264Decoder;
35
+ }
@@ -0,0 +1,98 @@
1
+ import { WritableStream } from '@yume-chan/adb';
2
+ import type { VideoStreamPacket } from "../../options/index.js";
3
+ import type { H264Configuration, H264Decoder } from "../types.js";
4
+
5
+ function toHex(value: number) {
6
+ return value.toString(16).padStart(2, '0').toUpperCase();
7
+ }
8
+
9
+ export class WebCodecsDecoder implements H264Decoder {
10
+ // Usually, browsers can decode most configurations,
11
+ // So let device choose best profile and level for itself.
12
+ public readonly maxProfile = undefined;
13
+ public readonly maxLevel = undefined;
14
+
15
+ private _writable: WritableStream<VideoStreamPacket>;
16
+ public get writable() { return this._writable; }
17
+
18
+ private _renderer: HTMLCanvasElement;
19
+ public get renderer() { return this._renderer; }
20
+
21
+ private _frameRendered = 0;
22
+ public get frameRendered() { return this._frameRendered; }
23
+
24
+ private context: CanvasRenderingContext2D;
25
+ private decoder: VideoDecoder;
26
+
27
+ // Limit FPS to system refresh rate
28
+ private lastFrame: VideoFrame | undefined;
29
+ private animationFrame: number = 0;
30
+
31
+ public constructor() {
32
+ this._renderer = document.createElement('canvas');
33
+
34
+ this.context = this._renderer.getContext('2d')!;
35
+ this.decoder = new VideoDecoder({
36
+ output: (frame) => {
37
+ if (this.lastFrame) {
38
+ this.lastFrame.close();
39
+ }
40
+ this.lastFrame = frame;
41
+
42
+ if (!this.animationFrame) {
43
+ // Start render loop on first frame
44
+ this.render();
45
+ }
46
+ },
47
+ error() { },
48
+ });
49
+
50
+ this._writable = new WritableStream<VideoStreamPacket>({
51
+ write: async (packet) => {
52
+ switch (packet.type) {
53
+ case 'configuration':
54
+ this.configure(packet.data);
55
+ break;
56
+ case 'frame':
57
+ this.decoder.decode(new EncodedVideoChunk({
58
+ type: 'key',
59
+ timestamp: 0,
60
+ data: packet.data,
61
+ }));
62
+ break;
63
+ }
64
+ }
65
+ });
66
+ }
67
+
68
+ private render = () => {
69
+ if (this.lastFrame) {
70
+ this._frameRendered += 1;
71
+ this.context.drawImage(this.lastFrame, 0, 0);
72
+ this.lastFrame.close();
73
+ this.lastFrame = undefined;
74
+ }
75
+
76
+ this.animationFrame = requestAnimationFrame(this.render);
77
+ };
78
+
79
+ private configure(config: H264Configuration) {
80
+ const { profileIndex, constraintSet, levelIndex } = config;
81
+
82
+ this._renderer.width = config.croppedWidth;
83
+ this._renderer.height = config.croppedHeight;
84
+
85
+ // https://www.rfc-editor.org/rfc/rfc6381#section-3.3
86
+ // ISO Base Media File Format Name Space
87
+ const codec = `avc1.${[profileIndex, constraintSet, levelIndex].map(toHex).join('')}`;
88
+ this.decoder.configure({
89
+ codec: codec,
90
+ optimizeForLatency: true,
91
+ });
92
+ }
93
+
94
+ public dispose() {
95
+ cancelAnimationFrame(this.animationFrame);
96
+ this.decoder.close();
97
+ }
98
+ }
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ export * from './client.js';
2
+ export * from './codec.js';
3
+ export * from './connection.js';
4
+ export * from './decoder/index.js';
5
+ export * from './message.js';
6
+ export * from './options/index.js';
7
+ export * from './push-server.js';
8
+ export * from './utils.js';