1package eu.siacs.conversations.ui;
2
3import android.app.Activity;
4import android.content.Intent;
5import android.content.SharedPreferences;
6import android.media.MediaRecorder;
7import android.net.Uri;
8import android.os.Build;
9import android.os.Bundle;
10import android.os.Environment;
11import android.os.FileObserver;
12import android.os.Handler;
13import android.os.SystemClock;
14import android.preference.PreferenceManager;
15import android.util.Log;
16import android.view.View;
17import android.view.WindowManager;
18import android.widget.Toast;
19
20import androidx.appcompat.app.AppCompatActivity;
21import androidx.databinding.DataBindingUtil;
22
23import com.google.common.collect.ImmutableSet;
24
25import java.io.File;
26import java.lang.ref.WeakReference;
27import java.text.SimpleDateFormat;
28import java.util.Date;
29import java.util.Locale;
30import java.util.Objects;
31import java.util.concurrent.CountDownLatch;
32import java.util.concurrent.TimeUnit;
33import java.util.Set;
34
35import eu.siacs.conversations.Config;
36import eu.siacs.conversations.R;
37import eu.siacs.conversations.databinding.ActivityRecordingBinding;
38import eu.siacs.conversations.ui.util.SettingsUtils;
39import eu.siacs.conversations.utils.TimeFrameUtils;
40
41public class RecordingActivity extends BaseActivity implements View.OnClickListener {
42
43 private ActivityRecordingBinding binding;
44
45 private MediaRecorder mRecorder;
46 private long mStartTime = 0;
47
48 private final CountDownLatch outputFileWrittenLatch = new CountDownLatch(1);
49
50 private final Handler mHandler = new Handler();
51 private final Runnable mTickExecutor =
52 new Runnable() {
53 @Override
54 public void run() {
55 tick();
56 mHandler.postDelayed(mTickExecutor, 100);
57 }
58 };
59
60 private File mOutputFile;
61
62 private FileObserver mFileObserver;
63
64 @Override
65 protected void onCreate(Bundle savedInstanceState) {
66 super.onCreate(savedInstanceState);
67 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_recording);
68 this.binding.cancelButton.setOnClickListener(this);
69 this.binding.shareButton.setOnClickListener(this);
70 this.setFinishOnTouchOutside(false);
71 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
72 }
73 @Override
74 public void onStart() {
75 super.onStart();
76 if (!startRecording()) {
77 this.binding.shareButton.setEnabled(false);
78 this.binding.timer.setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_BodyMedium);
79 // TODO reset font family. make red?
80 this.binding.timer.setText(R.string.unable_to_start_recording);
81 }
82 }
83
84 @Override
85 protected void onStop() {
86 super.onStop();
87 if (mRecorder != null) {
88 mHandler.removeCallbacks(mTickExecutor);
89 stopRecording(false);
90 }
91 if (mFileObserver != null) {
92 mFileObserver.stopWatching();
93 }
94 }
95
96 protected SharedPreferences getPreferences() {
97 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
98 }
99
100 private static final Set<String> AAC_SENSITIVE_DEVICES =
101 new ImmutableSet.Builder<String>()
102 .add("FP4") // Fairphone 4 https://codeberg.org/monocles/monocles_chat/issues/133
103 .add("ONEPLUS A6000") // OnePlus 6 https://github.com/iNPUTmice/Conversations/issues/4329
104 .add("ONEPLUS A6003") // OnePlus 6 https://github.com/iNPUTmice/Conversations/issues/4329
105 .add("ONEPLUS A6010") // OnePlus 6T https://codeberg.org/monocles/monocles_chat/issues/133
106 .add("ONEPLUS A6013") // OnePlus 6T https://codeberg.org/monocles/monocles_chat/issues/133
107 .add("Pixel 4a") // Pixel 4a https://github.com/iNPUTmice/Conversations/issues/4223
108 .add("WP12 Pro") // Oukitel WP 12 Pro https://github.com/iNPUTmice/Conversations/issues/4223
109 .add("Volla Phone X") // Volla Phone X https://github.com/iNPUTmice/Conversations/issues/4223
110 .build();
111
112 private boolean startRecording() {
113 mRecorder = new MediaRecorder();
114 final String userChosenCodec = getPreferences().getString("voice_message_codec", "");
115 try {
116 mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
117 } catch (final RuntimeException e) {
118 Log.e(Config.LOGTAG,"could not set audio source", e);
119 return false;
120 }
121 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
122 mRecorder.setPrivacySensitive(true);
123 }
124 final int outputFormat;
125 if (("opus".equals(userChosenCodec) || ("".equals(userChosenCodec) && Config.USE_OPUS_VOICE_MESSAGES)) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
126 outputFormat = MediaRecorder.OutputFormat.OGG;
127 mRecorder.setOutputFormat(outputFormat);
128 mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.OPUS);
129 mRecorder.setAudioEncodingBitRate(32000);
130 } else if ("mpeg4".equals(userChosenCodec) || !Config.USE_OPUS_VOICE_MESSAGES) {
131 outputFormat = MediaRecorder.OutputFormat.MPEG_4;
132 mRecorder.setOutputFormat(outputFormat);
133 if (AAC_SENSITIVE_DEVICES.contains(Build.MODEL) && Build.VERSION.SDK_INT <= Build.VERSION_CODES.TIRAMISU) {
134 // Changing these three settings for AAC sensitive devices for Android<=13 might lead to sporadically truncated (cut-off) voice messages.
135 mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC);
136 mRecorder.setAudioSamplingRate(24_000);
137 mRecorder.setAudioEncodingBitRate(28_000);
138 } else {
139 mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
140 mRecorder.setAudioSamplingRate(44_100);
141 mRecorder.setAudioEncodingBitRate(64_000);
142 }
143 } else {
144 outputFormat = MediaRecorder.OutputFormat.THREE_GPP;
145 mRecorder.setOutputFormat(outputFormat);
146 mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
147 mRecorder.setAudioEncodingBitRate(23850);
148 mRecorder.setAudioSamplingRate(16000);
149 }
150 setupOutputFile(outputFormat);
151 mRecorder.setOutputFile(mOutputFile.getAbsolutePath());
152
153 try {
154 mRecorder.prepare();
155 mRecorder.start();
156 mStartTime = SystemClock.elapsedRealtime();
157 mHandler.postDelayed(mTickExecutor, 100);
158 Log.d(Config.LOGTAG, "started recording to " + mOutputFile.getAbsolutePath());
159 return true;
160 } catch (Exception e) {
161 Log.e(Config.LOGTAG, "prepare() failed ", e);
162 return false;
163 }
164 }
165
166 protected void stopRecording(final boolean saveFile) {
167 try {
168 mRecorder.stop();
169 mRecorder.release();
170 } catch (Exception e) {
171 if (saveFile) {
172 Toast.makeText(this, R.string.unable_to_save_recording, Toast.LENGTH_SHORT).show();
173 return;
174 }
175 } finally {
176 mRecorder = null;
177 mStartTime = 0;
178 }
179 if (!saveFile && mOutputFile != null) {
180 if (mOutputFile.delete()) {
181 Log.d(Config.LOGTAG, "deleted canceled recording");
182 }
183 }
184 if (saveFile) {
185 new Thread(new Finisher(outputFileWrittenLatch, mOutputFile, this)).start();
186 }
187 }
188
189 private static class Finisher implements Runnable {
190
191 private final CountDownLatch latch;
192 private final File outputFile;
193 private final WeakReference<Activity> activityReference;
194
195 private Finisher(CountDownLatch latch, File outputFile, Activity activity) {
196 this.latch = latch;
197 this.outputFile = outputFile;
198 this.activityReference = new WeakReference<>(activity);
199 }
200
201 @Override
202 public void run() {
203 try {
204 if (!latch.await(8, TimeUnit.SECONDS)) {
205 Log.d(Config.LOGTAG, "time out waiting for output file to be written");
206 }
207 } catch (final InterruptedException e) {
208 Log.d(Config.LOGTAG, "interrupted while waiting for output file to be written", e);
209 }
210 final Activity activity = activityReference.get();
211 if (activity == null) {
212 return;
213 }
214 activity.runOnUiThread(
215 () -> {
216 activity.setResult(
217 Activity.RESULT_OK, new Intent().setData(Uri.fromFile(outputFile)));
218 activity.finish();
219 });
220 }
221 }
222
223 private File generateOutputFilename(final int outputFormat) {
224 final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.US);
225 final String extension;
226 if (outputFormat == MediaRecorder.OutputFormat.MPEG_4) {
227 extension = "m4a";
228 } else if (outputFormat == MediaRecorder.OutputFormat.OGG) {
229 extension = "oga";
230 } else if (outputFormat == MediaRecorder.OutputFormat.THREE_GPP) {
231 extension = "awb";
232 } else {
233 throw new IllegalStateException("Unrecognized output format");
234 }
235 final String filename =
236 String.format("RECORDING_%s.%s", dateFormat.format(new Date()), extension);
237 final File parentDirectory;
238 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
239 parentDirectory =
240 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RECORDINGS);
241 } else {
242 parentDirectory =
243 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
244 }
245 final File conversationsDirectory = new File(parentDirectory, getString(R.string.app_name));
246 return new File(conversationsDirectory, filename);
247 }
248
249 private void setupOutputFile(final int outputFormat) {
250 mOutputFile = generateOutputFilename(outputFormat);
251 final File parentDirectory = mOutputFile.getParentFile();
252 if (Objects.requireNonNull(parentDirectory).mkdirs()) {
253 Log.d(Config.LOGTAG, "created " + parentDirectory.getAbsolutePath());
254 }
255 setupFileObserver(parentDirectory);
256 }
257
258 private void setupFileObserver(final File directory) {
259 mFileObserver =
260 new FileObserver(directory.getAbsolutePath()) {
261 @Override
262 public void onEvent(int event, String s) {
263 if (s != null
264 && s.equals(mOutputFile.getName())
265 && event == FileObserver.CLOSE_WRITE) {
266 outputFileWrittenLatch.countDown();
267 }
268 }
269 };
270 mFileObserver.startWatching();
271 }
272
273 private void tick() {
274 this.binding.timer.setText(TimeFrameUtils.formatTimePassed(mStartTime, true));
275 }
276
277 @Override
278 public void onClick(final View view) {
279 switch (view.getId()) {
280 case R.id.cancel_button:
281 mHandler.removeCallbacks(mTickExecutor);
282 stopRecording(false);
283 setResult(RESULT_CANCELED);
284 finish();
285 break;
286 case R.id.share_button:
287 this.binding.shareButton.setEnabled(false);
288 this.binding.shareButton.setText(R.string.please_wait);
289 mHandler.removeCallbacks(mTickExecutor);
290 mHandler.postDelayed(() -> stopRecording(true), 500);
291 break;
292 }
293 }
294}