summaryrefslogtreecommitdiff
path: root/app/src/main/java/com/wuhei/reccoon/PlayerActivity.java
blob: eb5b8cac135f03121fb66604594da3707ff8377f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
package com.wuhei.reccoon;

import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.util.List;

/**
 * Plays a saved recording with a scrubber and transcribes it on device with
 * sherpa-onnx (multilingual Whisper: English and Italian).
 */
public class PlayerActivity extends AppCompatActivity {

    public static final String EXTRA_NAME = "name";
    public static final String EXTRA_URI = "uri";

    private static final float[] SPEEDS = {1.0f, 1.5f, 2.0f, 0.5f};

    private String recordingName;
    private Uri recordingUri;

    private MediaPlayer player;
    private boolean prepared;

    private TextView titleText;
    private TextView timeText;
    private TextView statusText;
    private SeekBar seekBar;
    private Button playButton;
    private Button speedButton;
    private Button transcribeButton;
    private Spinner languageSpinner;
    private Spinner modelSpinner;
    private ProgressBar progressBar;
    private LinearLayout transcriptContainer;
    private LinearLayout markersSection;
    private LinearLayout markersContainer;

    private final Handler handler = new Handler(Looper.getMainLooper());
    private boolean userSeeking;
    private float speed = SPEEDS[0];
    private int speedIndex;
    private volatile boolean cancelled;

    private ModelRepository models;
    private TranscriptStore transcripts;
    private MarkerStore markerStore;

    private final Runnable ticker = new Runnable() {
        @Override
        public void run() {
            updateProgress();
            handler.postDelayed(this, 250);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);

        Intent intent = getIntent();
        recordingName = intent.getStringExtra(EXTRA_NAME);
        String uriString = intent.getStringExtra(EXTRA_URI);
        if (recordingName == null || uriString == null) {
            finish();
            return;
        }
        recordingUri = Uri.parse(uriString);

        models = new ModelRepository(this);
        transcripts = new TranscriptStore(this);
        markerStore = new MarkerStore(this);

        titleText = findViewById(R.id.titleText);
        timeText = findViewById(R.id.timeText);
        statusText = findViewById(R.id.statusText);
        seekBar = findViewById(R.id.seekBar);
        playButton = findViewById(R.id.playButton);
        speedButton = findViewById(R.id.speedButton);
        transcribeButton = findViewById(R.id.transcribeButton);
        languageSpinner = findViewById(R.id.languageSpinner);
        modelSpinner = findViewById(R.id.modelSpinner);
        progressBar = findViewById(R.id.progressBar);
        transcriptContainer = findViewById(R.id.transcriptContainer);
        markersSection = findViewById(R.id.markersSection);
        markersContainer = findViewById(R.id.markersContainer);

        titleText.setText(Formats.prettyName(recordingName));

        setUpSpinners();
        setUpButtons();
        setUpPlayer();

        InsetsHelper.apply(findViewById(R.id.root));
        showMarkers(loadMarkers());

        TranscriptionEngine.Result existing = transcripts.load(recordingName);
        if (existing != null) {
            showTranscript(existing);
        } else {
            statusText.setText(R.string.transcribe_hint);
        }

        handler.post(ticker);
    }

    private void setUpSpinners() {
        ArrayAdapter<String> languages = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item,
                new String[]{
                        getString(R.string.lang_auto),
                        getString(R.string.lang_en),
                        getString(R.string.lang_it),
                });
        languages.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        languageSpinner.setAdapter(languages);

