Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit 1419ac6

Browse files
committed
Hook up a clock and implement proper design
1 parent 449e028 commit 1419ac6

File tree

9 files changed

+222
-46
lines changed

9 files changed

+222
-46
lines changed

res/css/views/rooms/_VoiceRecordComposerTile.scss

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,43 @@ limitations under the License.
3434
background-color: $voice-record-stop-symbol-color;
3535
}
3636
}
37+
38+
.mx_VoiceRecordComposerTile_waveformContainer {
39+
padding: 5px;
40+
padding-right: 4px; // there's 1px from the waveform itself, so account for that
41+
padding-left: 15px; // +10px for the live circle, +5px for regular padding
42+
background-color: $voice-record-waveform-bg-color;
43+
border-radius: 12px;
44+
margin-right: 12px; // isolate from stop button
45+
46+
// Cheat at alignment a bit
47+
display: flex;
48+
align-items: center;
49+
50+
position: relative; // important for the live circle
51+
52+
color: $voice-record-waveform-fg-color;
53+
font-size: $font-14px;
54+
55+
&::before {
56+
// TODO: @@ TravisR: Animate
57+
content: '';
58+
background-color: $voice-record-live-circle-color;
59+
width: 10px;
60+
height: 10px;
61+
position: absolute;
62+
left: 8px;
63+
top: 16px; // vertically center
64+
border-radius: 10px;
65+
}
66+
67+
.mx_Waveform_bar {
68+
background-color: $voice-record-waveform-fg-color;
69+
}
70+
71+
.mx_Clock {
72+
padding-right: 8px; // isolate from waveform
73+
padding-left: 10px; // isolate from live circle
74+
width: 42px; // we're not using a monospace font, so fake it
75+
}
76+
}

res/css/views/voice_messages/_Waveform.scss

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,24 @@ limitations under the License.
1717
.mx_Waveform {
1818
position: relative;
1919
height: 30px; // tallest bar can only be 30px
20+
top: 1px; // because of our border trick (see below), we're off by 1px of aligntment
2021

2122
display: flex;
2223
align-items: center; // so the bars grow from the middle
2324

25+
overflow: hidden; // this is cheaper than a `max-height: calc(100% - 4px)` in the bar's CSS.
26+
27+
// A bar is meant to be a 2x2 circle when at zero height, and otherwise a 2px wide line
28+
// with rounded caps.
2429
.mx_Waveform_bar {
25-
width: 2px;
26-
margin-left: 1px;
30+
width: 0; // 0px width means we'll end up using the border as our width
31+
border: 1px solid transparent; // transparent means we'll use the background colour
32+
border-radius: 2px; // rounded end caps, based on the border
33+
min-height: 0; // like the width, we'll rely on the border to give us height
34+
max-height: 100%; // this makes the `height: 42%` work on the element
35+
margin-left: 1px; // we want 2px between each bar, so 1px on either side for balance
2736
margin-right: 1px;
28-
background-color: $muted-fg-color;
29-
display: inline-block;
30-
min-height: 2px;
31-
max-height: 100%;
32-
border-radius: 2px; // give them soft endcaps
37+
38+
// background color is handled by the parent components
3339
}
3440
}

res/themes/legacy-light/css/_legacy-light.scss

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,9 @@ $space-button-outline-color: #E3E8F0;
191191

192192
$voice-record-stop-border-color: #E3E8F0;
193193
$voice-record-stop-symbol-color: $warning-color;
194+
$voice-record-waveform-bg-color: #E3E8F0;
195+
$voice-record-waveform-fg-color: $muted-fg-color;
196+
$voice-record-live-circle-color: $warning-color;
194197

195198
$roomtile-preview-color: #9e9e9e;
196199
$roomtile-default-badge-bg-color: #61708b;

res/themes/light/css/_light.scss

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,9 @@ $space-button-outline-color: #E3E8F0;
182182

183183
$voice-record-stop-border-color: #E3E8F0;
184184
$voice-record-stop-symbol-color: $warning-color;
185+
$voice-record-waveform-bg-color: #E3E8F0;
186+
$voice-record-waveform-fg-color: $muted-fg-color;
187+
$voice-record-live-circle-color: $warning-color;
185188

