Chapter 11. Media Components
The charts and galleries in the previous chapter deal with numbers already computed and images that already exist. This chapter switches to things the browser produces itself: a photo, a recording, a video, a 3D model.
These values differ from the earlier ones in one fundamental way: there is a file behind each of them. Where the file comes from, what the handler function receives, and what format it is written back as — every one of these has to be spelled out, and each has its own set of switches; mixing them up causes errors.
The example adds two blocks to the workbench. The image block holds two input images, an editor, and a composite image; the audio/video block holds a piece of audio, a video, and three models. The assets all ship with the example: an illustration, a marker image, a prompt tone a little over two seconds long, a three-second clip, and a sphere model.
11.1 Image Input Sources and Data Types
Two parameters in Image’s parameter list decide the whole contract; the rest only control appearance.
fromPath = gr.Image(
value: MediaBook.Photo,
sources: ["upload", "webcam", "clipboard"],
type: "filepath",
height: 260,
label: "Path image: three sources, the handler function receives a path");
fromBitmap = gr.Image(
value: MediaBook.Mark,
sources: ["upload"],
type: "numpy",
height: 260,
label: "Bitmap: upload only, the handler function receives pixels");
sources controls “where it comes from” and type controls “what gets passed”. Remembering these two statements separately is more useful than memorizing the parameter names. Figure 11-1 lays the two parameters out as two axes. The left column lists the three entry points of sources, the right column lists the two results of type, with the component in the middle.
Figure 11-1 The two parameters of Image: one controls where it comes from, one controls what gets passed
sources has three values. upload picks a file or lets you drag one in, webcam opens the camera to take a picture, and clipboard pastes from the clipboard. Leave it out and all three entry points are provided. Write only upload and the block is left with upload alone. In the example the “path image” carries three entry points, while the “bitmap” has only one.
type has three values, but in C# they come down to only two kinds of thing.
numpyandpil. The handler function receives aRasterImage, with width, height and RGBA pixels all in hand;filepath. The handler function receives a string, the path of that file in the cache directory.
You can compute the byte count of a bitmap yourself. Multiply width by height by four; the four channels are red, green, blue, and alpha. The example’s marker image is 200×200, so 200 × 200 × 4 = 160,000 bytes. It has nothing to do with file size. The same image saved as png is 1,011 bytes, yet the handler function receives 160,000 bytes. What the bitmap route buys you is “pixels already in memory”, and the price is size.
You write the handler function’s signature according to type.
string ReadImages(string? path, RasterImage? bitmap)
{
var fromPath = string.IsNullOrEmpty(path)
? "(empty)"
: $"{MediaBook.Describe(path)}\n\nLocation in the cache: `{path}`";
var fromBitmap = bitmap is null
? "(empty)"
: $"{bitmap.Width}×{bitmap.Height} · {bitmap.Pixels.Length} bytes";
return $"""
**Read images**
Path image: {fromPath}
Bitmap: {fromBitmap}
""";
}
Both parameters are nullable, because both images can be empty. Click “Clear images” and read again: both parameters are null, and the panel reads “(empty)”. The empty value is part of the contract. No image means no image, and the handler function has to decide on its own what to return in that case. The example’s choice is to write “(empty)” into the panel, so that emptiness is visible.
What you can give value is not limited to a path. An existing image (a RasterImage), a byte array, or a stream can all serve as the initial value; the example gives a path, because the assets are files that ship with the program, and passing one to the component as the initial value is the least work. After the component gets the path, it copies the file into the cache directory and sends the address of that cached copy to the front end. So the address shown in the UI is not the same as the path supplied by the business side.
Figure 11-2 shows what it looks like after you click “Read images”. The path image reports photo.png · 2217 bytes · .png, and the bitmap reports 200×200 · 160000 bytes.
Figure 11-2 Read images: the path image brings back a cache path, the bitmap brings back width, height, and byte count
You have to read these two numbers together. The illustration in the example is 480×320. As a file it is 2,217 bytes; as pixels it is 614,400 bytes. Click “Swap image” and the bitmap block switches to the illustration; read again and you get this number. 2,217 is the compressed file, 614,400 is the pixels of 480 × 320 × 4 bytes. The two measurements are two different things.
Under the right-hand image in Figure 11-2 there is only one line, “Drop an image file here to upload”; under the left-hand one there are three icons in a row. The difference is that sources is missing two values. Buttons follow the values: an entry point with no value does not appear.
Each of the three entry points maps to one browser capability. Upload is a file picker, the webcam needs user permission, and the clipboard needs the page to be granted paste permission. If permission is not granted, the entry point will not open; that is the browser enforcing the rules. When you write sources, narrow it to the situation at hand. A form that only allows upload but leaves the webcam and clipboard on as well is just giving the user two extra paths that will fail.
The entry points do not accept everything either. Push an audio file into the image block and the front end stops it on the spot, popping up Invalid file type: tone.wav. Only image/* allowed. in the top-right corner; the value in the block does not move. Figure 11-3 shows exactly that. The audio block behaves the same way. Feed it a text file and the message changes to “Only audio/* accepted”, followed by a long list of the types it recognizes.
Because it is stopped at the front end, the server never receives this upload at all, and the handler function knows nothing about it. This is the same type boundary discussed in Chapter 3. The error is in the type, the value does not change, and the UI states the reason. Skip this step and the consequences are reversed: the file lands in the cache, the handler function gets a path it cannot open, and it becomes unclear whose fault the error is.
Figure 11-3 Wrong type: the front end rejects it on the spot, the value in the block does not move
“Swap image” and “Clear images” follow the old route from Chapter 3. The handler function returns a new value, or returns null. The component changes along with it; events are not involved.
11.2 Image Format, Size, and Streaming
format defaults to webp. This parameter controls exactly one thing: which format to use when writing pixels to a file. The example’s composite-image block sets format: "png".
composite = gr.Image(type: "filepath", format: "png", height: 320, interactive: false,
label: "Composite image: written back as png");
When the value is an existing file path, format has no say. The composite image that the editor passes to the handler function is already png, so the component sends it to the front end unchanged and the file is still called composite.png. Only if you replace this block’s value with a bitmap (type: "numpy") will the component write a fresh file according to format, named image.png.
Keep these two things distinct. The incoming file lands in the cache as-is, byte for byte unchanged; only if what goes out is a pile of pixels does the component write a file for you, and that is when format has the final say.
The default webp is a sensible choice: small, with transparency, and recognized by every browser. If another program is going to use it next, png is safer. It is lossless, and there is no “how lossy should it be” parameter to tune. The example’s composite image writes png, because the next step may be to print it or edit it again; webp would look fine too, except that every save adds another layer of compression.
height and width are the dimensions of the block, in pixels. The example’s two input images set 260, the editor sets 320. They are not the pixel dimensions of the image. Put a 480×320 image into a block 260 high and the image is scaled down proportionally into the block, aspect ratio unchanged. Fix the block height while the image’s ratio does not match and you get either letterboxing or cropping — the same thing as objectFit in the Chapter 10 gallery.
Letterboxing or cropping: Image has no switch like objectFit; it works on a “fit it all in” basis. The whole image is shrunk into the block and the spare space is left blank. In the left-hand block of Figure 11-2 the image is a 480×320 landscape picture, the block is 260 high and nearly four hundred wide, so a white strip is left on each side. To make the image fill the block you have to set the block’s aspect ratio to the image’s ratio. The block is a container, not a picture frame.
On Image, interactive controls “whether you can put things into it”. The composite-image block sets interactive: false, so there is no upload entry point on the block, just an image. It is an output slot; nobody should be dragging files into it. The input block leaves it out, so by default things can be put in. An input component with no interactive counts as interactive — this is the Chapter 4 rule carried over to media components.
streaming is another switch, false by default. Set it to true and the default for sources changes: no longer three entry points, only the webcam remains. The webcam then sends frames to the server one by one, firing a stream event for each frame that arrives. The example does not enable it, because there is no webcam on this machine to shoot with; to try it, change one input image to streaming: true, swap the handler function for one that takes a RasterImage, and the UI shows a live feed.
The contract for this mode differs from the previous two. The stream event’s handler function is called once per frame, and the RasterImage is that single frame, not a whole video. In other words, the handler function paired with streaming input must return within one frame and can only do lightweight checks. Run heavy work on every frame and the UI grinds to a halt. None of the example’s handler functions that run once per button click are suitable for hanging off this.
Streaming input is not the same as the streaming output of Chapter 16. Here what streams is the input, and the handler function is called repeatedly; there what streams is the return value, and one call produces many outputs. The two share a word; do not mix them up.
streaming has one more side effect. Once it rewrites sources, the upload and clipboard entry points are gone. If you want both “take a picture” and “live view” at the same time, you have to place two components: one ordinary, one streaming, each handling one thing.
Figure 11-4 draws the two legs a media value travels on the server. The incoming leg is “move”: the bytes the browser uploads land in the cache directory as-is, with the file name and extension unchanged. The outgoing leg is “write”: if what the handler function returns is not yet a file, the component writes a fresh one according to format.
Figure 11-4 The two legs a media value travels: in is move, out is write
Both legs land in the same directory. When that directory is cleared and how large it can grow is what the file mechanism in Chapter 12 governs; this chapter only uses the layer where “a file sits behind the value”.
11.3 ImageEditor Transforms and Layers
ImageEditor is a heavier version of Image: on a background image you can draw with a brush, erase, crop, and add layers. Its value is three images.
editor = gr.ImageEditor(
value: MediaBook.Photo,
type: "filepath",
transforms: ["crop", "resize"],
height: 320,
label: "Editor: brush, eraser, layers");
The handler function receives an EditorValue, with three fields. Background is the base image, Layers are the layers drawn on top of it, ordered from bottom to top, and Composite is the one the user sees — the base image plus all the layers.
The types of these three fields follow type. The example’s editor sets type: "filepath", so all three are paths; leave out type and the default is numpy, so all three are RasterImage. One component passes three images to the handler function at once, and type governs all three at once.
transforms decides which transform tools appear in the toolbar. Write ["crop", "resize"], click the “Image” button on the toolbar, and what expands are the two items Crop and Resize; write only ["crop"] and the resize item does not appear. Leave it out and the default is still these two items. Cropping and resizing are the two things you do most often when editing an image.
Cropping is done by dragging a box; once the box is set, a “Confirm crop” button appears on the toolbar, and only clicking it actually cuts. Skip that click and the box stays but the image is unchanged. Both transforms modify the base image, and the modified base image is Background.
(string, object) ApplyEdit(EditorValue value)
{
var report = $"""
**Edit** layers {value.Layers.Count}
Background {Size(value.Background)} · Composite {Size(value.Composite)}
""";
return (report, value.Composite!);
}
Figure 11-5 shows the state after one stroke is drawn. The toolbar is a column on the left; from top to bottom it is Image (base image and transforms), Brush, Eraser, Color, Brush size, and the Layers toggle. The top three buttons are one group. Click “Image” to expand crop and resize, click Brush to enter drawing mode, click Eraser to enter erasing mode. Only one is active at a time, and the selected one gets a darker background.
The bar at the bottom reads “Layer 1”, the current layer. When you do not name one, the editor supplies a layer called Layer 1. There is another toggle on the right of the layer bar; click it to open the layer list. The example has only one layer: draw one stroke and Layers goes from 0 to 1. An empty layer does not count; only one with something drawn on it does.
The benefit of the layer design is that “you can undo a mistake”. Annotations go on a separate layer, the base image stays put, and erasing a layer returns things to the original. Layers is ordered bottom to top, with the first element the lowest layer; Composite is what those layers look like stacked in order, so reading it saves you from compositing them yourself.
Figure 11-5 One stroke in the editor: toolbar on the left, layer bar at the bottom
Brush and Eraser are each a set of options; leave them out and the defaults are used. Eraser has one default_size, Brush has five colors with red as the first. The example does not set them, so it uses the defaults and that stroke is red. layers can be turned off too. Write false and the layer button disappears, leaving only a base image.
After drawing, click “Apply edit”: the handler function gets the EditorValue, the panel reads “layers 1”, the background is background.png · 6927 bytes, and the composite is composite.png · 7980 bytes. The composite is a little larger than the background; the extra is that stroke.
Figure 11-6 Apply edit: the composite image lands on the right, the values report the layer count and two files
The “composite image” on the right is Composite. It is returned by the handler function and takes the ordinary output route. The first return value of ApplyEdit is written into the panel, the second into the image block. This step is the same as the multiple return values discussed in Chapter 3, except that here what is returned is an image.
You can keep using the edited result. Click “Back to editor”.
string BackToEditor(string composite) => composite;
The handler function writes the value of the composite-image block straight back into the editor, and the editor treats it as the new base image. That stroke turns from “a drawing on a layer” into “part of the base image”; keep drawing on top and you are drawing a second layer. This works because the editor is set to type: "filepath". The composite image is a path, and a path written back into the same component is recognized.
The chain goes like this. The editor produces an image, the image block catches it, then feeds the path back into the editor, so “the edited result” becomes “the starting point for the next round”. No state is needed in between, no extra storage either; the value just keeps passing between the two components. In a product this is the least-effort way to “keep editing on top of existing annotations”.
The editor also has a canvasSize, 800×800 by default, which is the pixel size of the canvas; fixedCanvas decides whether an uploaded image is shrunk onto the canvas or the canvas is stretched to the image’s size. The example leaves both alone. The base image is 480×320 and the canvas follows the image; a canvas larger than the image is no easier to use. You only need to hard-code these two when you want a fixed board for people to draw on (say, a signature pad of uniform size).
EditorValue is an output-only type. It has no public constructor; the handler function can read it but cannot construct one itself. To push a value back into the editor, you push an image or a path, not an EditorValue.
11.4 Audio Input Sources and Recording
Audio follows the same idea as Image. sources controls where it comes from, type controls what gets passed, and format controls what is written back.
var audio = gr.Audio(
value: MediaBook.Tone,
sources: (object)new[] { "upload", "microphone" },
type: "numpy",
format: "wav",
editable: true,
waveformOptions: new WaveformOptions
{
WaveformColor = "#1d4ed8",
SkipLength = 25,
},
label: "Audio: upload or record, waveform is draggable");
sources has two values, upload and microphone. Leave it out and both are provided; with streaming: true only the microphone remains, the same rule as for Image. The example provides both, so the block has two entry points underneath, one for upload and one for recording. Write only upload and the record button does not appear. As on the image side, entry points follow the values.
The values of type are numpy and filepath, and the values of format are wav, mp3, or empty. The three parameters have the same names as on Image, and their meanings are carried over too: one controls what gets passed, one controls the format written back. The differences are in the details, covered in the next section.
recording is another entry-point switch, false by default. Set it to true and the component opens the microphone as soon as it loads and sits in a ready-to-record state, so the user does not have to click an entry point first. That suits an interface that “opens as a voice recorder”; it does not suit a default page. A permission prompt the moment the page opens makes many people refuse on instinct. The example uses the default. Give it a ready-made piece of audio, so arriving shows a waveform first, which is friendlier than a permission dialog.
Recording is not a single click. Click the record entry point, a device list appears first, choose a microphone, then click “Record”, and when you are done speaking click “Stop”. Once that sequence finishes, startRecording and stopRecording each fire once, and the recorded audio becomes the component’s new value. The example binds both events, so the panel logs one line at the start and one at the stop. First it reads “Recording started; click Stop when done”, and after stopping it changes to “Recording audio.wav · 222306 bytes · .wav”.
The recorded file is named audio.wav, with the extension following format. A roughly three-second mono recording is over two hundred thousand bytes. Wav is uncompressed, so the size is simply that substantial. To make it smaller you have to convert to another format before writing the file; the component does not do it for you.
Recording needs a microphone and browser permission too. If permission is denied, the record entry point will not open, and the UI will not conjure up a fake audio file. This is the same kind of thing as “unsupported format”: if it cannot be done, say so plainly, do not pretend it was done. The same holds when the machine has no microphone: the device list is empty and clicking “Record” does nothing.
Playback is another set of events. The example binds play and stop.
played.Audio.Play(OnAudioPlay, [played.Audio], [played.AudioReport], apiName: "Audio play");
played.Audio.Stop(OnAudioStop, [played.Audio], [played.AudioReport], apiName: "Audio stop");
Click Play and the waveform fills with color from left to right, the time goes from 0:00 to 0:01, and the panel reads Play tone.wav · 105884 bytes · .wav. What the handler function receives is the path of this audio, not sample data. Figure 11-7 shows playback at one second.
Figure 11-7 Audio playback: the waveform has moved through a stretch, the panel notes this file
stop does not fire on every click the way play does. Reaching the end does not fire it; only clicking “Reset” fires it once, and the panel changes to “Stop”. These are two different things. Finished playing is finished playing, stopped is stopped, and the component only reports the latter. To handle “played to the end” you have to watch the time reach the end, or compute it yourself from playbackPosition and the duration; this chapter does not go into it.
pause is the third event, and the example does not bind it. Its difference from stop is semantic. Pause means “stop here and resume later”, stop means “go back to the start”. To record “where the user listened up to”, bind pause; to record “this pass is finished”, bind stop.
The handler functions of all three events accept a string, the path of this audio. Not sample data, not the duration. You have to read the duration from the file yourself. The example’s panel prints only the file name and byte count, because those are enough to show that “the event really did arrive with a value”.
11.5 Audio Waveform and Format
The waveform is the main appearance of this block, and its parameters all live in waveformOptions.
WaveformColor is the color of the waveform; the example gives it blue, and the already-played stretch switches to another color on its own, no extra setup needed. SkipLength is how far the rewind and fast-forward buttons jump in one go, in percent. The example writes 25, this clip is 2.4 seconds, so the two arrow buttons’ tooltips read “Skip 0.6 seconds”. Write 10 and it jumps 0.24 seconds, write 50 and it jumps 1.2 seconds.
ShowRecordingWaveform decides whether a live waveform is drawn while recording; by default it is. The reason you can see the loudness during recording comes down to this. SampleRate is the sample rate of the waveform, 44100 by default; lower it and the waveform gets coarser, while the audio itself is unaffected.
The waveform itself has three color segments: the part not yet played, the part already played, and the part drag-selected ready for trimming. The example only configures WaveformColor, and the played segment changes color automatically, so in Figure 11-7 the left is orange and the right is blue. All three colors can be configured separately; TrimRegionColor is the selection one, and since the example does no trimming it goes unused.
editable decides whether the user can trim and edit. The example writes true, so the toolbar has “Trim” and “Reset”; write false and the user can only play, not change this audio. The trimmed result is also a new value for this component and can be passed straight to the handler function.
The values of format are wav, mp3, or empty. It governs output only. When the handler function returns a piece of audio, the component writes a file in that format. The example writes wav, so stopping a recording saves audio.wav. This “write by format” does not include transcoding. The framework does not run external programs; writing mp3 will not turn wav into mp3 either — a wrong format simply means a wrong file. To convert, you have to do it yourself before passing the audio to the component.
Writing empty (leaving this parameter out) means “leave it alone”. Whatever file the handler function returns is sent to the front end unchanged. Upload an mp3 and return it as-is: empty is the least effort; when the path runs all the way from recording, writing wav is more explicit.
A separate word about type: it says numpy, yet the handler function receives a path.
string OnAudioPlay(string? path)
=> path is null ? "**Audio** no value." : $"**Play** {MediaBook.Describe(path)}";
The signature says string, and what gets printed on the panel is a path like C:\...\tone.wav. The reason is not complicated. Decoding audio into a sample rate and a sample buffer requires a decoder that can handle the various browser recording formats, and libraries of that kind almost all call external programs. The framework does not do this, so on audio the value numpy only means “it knows you want samples”; what actually reaches the handler function is still a path. Writing filepath gets you the same thing. On audio the two spellings make no difference.
This is a boundary the component draws for itself. Pixel-level processing of audio you do yourself; the component only guarantees that “where the file is” is reliable. For waveform data, a spectrum, or silence detection, start from that path and read it with a decoding library of your own choosing.
playbackPosition sets which second playback starts from, 0 by default; loop makes it restart automatically after finishing; autoplay makes it play on arrival. All three are pure playback behavior and do not affect the value. autoplay is blocked by the browser’s autoplay policy. If the page has had no user interaction, no sound plays — that is the browser’s doing, not a component problem. The example leaves all three alone: the audio comes in stopped at 0:00, waiting for someone to click Play.
11.6 Video Sources, Subtitles, and Playback
The parameter list of Video closely resembles Image, with three extra things: subtitles, playback position, and the audio track.
var video = gr.Video(
value: MediaBook.Clip,
playbackPosition: 1,
height: 300,
subtitles: new[]
{
new Subtitle { Start = 0.4, End = 1.6, Text = "Sentence one: four squares from left to right" },
new Subtitle { Start = 1.7, End = 2.9, Text = "Sentence two: the subtitles are written as a vtt file" },
},
label: "Video: starts at second 1, with subtitles");
sources provides upload and webcam by default; the example does not set it, so the block has two entry points, “Upload” and “Webcam”. streaming is off by default; turn it on and the component plays a stream produced piece by piece by the handler function, which is a Chapter 16 matter.
subtitles accepts a path, or a series of Subtitle items. The example gives the latter. Each item has three fields: start second, end second, and text. This list of entries is not sent to the front end as-is. Browsers only understand WebVTT, so the component first writes them into a subtitles.vtt file in the cache, then has <video> attach that file. The line of text you see in the UI is displayed by the browser itself, according to the time.
Each of the two forms has its use. If you already have a finished subtitle file, give the path directly and the component attaches it unchanged; if the subtitles are computed from data (say, generated from timestamps), giving a list is less work. You do not have to land a file first, nor hand-write the WebVTT header. The example is the second form. The two sentences sit in the code, and their times line up with that three-second clip.
The time unit is seconds, and decimals are allowed. The example’s first entry runs from 0.4 seconds to 1.6 seconds, the second from 1.7 seconds to 2.9 seconds. A 0.1-second gap is left in between, so the two lines do not overlap when switching. That gap is not required, but with it the speech feels more human.
Figure 11-8 shows it during playback. The video starts at second 1. That is what playbackPosition: 1 means: on arrival it does not play from the beginning, it stops directly at second 1. Click Play, and when it reaches a little past two seconds the bottom of the frame switches to the second subtitle.
Note that “stop at second 1” and “start playing from second 1” are two different things. playbackPosition only moves the position; it does not press Play. On arrival the example is a still frame with the time 0:01 / 0:03, and nothing moves until you click. To play on arrival you have to add autoplay: true, and autoplay is blocked by the browser. A page with no user interaction plays no sound. So “start in the middle and wait for a click” is the steadier default.
Figure 11-8 Video playback: starting at second 1, the second subtitle sits at the bottom of the frame
The subtitle position is decided by the browser, hugging the lower edge of the frame. Make the block taller and the frame larger and the text grows; make the block short and the text shrinks. The example fixes the block height at 300, so the subtitles are legible but not large. To make them larger you have to draw your own subtitle band outside the frame, which is a different matter.
The control bar also comes with the viewer: play/pause, progress, time, volume, fullscreen. It appears when the mouse rests on the frame and hides itself a moment after you move away. There is no control bar in Figure 11-8 precisely because the mouse was moved away before the screenshot. For subtitles to stay visible, the control bar must not sit on top of them. In a product you need not worry about this; the user will make it appear on their own.
Three events follow playback: play, pause, and end. The example binds all three, and the panel writes “Play”, “Pause”, and “Playback finished” respectively. The line in Figure 11-8 is Play clip.webm · 79168 bytes · .webm; at the end of playback the same line changes to “Playback finished”.
played.Video.Play(OnVideoPlay, [played.Video], [played.VideoReport], apiName: "Video play");
played.Video.Pause(OnVideoPause, [played.Video], [played.VideoReport], apiName: "Video pause");
played.Video.End(OnVideoEnd, [played.Video], [played.VideoReport], apiName: "Video end");
On video, format is likewise “the container used when writing the file”, not a transcoder. The example’s asset is webm, which browsers can play directly, so it passes through unchanged. Switch to a container browsers do not recognize, such as avi, and writing format as mp4 will not rescue it. The component will not convert for you; convert it yourself before passing it to the component.
includeAudio follows sources by default: for videos that can be uploaded, the audio track is kept; for videos recorded from the webcam, there is no audio track to keep in the first place. loop and autoplay are each a boolean — the former restarts after finishing, the latter plays on arrival. Autoplay is blocked by the browser’s policy, and being blocked raises no error; there is simply no sound.
Think carefully about putting loop and the end event together. With looping on, reaching the end fires end once and immediately starts again from the beginning. If you want to do something “when one round ends” (log a line, switch to the next clip), looping makes that happen over and over. The example does not enable looping: playback stops on the last frame, the panel writes “Playback finished”, and you can see at a glance that it has reached the end.
When the container is not recognized, the block is just an empty frame and clicking does nothing. It is the same principle as a wrong image path. When the error is in the file, the UI shows only “nothing there”. Video runs into this especially often, because different browsers support different containers. mp4 is the safest, webm is fine on newer browsers, and avi is basically out of the question. The example uses webm because the asset was itself recorded by a browser, so the container matches.
11.7 Model3D Display Modes and Camera
Model3D is the quietest component in this chapter. It accepts no upload, only a path, and sends the model path to a viewer in the browser to be drawn. The block has only two buttons, Undo and Download; there is no “swap the model” entry point, and where the model comes from is the application’s business.
solid = gr.Model3D(
value: MediaBook.Model,
displayMode: "solid",
cameraPosition: new double?[] { 45, 30, 2.4 },
height: 220,
label: "Solid");
cloud = gr.Model3D(
value: MediaBook.Model,
displayMode: "point_cloud",
clearColor: new double[] { 0.06, 0.09, 0.16, 1 },
cameraPosition: new double?[] { 45, 30, 2.0 },
height: 220,
label: "Point cloud");
wire = gr.Model3D(
value: MediaBook.Model,
displayMode: "wireframe",
clearColor: new double[] { 0.06, 0.09, 0.16, 1 },
cameraPosition: new double?[] { 45, 30, 2.4 },
height: 220,
label: "Wireframe");
displayMode has three values. solid draws the faces, point_cloud draws only the vertices, wireframe draws only the edges. The same model file gives different information in the three modes. Solid shows shape and color, point cloud shows vertex distribution, wireframe shows mesh structure. Figure 11-9 places the three in a row.
Figure 11-9 The three display modes: solid, point cloud, wireframe
The point cloud mode has a prerequisite: the vertices must be dense enough. A cube has only twenty-four vertices, and in point cloud mode that is twenty-four nearly invisible dots, which amounts to nothing; switch to a sphere with over three hundred vertices and the point cloud becomes a mesh whose shape you can make out. displayMode does not change the model itself, it only changes how it is drawn. Whether that way of drawing shows anything depends on how much the model has to draw.
How to choose among the three depends on the question you want to answer. To see what the finished product looks like, use solid; to inspect mesh density and find broken faces, use wireframe; to look at a scanned point cloud and its vertex distribution, use point cloud. Opening three blocks side by side for the same model is easier to compare than switching modes back and forth. Figure 11-9 is arranged exactly that way.
clearColor is the color behind the model, four numbers: red, green, blue, and alpha, all between 0 and 1. By default all four are 0, which is fully transparent. Whatever color is beneath the block, the model appears to float on that color. The example gives the point cloud and wireframe a dark background, because light points and lines are hard to see on a light background; the solid one keeps transparency and follows the page.
The alpha dimension can be used on its own. Write the fourth component as 0.5 and a semi-transparent color block appears behind the model, with the page background still showing through. Write 1 and it is opaque, so the block becomes its own canvas. In Figure 11-9 the two on the right are 1, and the one on the left is the default 0.
cameraPosition is the camera’s position, three numbers: two angles and one distance. The first two are the horizontal angle and the pitch angle, in degrees; the third is how far the camera is from the model. Any of the three can be left out (written as null), and the one left out is decided by the viewer itself. The example writes all three. The angles are the same and the distances differ slightly, so the three images share one viewpoint but differ a little in size.
The distance number depends on the model’s size. The example’s sphere has a radius of 0.8; at a distance of 2.4 the sphere fills two thirds of the block height, and at 1.6 it is right in your face. Switch to a model of very different size and this number has to be adjusted along with it. It is a real distance.
To change only the distance and leave the angles alone, write new double?[] { null, null, 2.4 }; writing all null is the same as omitting the parameter entirely, and the camera parameters keep the viewer’s defaults. The example writes all three so the three images share one viewpoint. Write only one and the other two each follow their own defaults, so side by side they look like three different models.
zoomSpeed and panSpeed are the sensitivity of mouse operations, both 1 by default. Scroll to zoom, drag to pan; turn them up and they feel more responsive, turn them down and they feel steadier. The example leaves them alone. With three blocks side by side, the sensitivity has to be the same so they do not interfere with each other.
The viewer comes with its own set of mouse operations: drag to rotate, scroll to zoom in and out. These operations do not go through the server and do not change the value. After you rotate, the handler function knows nothing about it. If you want “which angle the user rotated to”, this component cannot give it to you; it is a viewer, not an editor. To make a model editable you have to build your own.
The model file itself is not validated. Give it a file that is not glb and the component still accepts it; the browser just cannot draw it, so the block is empty — the same principle as giving Image a path that does not exist. When the error is in the file, the UI shows only “nothing there”.
11.8 Chapter Summary
Two parameters of Image decide the contract. sources controls where it comes from, with three values: upload, webcam, clipboard; leave it out and all three are provided, and with streaming: true only the webcam remains. type controls what gets passed. numpy and pil give the handler function a RasterImage (width, height, RGBA), filepath gives a cache path. The same 480×320 image is 2,217 bytes as a file and 614,400 bytes as pixels.
format only governs the leg where pixels are written to a file; when the value is an existing path it has no say, and the file is sent to the front end unchanged. height and width are the dimensions of the block, not the pixel dimensions of the image. interactive: false removes the upload entry point — an output slot should not let people drag things into it.
The value of ImageEditor is an EditorValue. Three parts — base image, layers, composite — whose types follow type. transforms decides which transforms appear in the toolbar; brush, eraser, and layers decide what those tools look like. Draw one stroke and layers go from 0 to 1; after applying, the composite image is the new output, and writing its path back into the editor makes the edited result the new base image.
For Audio, sources is upload and microphone, and recording: true opens the microphone as soon as it loads. play fires on playback, stop fires on stopping; reaching the end does not fire stop. Recording needs a microphone and permission, and startRecording and stopRecording each fire once. The waveform is governed by waveformOptions: color, skip ratio, recording waveform, sample rate; editable decides whether trimming is allowed.
On audio, type set to numpy still gets a path, because decoding needs external programs and the framework does not do it. format only takes effect when writing the file, and it does not transcode.
For Video, sources defaults to upload and webcam, playbackPosition sets which second to start from, and giving subtitles a series of Subtitle items writes them into subtitles.vtt and attaches that to <video>. The three events play, pause, and end follow playback. format likewise does not transcode, and cannot rescue a container the browser does not recognize.
Model3D accepts only a path, displayMode is one of three — solid, point cloud, wireframe; clearColor has four components between 0 and 1, fully transparent by default; cameraPosition is two angles plus a distance, any of which can be left out. A point cloud needs dense enough vertices before its shape shows.
Look at the four components together and the structure is the same one. sources controls the entry points, type controls what gets passed, format controls what is written back. Image breaks these three things down the finest, audio and video copy it, and the model keeps only the first. It accepts no upload, only a path. Once the structure is fixed, when you meet a new media component, look for these three parameters first; it is faster than memorizing the parameter list one by one.
Behind every media value is a file. The file lands in the cache directory, in is move and out is write; when that directory is cleared and how large it can grow is covered in the next chapter. The next chapter also fills in the things this one skirted around: one file, multiple files, upload destination, size limits, and download.