        ArrayAdapter<String> modelAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item,
                new String[]{
                        getString(R.string.model_base),
                        getString(R.string.model_tiny),
                });
        modelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        modelSpinner.setAdapter(modelAdapter);
    }

    private void setUpButtons() {
        playButton.setOnClickListener(v -> togglePlay());
        speedButton.setOnClickListener(v -> cycleSpeed());
        findViewById(R.id.rewindButton).setOnClickListener(v -> seekBy(-10_000));
        findViewById(R.id.forwardButton).setOnClickListener(v -> seekBy(10_000));
        findViewById(R.id.shareButton).setOnClickListener(v -> shareRecording());
        findViewById(R.id.renameButton).setOnClickListener(v -> showRenameDialog());
        findViewById(R.id.exportButton).setOnClickListener(v -> exportTranscript());
        findViewById(R.id.deleteButton).setOnClickListener(v -> confirmDelete());
        transcribeButton.setOnClickListener(v -> onTranscribeClicked());

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) {
                if (fromUser) {
                    timeText.setText(Formats.clock(progress) + " / " + Formats.clock(duration()));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar bar) {
                userSeeking = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar bar) {
                userSeeking = false;
                if (player != null && prepared) {
                    player.seekTo(bar.getProgress());
                }
            }
        });
    }

    private void setUpPlayer() {
        player = new MediaPlayer();
        prepared = false;
        try {
            player.setDataSource(this, recordingUri);
            player.setOnPreparedListener(mp -> {
                prepared = true;
                seekBar.setMax(mp.getDuration());
                updateTimeLabel();
                updatePlayButton(); // no autoplay
            });
            player.setOnCompletionListener(mp -> updatePlayButton());
            player.prepareAsync();
        } catch (Exception e) {
            Toast.makeText(this, R.string.err_playback, Toast.LENGTH_LONG).show();
        }
    }

    private int duration() {
        if (player == null || !prepared) {
            return 0;
        }
        try {
            return player.getDuration();
        } catch (Exception e) {
            return 0;
        }
    }

    private void togglePlay() {
        if (player == null || !prepared) {
            return;
        }
        try {
            if (player.isPlaying()) {
                player.pause();
            } else {
                if (player.getCurrentPosition() >= player.getDuration() - 150) {
                    player.seekTo(0);
                }
                player.start();
                applySpeed();
            }
        } catch (Exception ignored) {
            // Ignore.
        }
        updatePlayButton();
    }

    private void seekBy(int deltaMs) {
        if (player == null || !prepared) {
            return;
        }
        int target = Math.max(0, Math.min(player.getCurrentPosition() + deltaMs, player.getDuration()));
        player.seekTo(target);
        seekBar.setProgress(target);
        updateTimeLabel();
    }

    private void cycleSpeed() {
        speedIndex = (speedIndex + 1) % SPEEDS.length;
        speed = SPEEDS[speedIndex];
        speedButton.setText(String.format(java.util.Locale.US, "%.1f×", speed));
        applySpeed();
    }

    private void applySpeed() {
        if (player == null || !prepared) {
            return;
        }
        try {
            PlaybackParams params = player.getPlaybackParams();
            params.setSpeed(speed);
            player.setPlaybackParams(params);
        } catch (Exception ignored) {
            // Some devices reject speed changes while paused.
        }
    }

    private void updateProgress() {
        if (player == null || !prepared) {
            return;
        }
        try {
            if (!userSeeking) {
                seekBar.setProgress(player.getCurrentPosition());
            }
        } catch (Exception ignored) {
            // Ignore.
        }
        updateTimeLabel();
        updatePlayButton();
    }

    private void updateTimeLabel() {
        timeText.setText(Formats.clock(player != null && prepared ? player.getCurrentPosition() : 0)
                + " / " + Formats.clock(duration()));
    }

    private void updatePlayButton() {
        boolean playing = false;
        if (player != null && prepared) {
            try {
                playing = player.isPlaying();
            } catch (Exception ignored) {
                // Ignore.
            }
        }
        playButton.setText(playing ? R.string.player_pause : R.string.player_play);
    }

    // --- Library actions --------------------------------------------------

    private List<Marker> loadMarkers() {
        List<Marker> markers = markerStore.load(recordingName);
        if (markers.isEmpty()) {
            markers = WavMarkers.read(this, recordingUri);
        }
        return markers;
    }

    private void shareRecording() {
        try {
            Uri shareUri = RecordingActions.shareableUri(this, recordingUri);
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("audio/wav");
            intent.putExtra(Intent.EXTRA_STREAM, shareUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(Intent.createChooser(intent, getString(R.string.action_share)));
        } catch (Exception e) {
            Toast.makeText(this, R.string.err_share, Toast.LENGTH_LONG).show();
        }
    }

    private void confirmDelete() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.delete_title)
                .setMessage(getString(R.string.delete_message, Formats.prettyName(recordingName)))
                .setPositiveButton(R.string.action_delete, (dialog, which) -> {
                    RecordingActions.delete(this, recordingUri, recordingName);
                    Toast.makeText(this, R.string.deleted, Toast.LENGTH_SHORT).show();
                    finish();
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    private void showRenameDialog() {
        EditText input = new EditText(this);
        input.setText(recordingName);
        input.selectAll();

        int padding = (int) (20 * getResources().getDisplayMetrics().density);
        FrameLayout container = new FrameLayout(this);
        container.setPadding(padding, padding / 2, padding, 0);
        container.addView(input);

        new AlertDialog.Builder(this)
                .setTitle(R.string.rename_title)
                .setView(container)
                .setPositiveButton(R.string.action_rename, (dialog, which) -> {
                    String requested = input.getText().toString().trim();
                    if (!requested.endsWith(".wav")) {
                        requested = requested + ".wav";
                    }
                    String renamed = RecordingActions.rename(
                            this, recordingUri, recordingName, requested);
                    if (renamed == null) {
                        Toast.makeText(this, R.string.rename_failed, Toast.LENGTH_LONG).show();
                        return;
                    }
                    if ("file".equals(recordingUri.getScheme())) {
                        File parent = new File(recordingUri.getPath()).getParentFile();
                        recordingUri = Uri.fromFile(new File(parent, renamed));
                    }
                    recordingName = renamed;
                    titleText.setText(Formats.prettyName(recordingName));
                    showMarkers(loadMarkers());
                    Toast.makeText(this, R.string.renamed, Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    private void exportTranscript() {
        TranscriptionEngine.Result result = transcripts.load(recordingName);
        if (result == null || result.segments.isEmpty()) {
            Toast.makeText(this, R.string.export_none, Toast.LENGTH_LONG).show();
            return;
        }
        try {
            RecordingActions.exportTranscript(this, recordingName, result);
            Toast.makeText(this, R.string.exported, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(this, getString(R.string.export_failed, String.valueOf(e.getMessage())),
                    Toast.LENGTH_LONG).show();
        }
    }

    // --- Transcription ----------------------------------------------------

    private void onTranscribeClicked() {
        ModelRepository.WhisperModel model = modelSpinner.getSelectedItemPosition() == 1
                ? ModelRepository.WhisperModel.TINY
                : ModelRepository.WhisperModel.BASE;
        String language = languageFor(languageSpinner.getSelectedItemPosition());

        if (!models.isReady(model)) {
            promptDownload(model, language);
        } else {
            runTranscription(model, language);
        }
    }

    private void promptDownload(ModelRepository.WhisperModel model, String language) {
        new AlertDialog.Builder(this)
                .setTitle(R.string.model_download_title)
                .setMessage(getString(R.string.model_download_message,
                        model.label, Formats.humanBytes(model.totalBytes())))
                .setPositiveButton(R.string.download, (dialog, which) -> runDownload(model, language))
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    private void runDownload(ModelRepository.WhisperModel model, String language) {
        transcribeButton.setEnabled(false);
        progressBar.setVisibility(View.VISIBLE);
        progressBar.setIndeterminate(false);
        progressBar.setProgress(0);
        statusText.setText(R.string.status_preparing);

        new Thread(() -> {
            try {
                models.download(model, (downloaded, total, file) -> runOnUiThread(() -> {
                    int permille = (int) (downloaded * 1000 / Math.max(1, total));
                    progressBar.setProgress(permille);
                    statusText.setText(getString(
                            R.string.status_downloading, file, permille / 10));
                }));
                runOnUiThread(() -> {
                    statusText.setText(R.string.status_model_ready);
                    runTranscription(model, language);
                });
            } catch (Exception e) {
                runOnUiThread(() -> {
                    transcribeButton.setEnabled(true);
                    progressBar.setVisibility(View.GONE);
                    statusText.setText(getString(R.string.err_download, String.valueOf(e.getMessage())));
                });
            }
        }, "model-download").start();
    }

    private void runTranscription(ModelRepository.WhisperModel model, String language) {
        cancelled = false;
        transcribeButton.setEnabled(false);
        transcriptContainer.removeAllViews();
        progressBar.setVisibility(View.VISIBLE);
        progressBar.setIndeterminate(true);
        statusText.setText(R.string.status_preparing);

        new Thread(() -> {
            TranscriptionEngine.Result result;
            try {
                TranscriptionEngine engine = new TranscriptionEngine(PlayerActivity.this);
                result = engine.transcribe(recordingUri, model, language,
                        new TranscriptionEngine.Callback() {
                            @Override
                            public void onProgress(int percent, String message) {
                                runOnUiThread(() -> {
                                    progressBar.setIndeterminate(false);
                                    progressBar.setProgress(percent * 10);
                                    statusText.setText(message);
                                });
                            }

                            @Override
                            public boolean isCancelled() {
                                return cancelled;
                            }
                        });
            } catch (Exception e) {
                runOnUiThread(() -> statusText.setText(
                        getString(R.string.err_transcribe, String.valueOf(e.getMessage()))));
                return;
            } finally {
                runOnUiThread(() -> {
                    transcribeButton.setEnabled(true);
                    progressBar.setVisibility(View.GONE);
                });
            }

            if (result == null) {
                return;
            }
            try {
                transcripts.save(recordingName, result);
            } catch (Exception ignored) {
                // The transcript is still shown below.
            }
            runOnUiThread(() -> showTranscript(result));
        }, "transcribe").start();
    }

    private void showTranscript(TranscriptionEngine.Result result) {
        transcriptContainer.removeAllViews();
        if (result.segments.isEmpty()) {
            statusText.setText(R.string.status_no_speech);
            return;
        }
        for (TranscriptionEngine.Segment segment : result.segments) {
            addTranscriptLine(segment);
        }
        statusText.setText(R.string.status_transcript_saved);
    }

    private void addTranscriptLine(TranscriptionEngine.Segment segment) {
        SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append("[").append(Formats.clock((int) (segment.startSeconds * 1000))).append("]   ");

        if (segment.words.isEmpty()) {
            builder.append(segment.text);
        } else {
            for (TranscriptionEngine.Word word : segment.words) {
                int start = builder.length();
                builder.append(word.text);
                int end = builder.length();
                if (end > start) {
                    final int seekMs = (int) (word.startSeconds * 1000);
                    builder.setSpan(new ClickableSpan() {
                        @Override
                        public void onClick(@NonNull View widget) {
                            seekTo(seekMs);
                        }

                        @Override
                        public void updateDrawState(@NonNull TextPaint ds) {
                            ds.setColor(getResources().getColor(R.color.text_primary, getTheme()));
                            ds.setUnderlineText(false);
                        }
                    }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
        }

        TextView view = new TextView(this);
        view.setText(builder);
        view.setTextColor(getResources().getColor(R.color.text_primary, getTheme()));
        view.setTextSize(15f);
        view.setPadding(0, 12, 0, 12);
        view.setMovementMethod(LinkMovementMethod.getInstance());
        view.setHighlightColor(Color.TRANSPARENT);
        view.setOnClickListener(v -> seekTo((int) (segment.startSeconds * 1000)));
        transcriptContainer.addView(view);
    }

    private void showMarkers(List<Marker> markers) {
        markersContainer.removeAllViews();
        markersSection.setVisibility(markers.isEmpty() ? View.GONE : View.VISIBLE);
        float density = getResources().getDisplayMetrics().density;
        for (Marker marker : markers) {
            TextView chip = new TextView(this);
            StringBuilder text = new StringBuilder();
            text.append('M').append(marker.index)
                    .append("  ").append(Formats.clock((int) marker.timeMillis()));
            if (!marker.label.isEmpty()) {
                text.append("  ").append(marker.label);
            }
            chip.setText(text.toString());
            chip.setTextColor(getResources().getColor(R.color.text_primary, getTheme()));
            chip.setTextSize(13f);
            chip.setPadding((int) (12 * density), (int) (6 * density),
                    (int) (12 * density), (int) (6 * density));
            chip.setBackgroundResource(R.drawable.badge_marker);
            chip.setOnClickListener(v -> seekTo((int) marker.timeMillis()));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            params.rightMargin = (int) (8 * density);
            chip.setLayoutParams(params);
            markersContainer.addView(chip);
        }
    }

    private void seekTo(int millis) {
        if (player == null || !prepared) {
            return;
        }
        int target = Math.max(0, Math.min(millis, player.getDuration()));
        player.seekTo(target);
        seekBar.setProgress(target);
        if (!player.isPlaying()) {
            player.start();
            applySpeed();
        }
        updateTimeLabel();
    }

    private static String languageFor(int position) {
        switch (position) {
            case 1:
                return TranscriptionEngine.LANG_EN;
            case 2:
                return TranscriptionEngine.LANG_IT;
            default:
                return TranscriptionEngine.LANG_AUTO;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (player != null && prepared) {
            try {
                if (player.isPlaying()) {
                    player.pause();
                }
            } catch (Exception ignored) {
                // Ignore.
            }
            updatePlayButton();
        }
    }

    @Override
    protected void onDestroy() {
        cancelled = true;
        handler.removeCallbacksAndMessages(null);
        if (player != null) {
            try {
                player.release();
            } catch (Exception ignored) {
                // Ignore.
            }
            player = null;
        }
        super.onDestroy();
    }
}