186189
$roomtile-preview-color: $secondary-fg-color;
187190
$roomtile-default-badge-bg-color: #61708b;

src/components/views/rooms/VoiceRecordComposerTile.tsx

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ import {Room} from "matrix-js-sdk/src/models/room";
2222
import {MatrixClientPeg} from "../../../MatrixClientPeg";
2323
import classNames from "classnames";
2424
import LiveRecordingWaveform from "../voice_messages/LiveRecordingWaveform";
25+
import {replaceableComponent} from "../../../utils/replaceableComponent";
26+
import LiveRecordingClock from "../voice_messages/LiveRecordingClock";
2527

2628
interface IProps {
2729
room: Room;
@@ -32,6 +34,10 @@ interface IState {
3234
recorder?: VoiceRecorder;
3335
}
3436

37+
/**
38+
* Container tile for rendering the voice message recorder in the composer.
39+
*/
40+
@replaceableComponent("views.rooms.VoiceRecordComposerTile")
3541
export default class VoiceRecordComposerTile extends React.PureComponent<IProps, IState> {
3642
public constructor(props) {
3743
super(props);
@@ -61,23 +67,30 @@ export default class VoiceRecordComposerTile extends React.PureComponent<IProps,
6167
this.setState({recorder});
6268
};
6369

70+
private renderWaveformArea() {
71+
if (!this.state.recorder) return null;
72+
73+
return <div className='mx_VoiceRecordComposerTile_waveformContainer'>
74+
<LiveRecordingClock recorder={this.state.recorder} />
75+
<LiveRecordingWaveform recorder={this.state.recorder} />
76+
</div>;
77+
}
78+
6479
public render() {
6580
const classes = classNames({
6681
'mx_MessageComposer_button': !this.state.recorder,
6782
'mx_MessageComposer_voiceMessage': !this.state.recorder,
6883
'mx_VoiceRecordComposerTile_stop': !!this.state.recorder,
6984
});
7085

71-
let waveform = null;
7286
let tooltip = _t("Record a voice message");
7387
if (!!this.state.recorder) {
7488
// TODO: @@ TravisR: Change to match behaviour
7589
tooltip = _t("Stop & send recording");
76-
waveform = <LiveRecordingWaveform recorder={this.state.recorder} />;
7790
}
7891

7992
return (<>
80-
{waveform}
93+
{this.renderWaveformArea()}
8194
<AccessibleTooltipButton
8295
className={classes}
8396
onClick={this.onStartStopVoiceMessage}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
Copyright 2021 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import React from "react";
18+
import {replaceableComponent} from "../../../utils/replaceableComponent";
19+
20+
interface IProps {
21+
seconds: number;
22+
}
23+
24+
interface IState {
25+
}
26+
27+
/**
28+
* Simply converts seconds into minutes and seconds. Note that hours will not be
29+
* displayed, making it possible to see "82:29".
30+
*/
31+
@replaceableComponent("views.voice_messages.Clock")
32+
export default class Clock extends React.PureComponent<IProps, IState> {
33+
public constructor(props) {
34+
super(props);
35+
}
36+
37+
public render() {
38+
const minutes = Math.floor(this.props.seconds / 60).toFixed(0).padStart(2, '0');
39+
const seconds = Math.round(this.props.seconds % 60).toFixed(0).padStart(2, '0'); // hide millis
40+
return <span className='mx_Clock'>{minutes}:{seconds}</span>;
41+
}
42+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
Copyright 2021 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import React from "react";
18+
import {IRecordingUpdate, VoiceRecorder} from "../../../voice/VoiceRecorder";
19+
import {replaceableComponent} from "../../../utils/replaceableComponent";
20+
import Clock from "./Clock";
21+
22+
interface IProps {
23+
recorder: VoiceRecorder;
24+
}
25+
26+
interface IState {
27+
seconds: number;
28+
}
29+
30+
/**
31+
* A clock for a live recording.
32+
*/
33+
@replaceableComponent("views.voice_messages.LiveRecordingClock")
34+
export default class LiveRecordingClock extends React.PureComponent<IProps, IState> {
35+
public constructor(props) {
36+
super(props);
37+
38+
this.state = {seconds: 0};
39+
this.props.recorder.liveData.onUpdate(this.onRecordingUpdate);
40+
}
41+
42+
shouldComponentUpdate(nextProps: Readonly<IProps>, nextState: Readonly<IState>, nextContext: any): boolean {
43+
const currentFloor = Math.floor(this.state.seconds);
44+
const nextFloor = Math.floor(nextState.seconds);
45+
return currentFloor !== nextFloor;
46+
}
47+
48+
private onRecordingUpdate = (update: IRecordingUpdate) => {
49+
this.setState({seconds: update.timeSeconds});
50+
};
51+
52+
public render() {
53+
return <Clock seconds={this.state.seconds} />;
54+
}
55+
}

src/components/views/voice_messages/LiveRecordingWaveform.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,12 +49,12 @@ export default class LiveRecordingWaveform extends React.PureComponent<IProps, I
4949
const bars = arrayFastResample(Array.from(update.waveform), DOWNSAMPLE_TARGET);
5050
this.setState({
5151
// The incoming data is between zero and one, but typically even screaming into a
52-
// microphone won't send you over 0.6, so we "cap" the graph at about 0.4 for a
52+
// microphone won't send you over 0.6, so we "cap" the graph at about 0.35 for a
5353
// point where the average user can still see feedback and be perceived as peaking
5454
// when talking "loudly".
5555
//
5656
// We multiply by 100 because the Waveform component wants values in 0-100 (percentages)
57-
heights: bars.map(b => percentageOf(b, 0, 0.40) * 100),
57+
heights: bars.map(b => percentageOf(b, 0, 0.35) * 100),
5858
});
5959
};
6060

src/voice/VoiceRecorder.ts

Lines changed: 48 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,10 @@ import {SimpleObservable} from "matrix-widget-api";
2323
const CHANNELS = 1; // stereo isn't important
2424
const SAMPLE_RATE = 48000; // 48khz is what WebRTC uses. 12khz is where we lose quality.
2525
const BITRATE = 24000; // 24kbps is pretty high quality for our use case in opus.
26-
const FREQ_SAMPLE_RATE = 10; // Target rate of frequency data (samples / sec). We don't need this super often.
2726

2827
export interface IRecordingUpdate {
2928
waveform: number[]; // floating points between 0 (low) and 1 (high).
30-
31-
// TODO: @@ TravisR: Generalize this for a timing package?
29+
timeSeconds: number; // float
3230
}
3331

3432
export class VoiceRecorder {
@@ -37,11 +35,11 @@ export class VoiceRecorder {
3735
private recorderSource: MediaStreamAudioSourceNode;
3836
private recorderStream: MediaStream;
3937
private recorderFFT: AnalyserNode;
38+
private recorderProcessor: ScriptProcessorNode;
4039
private buffer = new Uint8Array(0);
4140
private mxc: string;
4241
private recording = false;
4342
private observable: SimpleObservable<IRecordingUpdate>;
44-
private freqTimerId: number;
4543

4644
public constructor(private client: MatrixClient) {
4745
}
@@ -71,7 +69,20 @@ export class VoiceRecorder {
7169
// it makes the time domain less than helpful.
7270
this.recorderFFT.fftSize = 64;
7371

72+
// We use an audio processor to get accurate timing information.
73+
// The size of the audio buffer largely decides how quickly we push timing/waveform data
74+
// out of this class. Smaller buffers mean we update more frequently as we can't hold as
75+
// many bytes. Larger buffers mean slower updates. For scale, 1024 gives us about 30Hz of
76+
// updates and 2048 gives us about 20Hz. We use 2048 because it updates frequently enough
77+
// to feel realtime (~20fps, which is what humans perceive as "realtime"). Must be a power
78+
// of 2.
79+
this.recorderProcessor = this.recorderContext.createScriptProcessor(2048, CHANNELS, CHANNELS);
80+
81+
// Connect our inputs and outputs
7482
this.recorderSource.connect(this.recorderFFT);
83+
this.recorderSource.connect(this.recorderProcessor);
84+
this.recorderProcessor.connect(this.recorderContext.destination);
85+
7586
this.recorder = new Recorder({
7687
encoderPath, // magic from webpack
7788
encoderSampleRate: SAMPLE_RATE,
@@ -117,6 +128,37 @@ export class VoiceRecorder {
117128
return this.mxc;
118129
}
119130

131+
private tryUpdateLiveData = (ev: AudioProcessingEvent) => {
132+
if (!this.recording) return;
133+
134+
// The time domain is the input to the FFT, which means we use an array of the same
135+
// size. The time domain is also known as the audio waveform. We're ignoring the
136+
// output of the FFT here (frequency data) because we're not interested in it.
137+
//
138+
// We use bytes out of the analyser because floats have weird precision problems
139+
// and are slightly more difficult to work with. The bytes are easy to work with,
140+
// which is why we pick them (they're also more precise, but we care less about that).
141+
const data = new Uint8Array(this.recorderFFT.fftSize);
142+
this.recorderFFT.getByteTimeDomainData(data);
143+
144+
// Because we're dealing with a uint array we need to do math a bit differently.
145+
// If we just `Array.from()` the uint array, we end up with 1s and 0s, which aren't
146+
// what we're after. Instead, we have to use a bit of manual looping to correctly end
147+
// up with the right values
148+
const translatedData: number[] = [];
149+
for (let i = 0; i < data.length; i++) {
150+
// All we're doing here is inverting the amplitude and putting the metric somewhere
151+
// between zero and one. Without the inversion, lower values are "louder", which is
152+
// not super helpful.
153+
translatedData.push(1 - (data[i] / 128.0));
154+
}
155+
156+
this.observable.update({
157+
waveform: translatedData,
158+
timeSeconds: ev.playbackTime,
159+
});
160+
};
161+
120162
public async start(): Promise<void> {
121163
if (this.mxc || this.hasRecording) {
122164
throw new Error("Recording already prepared");
@@ -129,35 +171,7 @@ export class VoiceRecorder {
129171
}
130172
this.observable = new SimpleObservable<IRecordingUpdate>();
131173
await this.makeRecorder();
132-
this.freqTimerId = setInterval(() => {
133-
if (!this.recording) return;
134-
135-
// The time domain is the input to the FFT, which means we use an array of the same
136-
// size. The time domain is also known as the audio waveform. We're ignoring the
137-
// output of the FFT here (frequency data) because we're not interested in it.
138-
//
139-
// We use bytes out of the analyser because floats have weird precision problems
140-
// and are slightly more difficult to work with. The bytes are easy to work with,
141-
// which is why we pick them (they're also more precise, but we care less about that).
142-
const data = new Uint8Array(this.recorderFFT.fftSize);
143-
this.recorderFFT.getByteTimeDomainData(data);
144-
145-
// Because we're dealing with a uint array we need to do math a bit differently.
146-
// If we just `Array.from()` the uint array, we end up with 1s and 0s, which aren't
147-
// what we're after. Instead, we have to use a bit of manual looping to correctly end
148-
// up with the right values
149-
const translatedData: number[] = [];
150-
for (let i = 0; i < data.length; i++) {
151-
// All we're doing here is inverting the amplitude and putting the metric somewhere
152-
// between zero and one. Without the inversion, lower values are "louder", which is
153-
// not super helpful.
154-
translatedData.push(1 - (data[i] / 128.0));
155-
}
156-
157-
this.observable.update({
158-
waveform: translatedData,
159-
});
160-
}, 1000 / FREQ_SAMPLE_RATE) as any as number; // XXX: Linter doesn't understand timer environment
174+
this.recorderProcessor.addEventListener("audioprocess", this.tryUpdateLiveData);
161175
await this.recorder.start();
162176
this.recording = true;
163177
}
@@ -179,8 +193,8 @@ export class VoiceRecorder {
179193
this.recorderStream.getTracks().forEach(t => t.stop());
180194

181195
// Finally do our post-processing and clean up
182-
clearInterval(this.freqTimerId);
183196
this.recording = false;
197+
this.recorderProcessor.removeEventListener("audioprocess", this.tryUpdateLiveData);
184198
await this.recorder.close();
185199

186200
return this.buffer;

0 commit comments

Comments
 (0)