Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

fix(media): the Android release shows its animations as animated WebP images

Duarte Santos93b248b4ae44
diff --git a/frontend/src/lib/exercises.clip-ext.test.js b/frontend/src/lib/exercises.clip-ext.test.js
new file mode 100644
index 000000000..874aeb862
--- /dev/null
+++ b/frontend/src/lib/exercises.clip-ext.test.js
@@ -0,0 +1,26 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+// The Android release shows its animations as animated WebP images (VITE_CLIP_EXT=webp); every
+// other build keeps the MP4 loops.
+describe('gifSrc and VITE_CLIP_EXT', () => {
+ afterEach(() => { vi.unstubAllEnvs(); vi.resetModules() })
+ const ex = { id: '0025', img: '0025.webp', gif: '0025.mp4', fv: '9025' }
+
+ it('names MP4 loops by default', async () => {
+ const { gifSrc, isVideoSrc } = await import('./exercises.js')
+ expect(gifSrc(ex, 'male')).toBe('exercise-media/clip/0025.mp4')
+ expect(gifSrc(ex, 'female')).toBe('exercise-media/clip/9025.mp4')
+ expect(isVideoSrc(gifSrc(ex, 'male'))).toBe(true)
+ })
+
+ it('names animated WebP images in the Android release', async () => {
+ vi.stubEnv('VITE_CLIP_EXT', 'webp')
+ const { gifSrc, imgSrc, isVideoSrc } = await import('./exercises.js')
+ expect(gifSrc(ex, 'male')).toBe('exercise-media/clip/0025.webp')
+ expect(gifSrc(ex, 'female')).toBe('exercise-media/clip/9025.webp')
+ expect(isVideoSrc(gifSrc(ex, 'male'))).toBe(false)
+ expect(imgSrc(ex, 'male')).toBe('exercise-media/still/0025.webp')
+ // a fork's GIF stays a GIF
+ expect(gifSrc({ ...ex, gif: '0025.gif', fv: undefined }, 'male')).toBe('exercise-media/clip/0025.gif')
+ })
+})
diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.js
index 69def1c33..a3cea7ffe 100644
--- a/frontend/src/lib/exercises.js
+++ b/frontend/src/lib/exercises.js
@@ -172,6 +172,11 @@ const ENV = import.meta.env || {}
// dataset's media over img/ and gif/, and would hide the catalogue's files if they lived there.
const IMG_BASE = ENV.VITE_IMG_BASE || 'exercise-media/still/'
const GIF_BASE = ENV.VITE_GIF_BASE || 'exercise-media/clip/'
+// The animations are MP4 loops, except in the Android release: there they are animated WebP
+// (VITE_CLIP_EXT=webp, staged from APP_MEDIA_DIR), shown as a plain image. The WebView's video
+// player stalled at every loop of these 3-second clips on real phones; an image decodes like the
+// GIFs the app had before and loops by itself.
+const CLIP_EXT = ENV.VITE_CLIP_EXT === 'webp' ? '.webp' : '.mp4'
// About 940 exercises are drawn twice, on a male and on a female figure: `fv` names the female
// drawing of a male exercise, `mv` the male drawing of a female one. Which figure shows is a
// setting (figureOf); the exercise, its id and everything logged against it stay the same either
@@ -182,7 +187,8 @@ export const figureOf = S => (S?.exFigure === 'female' || S?.exFigure === 'male'
: (S?.body === 'female' ? 'female' : 'male')
const drawing = (ex, figure) => (figure === 'female' ? ex.fv : figure === 'male' ? ex.mv : null) || null
export const imgSrc = (ex, figure) => IMG_BASE + (drawing(ex, figure) ? drawing(ex, figure) + '.webp' : ex.img)
-export const gifSrc = (ex, figure) => GIF_BASE + (drawing(ex, figure) ? drawing(ex, figure) + '.mp4' : ex.gif)
+const clipFile = f => (CLIP_EXT !== '.mp4' && f.endsWith('.mp4') ? f.slice(0, -4) + CLIP_EXT : f)
+export const gifSrc = (ex, figure) => GIF_BASE + clipFile(drawing(ex, figure) ? drawing(ex, figure) + '.mp4' : ex.gif)
// The catalogue's animations are short MP4 loops; a fork's or an older build's may still be GIFs.
export const isVideoSrc = src => /\.(mp4|webm)(\?|$)/i.test(src || '')
diff --git a/scripts/catalogue/stage-media.mjs b/scripts/catalogue/stage-media.mjs
index 502e0f322..34aee2f8e 100644
--- a/scripts/catalogue/stage-media.mjs
+++ b/scripts/catalogue/stage-media.mjs
@@ -4,6 +4,7 @@
// node scripts/catalogue/stage-media.mjs frontend/dist web demo, 180 px from catalogue/media
// APP_MEDIA_DIR=/private/app node scripts/catalogue/stage-media.mjs frontend/dist
// Android package: larger animations
+// VITE_CLIP_EXT=webp APP_MEDIA_DIR=/private/app-webp ... ... as animated WebP (the release)
//
// The media are licensed from Gym visual for openGym only (catalogue/media/NOTICE.md). 180 px is
// what may sit in the repository, a website or a self-hosted server; anything larger may only
@@ -17,6 +18,11 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const out = path.resolve(process.argv[2] || 'frontend/dist')
const media = path.join(ROOT, 'catalogue/media')
const appDir = process.env.APP_MEDIA_DIR
+const clipExt = process.env.VITE_CLIP_EXT === 'webp' ? '.webp' : '.mp4'
+if (clipExt === '.webp' && !appDir) {
+ console.error('VITE_CLIP_EXT=webp needs APP_MEDIA_DIR: the repository only has the MP4 animations')
+ process.exit(1)
+}
const copyDir = (from, to, ext) => {
fs.mkdirSync(to, { recursive: true })
@@ -30,6 +36,6 @@ const copyDir = (from, to, ext) => {
}
const dest = path.join(out, 'exercise-media')
const stills = copyDir(path.join(media, 'still'), path.join(dest, 'still'), '.webp')
-const clips = copyDir(appDir || path.join(media, 'clip'), path.join(dest, 'clip'), '.mp4')
+const clips = copyDir(appDir || path.join(media, 'clip'), path.join(dest, 'clip'), clipExt)
fs.copyFileSync(path.join(media, 'NOTICE.md'), path.join(dest, 'NOTICE.md'))
console.log(`media: ${stills} stills, ${clips} animations${appDir ? ' (app size)' : ''} -> ${path.relative(ROOT, out) || out}`)
diff --git a/scripts/media/build-app-webp.py b/scripts/media/build-app-webp.py
new file mode 100644
index 000000000..b1ea597ae
--- /dev/null
+++ b/scripts/media/build-app-webp.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python3
+"""The Android app's exercise animations as animated WebP (240 px, lossy q60), from the 360 px
+GIFs of the licensed Gym visual pack. Maintainer only, against the private archive:
+
+ python3 -I scripts/media/build-app-webp.py /path/to/opengym-media [--jobs 3]
+
+Writes <archive>/build-appwebp/<id>.webp. Why images and not the MP4 loops the web uses: in the
+app's WebView a <video> goes through the phone's hardware decoder, which stalled at every loop
+of these 3-second clips (users: "slow and buggy"); an animated image is decoded like the GIFs the
+app showed before and loops on its own. 240 px keeps the package at the size of the 360 px MP4s.
+The media are only ever re-encoded by ffmpeg here (licence: no AI on the media).
+"""
+import io, json, os, subprocess, sys, tempfile, zipfile
+from concurrent.futures import ProcessPoolExecutor, as_completed
+
+PX, Q = 240, 60
+
+def encode(job):
+ root, row = job
+ out = os.path.join(root, 'build-appwebp', row['gv'] + '.webp')
+ if os.path.exists(out) and os.path.getsize(out) > 0:
+ return row['gv'], 'skip'
+ files = row['files']
+ src = files.get('360') or files.get('720') or files.get('1080')
+ if not src:
+ return row['gv'], 'no-source'
+ with zipfile.ZipFile(os.path.join(root, 'original', 'gif-white', row['sex'], row['zip'])) as outer:
+ inner = zipfile.ZipFile(io.BytesIO(outer.read(row['inner'])))
+ with tempfile.TemporaryDirectory(dir=os.path.join(root, 'build-appwebp', 'tmp')) as tmp:
+ gif = os.path.join(tmp, 's.gif')
+ open(gif, 'wb').write(inner.read(src))
+ vf = f'scale={PX}:{PX}:force_original_aspect_ratio=decrease:flags=lanczos,pad={PX}:{PX}:(ow-iw)/2:(oh-ih)/2:white'
+ subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-y', '-i', gif, '-vf', vf, '-c:v', 'libwebp_anim',
+ '-lossless', '0', '-q:v', str(Q), '-compression_level', '6', '-loop', '0', '-an', out + '.part.webp'], check=True)
+ os.replace(out + '.part.webp', out)
+ return row['gv'], 'ok'
+
+def main():
+ a = sys.argv[1:]
+ if not a: sys.exit(__doc__)
+ root = os.path.abspath(a[0]); jobs = int(a[a.index('--jobs') + 1]) if '--jobs' in a else 3
+ only = set(a[a.index('--only') + 1].split(',')) if '--only' in a else None
+ rows = json.load(open(os.path.join(root, 'work', 'index.json')))
+ if only: rows = [r for r in rows if r['gv'] in only]
+ os.makedirs(os.path.join(root, 'build-appwebp', 'tmp'), exist_ok=True)
+ done = failed = 0
+ with ProcessPoolExecutor(jobs) as pool:
+ for f in as_completed([pool.submit(encode, (root, r)) for r in rows]):
+ try: gv, state = f.result()
+ except Exception as e: failed += 1; print('FAIL', e, flush=True); continue
+ if state == 'no-source': failed += 1; print('NO SOURCE', gv, flush=True)
+ done += 1
+ if done % 250 == 0: print(f'{done}/{len(rows)}', flush=True)
+ print(f'done {done}, failed {failed}', flush=True)
+
+if __name__ == '__main__':
+ main()