Debian Codegraph @

src/lib.rs

raw
1 mod cli;
2 mod error;
3
4 use std::ffi::OsString;
5 use std::io::Write;
6 use std::path::Path;
7 use std::sync::{Arc, Mutex};
8
9 use clap::Parser;
10 pub use error::*;
11 use gio::glib;
12 use gio::prelude::*;
13 use gst::prelude::*;
14
15 const SCALE_FILTER1: image::imageops::FilterType = image::imageops::FilterType::Nearest;
16 const SCALE_FILTER2: image::imageops::FilterType = image::imageops::FilterType::Triangle;
17
18 fn check_plugins() -> Result<()> {
19 let needed = [
20 "coreelements",
21 "playback",
22 "videoconvertscale",
23 "videofilter",
24 "audioconvert",
25 "audioresample",
26 "autodetect",
27 ];
28
29 let registry = gst::Registry::get();
30 let missing = needed
31 .iter()
32 .filter(|n| registry.find_plugin(n).is_none())
33 .cloned()
34 .collect::<Vec<_>>();
35
36 if !missing.is_empty() {
37 Err(Error::other(format!(
38 "Missing GStreamer plugins: {missing:?}"
39 )))
40 } else {
41 Ok(())
42 }
43 }
44
45 fn init<I, T>(args: I) -> Result<cli::Args>
46 where
47 I: IntoIterator<Item = T>,
48 T: Into<OsString> + Clone,
49 {
50 gst::init().unwrap();
51
52 check_plugins()?;
53
54 // This could be solved in a cleaner way when GStreamer adds support for
55 // sorting decoder factories in uridecodebin3.
56 // See: https://gitlab.freedesktop.org/gstreamer/gstreamer/-/issues/959
57 // and https://gitlab.freedesktop.org/gstreamer/gstreamer/-/merge_requests/9672
58 disable_hardware_decoders();
59
60 Ok(cli::Args::parse_from(args))
61 }
62
63 pub fn main_audio_thumbnailer<I, T>(args: I) -> Result<()>
64 where
65 I: IntoIterator<Item = T>,
66 T: Into<OsString> + Clone,
67 {
68 let args = init(args)?;
69
70 get_audio_thumbnail_source(&args.source.uri())?
71 .ok_or(Error::other("No tag image found"))?
72 .write_png(&args.output, args.size)
73 .unwrap();
74
75 Ok(())
76 }
77
78 pub fn main_video_thumbnailer<I, T>(args: I) -> Result<()>
79 where
80 I: IntoIterator<Item = T>,
81 T: Into<OsString> + Clone,
82 {
83 let args = init(args)?;
84
85 get_video_thumbnail_source(&args.source.uri(), args.size)?
86 .write_png(&args.output, args.size)
87 .unwrap();
88
89 Ok(())
90 }
91
92 fn get_audio_thumbnail_source(input_uri: &str) -> Result<Option<ThumbnailSource>> {
93 let pipeline = Pipeline::new();
94
95 // Source
96 let uridecodebin = gst::ElementFactory::make("uridecodebin3")
97 .property("uri", input_uri)
98 .build()?;
99
100 // Sink
101 let fakesink = gst::ElementFactory::make("fakesink")
102 .property("sync", false)
103 .build()?;
104
105 pipeline.add_many([&uridecodebin, &fakesink])?;
106
107 // Connect dynamic pad from uridecodebin3 to fakesink
108 uridecodebin.connect_pad_added(move |_, src_pad| {
109 let sink_pad = fakesink.static_pad("sink").unwrap();
110 if !sink_pad.is_linked() {
111 src_pad.link(&sink_pad).unwrap();
112 }
113 });
114
115 // Get stream initialized
116 match pipeline.set_state(gst::State::Paused) {
117 Ok(gst::StateChangeSuccess::NoPreroll) => {
118 return Err(Error::other(
119 "Error: thumbnails of live streams make little sense",
120 ));
121 }
122 Err(_) => {
123 return Err(Error::other(state_change_error_details(&pipeline)));
124 }
125 Ok(_) => {}
126 }
127
128 // Wait until stream is initialized
129 while let Some(message) = pipeline.bus().unwrap().timed_pop(gst::ClockTime::NONE) {
130 match message.view() {
131 gst::MessageView::AsyncDone(_) => return Ok(None),
132 gst::MessageView::Error(err) => {
133 return Err(Error::other(format!(
134 "Error: Failed pre-rolling pipeline: {err}"
135 )));
136 }
137 gst::MessageView::Tag(tag) => {
138 if let Some(sample) = get_thumbnail_from_tag(tag) {
139 return Ok(Some(ThumbnailSource::CoverArt(sample)));
140 }
141 }
142 _ => {}
143 }
144 }
145
146 Ok(None)
147 }
148
149 fn get_video_thumbnail_source(input_uri: &str, thumbnail_size: u16) -> Result<ThumbnailSource> {
150 let pipeline = Pipeline::new();
151
152 // Source
153 let uridecodebin = gst::ElementFactory::make("uridecodebin3")
154 .property("uri", input_uri)
155 .build()?;
156
157 // Filters
158 let videoscale = gst::ElementFactory::make("videoscale").build()?;
159 let videoconvert = gst::ElementFactory::make("videoconvert").build()?;
160 let capsfilter = gst::ElementFactory::make("capsfilter").build()?;
161 let videoflip = gst::ElementFactory::make("videoflip")
162 .property("video-direction", gst_video::VideoOrientationMethod::Auto)
163 .build()?;
164
165 // Sink
166 let appsink = gst_app::AppSink::builder()
167 .sync(false)
168 // Only keep one frame in buffer and block on it
169 .max_buffers(1)
170 .build();
171
172 pipeline.add_many([
173 &uridecodebin,
174 &videoscale,
175 &videoconvert,
176 &capsfilter,
177 &videoflip,
178 appsink.upcast_ref(),
179 ])?;
180
181 // Static links
182 gst::Element::link_many([
183 &videoscale,
184 &videoconvert,
185 &capsfilter,
186 &videoflip,
187 appsink.upcast_ref(),
188 ])?;
189
190 // Manually set number of worker threads for decoders in order to reduce memory
191 // usage on setups with many cores, see
192 // https://gitlab.freedesktop.org/gstreamer/gstreamer/-/issues/4423
193 uridecodebin.connect_closure(
194 "deep-element-added",
195 false,
196 glib::closure!(
197 |_uridecodebin: &gst::Element, _bin: &gst::Bin, element: &gst::Element| {
198 let Some(factory) = element.factory() else {
199 return;
200 };
201
202 match factory.name().as_str() {
203 // WARNING!
204 // Be careful adding support for new elements in the future here. Make sure
205 // your tests have covered newly added code, since it's easy to use an incorrect
206 // type for the "number of threads" property. Some elements use an unsigned
207 // integer, others a signed integer. Mixing them up will result
208 // in a runtime crash with no compiler warning.
209 factory_name if factory_name.starts_with("avdec_") => {
210 let gobject_class = element.class();
211 if gobject_class.find_property("max-threads").is_some() {
212 element.set_property("max-threads", 1i32);
213 }
214 }
215 "dav1ddec" => {
216 element.set_property("n-threads", 1u32);
217 }
218 "vp8dec" | "vp9dec" => {
219 element.set_property("threads", 1u32);
220 }
221 _ => (),
222 }
223 }
224 ),
225 );
226
227 // This error message will be replace once pads are detected
228 let source_link_status = Arc::new(Mutex::new(Err(Error::other("No pad added for source."))));
229 uridecodebin.connect_pad_added(glib::clone!(
230 #[strong]
231 source_link_status,
232 move |_, src_pad| {
233 let link_source = || {
234 let stream = src_pad.stream().unwrap();
235 if stream.stream_type() != gst::StreamType::VIDEO {
236 return Err(Error::other(format!(
237 "Stream is of type '{}' instead of 'video'",
238 stream.stream_type()
239 )));
240 }
241 let caps = stream.caps().unwrap();
242 let s = caps.structure(0).unwrap();
243
244 let mut width = s.get::<i32>("width").unwrap() as f32;
245 let height = s.get::<i32>("height").unwrap() as f32;
246 if let Some(par) = s
247 .get_optional::<gst::Fraction>("pixel-aspect-ratio")
248 .map_err(Error::other)?
249 {
250 width *= par.numer() as f32 / par.denom() as f32;
251 }
252
253 let (new_width, new_height) =
254 scale_thumbnail_dimensions(width, height, thumbnail_size);
255
256 let caps = gst::Caps::builder("video/x-raw")
257 .field("format", "RGB")
258 .field("width", new_width as i32)
259 .field("height", new_height as i32)
260 .field("pixel-aspect-ratio", gst::Fraction::new(1, 1))
261 .build();
262
263 capsfilter.set_property("caps", caps);
264
265 // Link source pad to sink of first filter
266 let sink_pad = videoscale.static_pad("sink").unwrap();
267 if !sink_pad.is_linked() {
268 src_pad.link(&sink_pad).map_err(Error::other)?;
269 }
270
271 Ok(())
272 };
273
274 let result = link_source();
275 let mut status = source_link_status.lock().unwrap();
276 if status.is_err() {
277 *status = result
278 }
279 }
280 ));
281
282 // Get stream initialized
283 match pipeline.set_state(gst::State::Paused) {
284 Ok(gst::StateChangeSuccess::NoPreroll) => {
285 return Err(Error::other(
286 "Error: thumbnails of live streams make little sense",
287 ));
288 }
289 Err(_) => {
290 return Err(Error::other(state_change_error_details(&pipeline)));
291 }
292 Ok(_) => {}
293 }
294
295 // Wait until stream is initialized
296 while let Some(message) = pipeline.bus().unwrap().timed_pop(gst::ClockTime::NONE) {
297 match message.view() {
298 gst::MessageView::StreamsSelected(_) => {
299 // This is fired after all pads have been connected. So check here if a usable
300 // pad has been connected.
301 std::mem::replace(&mut *source_link_status.lock().unwrap(), Ok(()))?;
302 }
303 gst::MessageView::AsyncDone(_) => {
304 // We didn't find a stored thumbnail/cover, so continue with extracting frames
305 break;
306 }
307 gst::MessageView::Error(err) => {
308 return Err(Error::other(format!("Failed pre-rolling pipeline: {err}")));
309 }
310 gst::MessageView::Tag(tag) => {
311 if let Some(sample) = get_thumbnail_from_tag(tag) {
312 return Ok(ThumbnailSource::CoverArt(sample));
313 }
314 }
315 _ => {}
316 }
317 }
318
319 pipeline.debug_to_dot_file_with_ts(
320 gst::DebugGraphDetails::all(),
321 "gst_video_thumbnailer_paused",
322 );
323
324 let duration = if let Some(duration) = pipeline.query_duration::<gst::ClockTime>() {
325 duration
326 } else {
327 eprintln!("Failed to get video length.");
328 gst::ClockTime::ZERO
329 };
330
331 // Determine position in video we want to take as thumbnail
332 let seek_at = if duration > 180.seconds() {
333 // For long videos, take frames at 10%, 15%, 20%, 25%, 30% of the
334 // video This only uses the first third of the video to not spoiler
335 // films
336 [10, 15, 20, 25, 30]
337 } else {
338 // For short videos, sample from the complete video
339 [10, 20, 30, 60, 90]
340 };
341
342 let mut samples = vec![appsink.pull_preroll()?];
343
344 // Pull frames at seek positions
345 for percentage in seek_at {
346 let seek_to = duration.mul_div_ceil(percentage, 100).unwrap();
347
348 // Seek to calculated position
349 //
350 // Allow to fail in the hope that we still get a frame
351 if pipeline
352 .seek_simple(gst::SeekFlags::FLUSH | gst::SeekFlags::KEY_UNIT, seek_to)
353 .is_err()
354 {
355 eprintln!("Failed to seek to {seek_to}");
356 }
357
358 // Wait until seek is finished
359 let msg = pipeline.bus().unwrap().timed_pop_filtered(
360 gst::ClockTime::NONE,
361 &[gst::MessageType::Error, gst::MessageType::AsyncDone],
362 );
363
364 if let Some(gst::MessageView::Error(err)) = msg.as_ref().map(|msg| msg.view()) {
365 return Err(Error::other(format!(
366 "Error: Failed pre-rolling pipeline after seek: {err}"
367 )));
368 }
369
370 samples.push(appsink.pull_preroll()?);
371 }
372
373 // Use sample with highest variance
374 let (sample, _) = samples
375 .into_iter()
376 .filter_map(|x| {
377 let caps = x.caps().unwrap();
378 let info = gst_video::VideoInfo::from_caps(caps).ok()?;
379
380 let data = x.buffer()?.map_readable().ok()?;
381 let var = variance(&data, info.width(), info.stride()[0] as u32, info.height());
382 drop(data);
383
384 Some((x, var))
385 })
386 .max_by(|(_, var1), (_, var2)| var1.partial_cmp(var2).unwrap())
387 .unwrap();
388
389 let caps = sample.caps().unwrap();
390 let info = gst_video::VideoInfo::from_caps(caps)?;
391 let width = info.width();
392 let height = info.height();
393 let stride = info.stride()[0] as usize;
394
395 let new_stride = width as usize * 3;
396 let sample_map = sample.buffer().unwrap().map_readable()?;
397
398 // Get rid of padding after stride
399 let mut buf = vec![0; height as usize * new_stride];
400 for (out_line, in_line) in Iterator::zip(
401 buf.chunks_exact_mut(new_stride),
402 sample_map.chunks_exact(stride),
403 ) {
404 out_line.copy_from_slice(&in_line[0..new_stride]);
405 }
406
407 Ok(ThumbnailSource::VideoFrame(width, height, buf))
408 }
409
410 fn state_change_error_details(pipeline: &gst::Pipeline) -> String {
411 let mut err_msg = String::from("Error: Failed setting pipeline to PAUSED");
412 if let Some(msg) = pipeline
413 .bus()
414 .unwrap()
415 .pop_filtered(&[gst::MessageType::Error])
416 {
417 let gst::MessageView::Error(msg) = msg.view() else {
418 unreachable!();
419 };
420
421 err_msg.push('\n');
422 err_msg.push_str(&msg.to_string());
423 if let Some(debug) = msg.debug() {
424 err_msg.push('\n');
425 err_msg.push_str(&debug);
426 }
427 }
428
429 err_msg
430 }
431
432 fn get_thumbnail_from_tag(tag: &gst::message::Tag) -> Option<gst::Sample> {
433 // Check for any cover art.
434 let tags = tag.tags();
435 let mut cover_sample = None;
436 for sample_value in tags.iter_tag::<gst::tags::Image>() {
437 let sample = sample_value.get();
438 let Some(caps) = sample.caps() else { continue };
439
440 let image_type = caps
441 .structure(0)
442 .and_then(|s| s.get::<i32>("image-type").ok());
443
444 // TODO: Use gst_tag::TagImageType when it's properly exported
445 // Hardcoding values: 0 = None, 1 = Undefined, 3 = FrontCover
446 // See: https://gitlab.gnome.org/sophie-h/gst-thumbnailers/-/issues/4
447 match image_type {
448 Some(3) => {
449 // Front cover found - use it immediately
450 return Some(sample);
451 }
452 Some(1) | None if cover_sample.is_none() => {
453 // Save as fallback
454 cover_sample = Some(sample);
455 }
456 _ => {}
457 }
458 }
459
460 cover_sample
461 }
462
463 fn scale_thumbnail_dimensions(width: f32, height: f32, thumbnail_size: u16) -> (u32, u32) {
464 let thumbnail_size = thumbnail_size as f32;
465 let scale = if width < thumbnail_size && height < thumbnail_size {
466 // avoid upscaling
467 1.0
468 } else if width > height {
469 thumbnail_size / width
470 } else {
471 thumbnail_size / height
472 };
473 let new_width = (width * scale).round() as u32;
474 let new_height = (height * scale).round() as u32;
475
476 (new_width, new_height)
477 }
478
479 fn filter_hw_decoders(feature: &gst::PluginFeature) -> bool {
480 let factory = match feature.downcast_ref::<gst::ElementFactory>() {
481 Some(f) => f,
482 None => return false,
483 };
484 factory.has_type(gst::ElementFactoryType::MEDIA_VIDEO)
485 && factory.has_type(gst::ElementFactoryType::DECODER)
486 && factory.has_type(gst::ElementFactoryType::HARDWARE)
487 }
488
489 fn disable_hardware_decoders() {
490 let registry = gst::Registry::get();
491 let hw_list = registry.features_filtered(filter_hw_decoders, false);
492 for l in hw_list.iter() {
493 registry.remove_feature(l);
494 }
495 }
496
497 struct Pipeline(gst::Pipeline);
498
499 impl Pipeline {
500 pub fn new() -> Self {
501 Self(gst::Pipeline::new())
502 }
503 }
504
505 impl std::ops::Deref for Pipeline {
506 type Target = gst::Pipeline;
507
508 fn deref(&self) -> &Self::Target {
509 &self.0
510 }
511 }
512
513 impl Drop for Pipeline {
514 fn drop(&mut self) {
515 let _ = self.0.set_state(gst::State::Null);
516 }
517 }
518
519 #[derive(Debug)]
520 pub enum ThumbnailSource {
521 VideoFrame(u32, u32, Vec<u8>),
522 CoverArt(gst::Sample),
523 }
524
525 impl ThumbnailSource {
526 fn write_png(&self, output_path: &Path, thumbnail_size: u16) -> Result<()> {
527 match self {
528 ThumbnailSource::VideoFrame(width, height, frame) => {
529 write_png(output_path, *width, *height, frame)?;
530 Ok(())
531 }
532 ThumbnailSource::CoverArt(sample) => {
533 let buffer = sample.buffer().unwrap();
534 let map = buffer.map_readable()?;
535
536 let loader = gly::Loader::for_bytes(&gly::glib::Bytes::from_owned(map.to_vec()));
537 loader.set_accepted_memory_formats(gly::MemoryFormatSelection::R8G8B8);
538
539 let image = loader.load()?;
540 let frame = image.next_frame()?;
541
542 let (thumbnail_width, thumbnail_height) = scale_thumbnail_dimensions(
543 frame.width() as f32,
544 frame.height() as f32,
545 thumbnail_size,
546 );
547 let data = resize::<image::Rgb<u8>>(&frame, thumbnail_width, thumbnail_height);
548
549 let creator = gly::Creator::new("image/png")?;
550 creator.add_frame(
551 thumbnail_width,
552 thumbnail_height,
553 frame.memory_format(),
554 &gly::glib::Bytes::from_owned(data),
555 )?;
556
557 let image_data = creator.create()?.unwrap();
558
559 std::fs::File::create(output_path)
560 .unwrap()
561 .write_all(&image_data.data())?;
562
563 Ok(())
564 }
565 }
566 }
567 }
568
569 fn write_png(
570 output_path: &Path,
571 thumbnail_width: u32,
572 thumbnail_height: u32,
573 buf: &[u8],
574 ) -> Result<()> {
575 let creator = gly::Creator::new("image/png")?;
576 creator.add_frame(
577 thumbnail_width,
578 thumbnail_height,
579 gly::MemoryFormat::R8g8b8,
580 &gly::glib::Bytes::from_owned(buf.to_vec()),
581 )?;
582
583 let encoded_image = creator.create()?.unwrap();
584
585 let data = encoded_image.data();
586
587 let mut out_file = std::fs::File::create(output_path)?;
588 out_file.write_all(&data)?;
589
590 Ok(())
591 }
592
593 fn resize<T: image::Pixel<Subpixel = u8> + 'static>(
594 frame: &gly::Frame,
595 thumbnail_width: u32,
596 thumbnail_height: u32,
597 ) -> Vec<u8> {
598 let img =
599 image::ImageBuffer::<T, _>::from_raw(frame.width(), frame.height(), frame.buf_bytes())
600 .unwrap();
601
602 let rought_scaled = image::imageops::resize(
603 &img,
604 thumbnail_width * 2,
605 thumbnail_height * 2,
606 SCALE_FILTER1,
607 );
608
609 image::imageops::resize(
610 &rought_scaled,
611 thumbnail_width,
612 thumbnail_height,
613 SCALE_FILTER2,
614 )
615 .into_raw()
616 }
617
618 pub fn variance(xs: &[u8], width: u32, stride: u32, height: u32) -> f32 {
619 let effective_stride = width as usize * 3; // format == "RGB"
620 let len = (effective_stride * height as usize) as f32;
621
622 let avg = xs
623 .chunks_exact(stride as usize)
624 .map(|line| {
625 line[0..effective_stride]
626 .iter()
627 .map(|&x| x as f32)
628 .sum::<f32>()
629 })
630 .sum::<f32>()
631 / len;
632
633 let sq_diff = xs
634 .chunks_exact(stride as usize)
635 .map(|line| {
636 line[0..effective_stride]
637 .iter()
638 .map(|&x| (x as f32 - avg).powi(2))
639 .sum::<f32>()
640 })
641 .sum::<f32>();
642
643 sq_diff / len
644 }