layout improvements
This commit is contained in:
@@ -15,6 +15,8 @@ import com.dtourolle.jellytau.player.JellyTauPlayer
|
||||
object VideoOverlayManager {
|
||||
|
||||
private var attachedSurfaceView: SurfaceView? = null
|
||||
private var contentLayoutListener: android.view.View.OnLayoutChangeListener? = null
|
||||
private var listenerContentView: ViewGroup? = null
|
||||
|
||||
/**
|
||||
* Attach the video SurfaceView to the Activity's content view.
|
||||
@@ -51,6 +53,23 @@ object VideoOverlayManager {
|
||||
contentView.addView(surfaceView, 0, layoutParams)
|
||||
attachedSurfaceView = surfaceView
|
||||
|
||||
// Re-fit the video whenever the content view's bounds change (e.g. on
|
||||
// device rotation) so the video is letterboxed to fit instead of being
|
||||
// stretched/cropped by the MATCH_PARENT surface.
|
||||
removeLayoutListener()
|
||||
val listener = android.view.View.OnLayoutChangeListener {
|
||||
_, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
|
||||
if (right - left != oldRight - oldLeft || bottom - top != oldBottom - oldTop) {
|
||||
player.fitSurfaceToScreen()
|
||||
}
|
||||
}
|
||||
contentView.addOnLayoutChangeListener(listener)
|
||||
contentLayoutListener = listener
|
||||
listenerContentView = contentView
|
||||
|
||||
// Fit once now that the surface is attached and the parent is sized.
|
||||
player.fitSurfaceToScreen()
|
||||
|
||||
android.util.Log.d("VideoOverlayManager", "Video surface attached to view hierarchy")
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("VideoOverlayManager", "Failed to attach video surface", e)
|
||||
@@ -64,6 +83,7 @@ object VideoOverlayManager {
|
||||
*/
|
||||
fun detachVideoSurface(activity: Activity) {
|
||||
try {
|
||||
removeLayoutListener()
|
||||
attachedSurfaceView?.let { surfaceView ->
|
||||
val contentView = activity.window.decorView.findViewById<ViewGroup>(android.R.id.content)
|
||||
contentView.removeView(surfaceView)
|
||||
@@ -83,4 +103,12 @@ object VideoOverlayManager {
|
||||
fun isVideoSurfaceAttached(): Boolean {
|
||||
return attachedSurfaceView != null
|
||||
}
|
||||
|
||||
private fun removeLayoutListener() {
|
||||
contentLayoutListener?.let { listener ->
|
||||
listenerContentView?.removeOnLayoutChangeListener(listener)
|
||||
}
|
||||
contentLayoutListener = null
|
||||
listenerContentView = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,6 +161,9 @@ class JellyTauPlayer(private val appContext: Context) {
|
||||
/** SurfaceView for video playback */
|
||||
private var surfaceView: SurfaceView? = null
|
||||
private var surfaceHolder: SurfaceHolder? = null
|
||||
/** Last reported video frame size, used to fit the surface to the screen preserving aspect ratio */
|
||||
private var videoWidth: Int = 0
|
||||
private var videoHeight: Int = 0
|
||||
private var currentMediaType: MediaType = MediaType.AUDIO
|
||||
private var currentActivity: java.lang.ref.WeakReference<android.app.Activity>? = null
|
||||
|
||||
@@ -262,7 +265,11 @@ class JellyTauPlayer(private val appContext: Context) {
|
||||
}
|
||||
|
||||
override fun onVideoSizeChanged(videoSize: androidx.media3.common.VideoSize) {
|
||||
android.util.Log.d("JellyTauPlayer", "▶ Video size: ${videoSize.width}x${videoSize.height}")
|
||||
android.util.Log.d("JellyTauPlayer", "▶ Video size: ${videoSize.width}x${videoSize.height} par=${videoSize.pixelWidthHeightRatio}")
|
||||
// Apply pixel aspect ratio so anamorphic content isn't distorted
|
||||
videoWidth = (videoSize.width * videoSize.pixelWidthHeightRatio).toInt()
|
||||
videoHeight = videoSize.height
|
||||
fitSurfaceToScreen()
|
||||
}
|
||||
|
||||
override fun onRenderedFirstFrame() {
|
||||
@@ -873,17 +880,62 @@ class JellyTauPlayer(private val appContext: Context) {
|
||||
|
||||
/**
|
||||
* Resize the video surface (for orientation changes).
|
||||
*
|
||||
* Re-fits the surface to the screen preserving the video's aspect ratio so
|
||||
* nothing is cropped when the device rotates.
|
||||
*/
|
||||
fun resizeSurface(width: Int, height: Int) {
|
||||
fitSurfaceToScreen()
|
||||
}
|
||||
|
||||
/**
|
||||
* Size the video SurfaceView so the video fits entirely inside its parent
|
||||
* (the full-screen content view) while preserving aspect ratio (letterbox/
|
||||
* pillarbox). A raw SurfaceView with MATCH_PARENT otherwise stretches the
|
||||
* video to the surface bounds, which crops the bottom on rotation.
|
||||
*/
|
||||
fun fitSurfaceToScreen() {
|
||||
mainHandler.post {
|
||||
surfaceView?.let { view ->
|
||||
view.layoutParams = view.layoutParams.apply {
|
||||
this.width = width
|
||||
this.height = height
|
||||
}
|
||||
view.requestLayout()
|
||||
android.util.Log.d("JellyTauPlayer", "Video surface resized to ${width}x${height}")
|
||||
val view = surfaceView ?: return@post
|
||||
val parent = view.parent as? ViewGroup
|
||||
// Available area: prefer the parent's measured size, fall back to the screen.
|
||||
val availW = parent?.width?.takeIf { it > 0 }
|
||||
?: appContext.resources.displayMetrics.widthPixels
|
||||
val availH = parent?.height?.takeIf { it > 0 }
|
||||
?: appContext.resources.displayMetrics.heightPixels
|
||||
|
||||
if (videoWidth <= 0 || videoHeight <= 0 || availW <= 0 || availH <= 0) {
|
||||
return@post
|
||||
}
|
||||
|
||||
val videoAspect = videoWidth.toFloat() / videoHeight.toFloat()
|
||||
val viewAspect = availW.toFloat() / availH.toFloat()
|
||||
|
||||
val targetW: Int
|
||||
val targetH: Int
|
||||
if (videoAspect > viewAspect) {
|
||||
// Video is wider than the screen → fit width, letterbox top/bottom
|
||||
targetW = availW
|
||||
targetH = (availW / videoAspect).toInt()
|
||||
} else {
|
||||
// Video is taller than the screen → fit height, pillarbox sides
|
||||
targetH = availH
|
||||
targetW = (availH * videoAspect).toInt()
|
||||
}
|
||||
|
||||
val lp = view.layoutParams
|
||||
// FrameLayout child: center the fitted surface within the full-screen parent.
|
||||
if (lp is FrameLayout.LayoutParams) {
|
||||
lp.gravity = android.view.Gravity.CENTER
|
||||
}
|
||||
lp.width = targetW
|
||||
lp.height = targetH
|
||||
view.layoutParams = lp
|
||||
view.requestLayout()
|
||||
android.util.Log.d(
|
||||
"JellyTauPlayer",
|
||||
"Video surface fitted to ${targetW}x${targetH} (video ${videoWidth}x${videoHeight}, avail ${availW}x${availH})"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -176,6 +176,12 @@ pub async fn player_on_playback_ended(
|
||||
AutoplayDecision::Stop => {
|
||||
log::debug!("[Autoplay] Decision: Stop playback");
|
||||
let controller = controller_arc.lock().await;
|
||||
// Clear the queue so the frontend's currentQueueItem becomes null and
|
||||
// the mini player hides. Without this, the queue still holds the last
|
||||
// track and the bar would linger (the frontend keeps the bar visible
|
||||
// through transient idle blips as long as a queue item exists).
|
||||
controller.clear_queue();
|
||||
controller.emit_queue_changed();
|
||||
if let Some(emitter) = controller.event_emitter() {
|
||||
// Emit StateChanged to idle to clear the current media from mini player
|
||||
// Note: Do NOT emit PlaybackEnded here - it would cause an infinite loop
|
||||
|
||||
@@ -677,12 +677,94 @@ fn specta_builder() -> Builder<tauri::Wry> {
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
/// Configure GStreamer (the media backend behind WebKitGTK's HTML5 `<video>`
|
||||
/// element on Linux) to prefer hardware-accelerated VAAPI decoding when the
|
||||
/// host provides it, falling back to software decoding otherwise.
|
||||
///
|
||||
/// All variables are only set if the user has not already exported them, so an
|
||||
/// explicit override (e.g. forcing software decode for debugging) is respected.
|
||||
/// They must be applied before WebKitGTK builds its GStreamer pipeline, hence the
|
||||
/// call at the very top of `run()`.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn enable_linux_hardware_video_decoding() {
|
||||
// Boost the rank of the modern stateless VAAPI decoders (gst-plugins-bad
|
||||
// `va` plugin) so GStreamer selects them ahead of the software decoders. The
|
||||
// `MAX` rank wins decoder autoplugging when the hardware/driver supports the
|
||||
// codec; unsupported codecs simply fall through to software.
|
||||
let rank_overrides = "vah264dec:MAX,vah265dec:MAX,vavp9dec:MAX,vaav1dec:MAX,\
|
||||
vampeg2dec:MAX,vavp8dec:MAX";
|
||||
|
||||
set_env_if_unset("GST_PLUGIN_FEATURE_RANK", rank_overrides);
|
||||
|
||||
// Ensure WebKit keeps GStreamer's hardware/DMABUF video path enabled. Setting
|
||||
// this to "0" would force software decoding, so only default it to "1".
|
||||
set_env_if_unset("WEBKIT_GST_ENABLE_HW_VIDEO_DECODER", "1");
|
||||
|
||||
info!("[INIT] Linux hardware video decoding (VAAPI) enabled where supported");
|
||||
|
||||
log_available_vaapi_decoders();
|
||||
}
|
||||
|
||||
/// Probe (via `gst-inspect-1.0`, which ships with GStreamer) which VAAPI hardware
|
||||
/// video decoders GStreamer can actually load on this host, and log the result so
|
||||
/// it is clear at startup whether hardware decoding is genuinely available or
|
||||
/// whether playback will fall back to software.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn log_available_vaapi_decoders() {
|
||||
const HW_DECODERS: &[&str] = &[
|
||||
"vah264dec", "vah265dec", "vavp9dec", "vaav1dec", "vampeg2dec", "vavp8dec",
|
||||
];
|
||||
|
||||
let available: Vec<&str> = HW_DECODERS
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|name| {
|
||||
std::process::Command::new("gst-inspect-1.0")
|
||||
.arg(name)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.status()
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.collect();
|
||||
|
||||
if available.is_empty() {
|
||||
log::warn!(
|
||||
"[INIT] No VAAPI hardware video decoders found via gst-inspect-1.0; \
|
||||
video will use software decoding. Install the GStreamer 'va' plugin \
|
||||
(gst-plugins-bad) and a VAAPI driver to enable hardware decoding."
|
||||
);
|
||||
} else {
|
||||
info!(
|
||||
"[INIT] VAAPI hardware video decoders available to GStreamer: {}",
|
||||
available.join(", ")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn set_env_if_unset(key: &str, value: &str) {
|
||||
if std::env::var_os(key).is_none() {
|
||||
// SAFETY: called once at startup before any threads that read the
|
||||
// environment (WebKitGTK/GStreamer) are spawned.
|
||||
std::env::set_var(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run() {
|
||||
// Initialize logger
|
||||
env_logger::Builder::from_default_env()
|
||||
.filter_level(log::LevelFilter::Info)
|
||||
.init();
|
||||
|
||||
// On Linux, video plays through WebKitGTK's HTML5 <video> element, which uses
|
||||
// GStreamer as its media backend. Enable hardware-accelerated (VAAPI) decoding
|
||||
// when available so video transcoding/decoding does not fall back to the CPU.
|
||||
// These must be set before WebKitGTK initializes its GStreamer pipeline.
|
||||
#[cfg(target_os = "linux")]
|
||||
enable_linux_hardware_video_decoding();
|
||||
|
||||
// NOTE: TypeScript bindings are generated by the `export_typescript_bindings`
|
||||
// test (`cargo test export_typescript_bindings`), NOT at runtime. Calling
|
||||
// `.export()` here would try to write `../src/lib/api/bindings.ts` at app
|
||||
|
||||
@@ -597,6 +597,13 @@ impl PlayerController {
|
||||
self.queue.clone()
|
||||
}
|
||||
|
||||
/// Clear the queue entirely (used when playback genuinely stops, e.g. the
|
||||
/// sleep timer fires or the queue ends with repeat off). Pair with
|
||||
/// `emit_queue_changed` so the frontend hides the mini player.
|
||||
pub fn clear_queue(&self) {
|
||||
self.queue.lock_safe().clear();
|
||||
}
|
||||
|
||||
/// Toggle shuffle
|
||||
pub fn toggle_shuffle(&self) {
|
||||
self.queue.lock_safe().toggle_shuffle();
|
||||
|
||||
@@ -122,6 +122,18 @@ impl QueueManager {
|
||||
self.context = context;
|
||||
}
|
||||
|
||||
/// Clear the queue entirely, returning it to the empty state.
|
||||
///
|
||||
/// Used when playback genuinely stops (sleep timer fires, or the queue ends
|
||||
/// with repeat off) so the frontend's `currentQueueItem` becomes null and
|
||||
/// the mini player hides. History and shuffle order are reset too.
|
||||
pub fn clear(&mut self) {
|
||||
self.items.clear();
|
||||
self.current_index = None;
|
||||
self.history.clear();
|
||||
self.shuffle_order.clear();
|
||||
}
|
||||
|
||||
/// Add items to the queue
|
||||
pub fn add(&mut self, items: Vec<MediaItem>, position: AddPosition) {
|
||||
if items.is_empty() {
|
||||
@@ -559,6 +571,21 @@ mod tests {
|
||||
assert_eq!(queue.current().unwrap().id, "item_0");
|
||||
}
|
||||
|
||||
/// Test clearing the queue returns it to the empty state so the frontend
|
||||
/// hides the mini player on a genuine stop.
|
||||
#[test]
|
||||
fn test_clear() {
|
||||
let mut queue = QueueManager::new();
|
||||
queue.set_queue(create_test_items(3), 1);
|
||||
assert_eq!(queue.current_index(), Some(1));
|
||||
|
||||
queue.clear();
|
||||
|
||||
assert_eq!(queue.items().len(), 0);
|
||||
assert_eq!(queue.current_index(), None);
|
||||
assert!(queue.current().is_none());
|
||||
}
|
||||
|
||||
/// Test next track navigation
|
||||
///
|
||||
/// @req-test: UR-005 - Control media playback (skip to next track)
|
||||
|
||||
Reference in New Issue
Block a user