• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.car.messenger;
18 
19 import android.content.Context;
20 import android.os.Handler;
21 import android.speech.tts.TextToSpeech;
22 import android.speech.tts.UtteranceProgressListener;
23 import android.util.Log;
24 
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.function.Consumer;
28 
29 /**
30  * Component that wraps platform TTS engine and supports queued playout.
31  * <p>
32  * It takes care of initializing the TTS engine. TTS requests made are queued up and played when the
33  * engine is setup. It only supports one queued requests; any new requests will cause the existing
34  * one to be dropped. Similarly, if a new one is queued while an existing message is already playing
35  * the existing one will be stopped/interrupted and the new one will start playing.
36  */
37 class TTSHelper {
38     interface Listener {
39         // Called when playout is about to start.
onTTSStarted()40         void onTTSStarted();
41 
42         // The following two are terminal callbacks and no further callbacks should be expected.
43         // Called when playout finishes or playout is cancelled/never started because another TTS
44         // request was made.
onTTSStopped()45         void onTTSStopped();
46         // Called when there's an internal error.
onTTSError()47         void onTTSError();
48     }
49 
50     private static final String TAG = "Messenger.TTSHelper";
51     private static final boolean DBG = MessengerService.DBG;
52 
53     private final Handler mHandler = new Handler();
54     private final TextToSpeech mTextToSpeech;
55     private int mInitStatus;
56     private SpeechRequest mPendingRequest;
57     private final Map<String, Listener> mListeners = new HashMap<>();
58 
TTSHelper(Context context)59     TTSHelper(Context context) {
60         // OnInitListener will only set to SUCCESS/ERROR. So we initialize to STOPPED.
61         mInitStatus = TextToSpeech.STOPPED;
62         // TODO(sriniv): Init this only when needed and shutdown to free resources.
63         mTextToSpeech = new TextToSpeech(context, this::handleInitCompleted);
64         mTextToSpeech.setOnUtteranceProgressListener(mProgressListener);
65     }
66 
handleInitCompleted(int initStatus)67     private void handleInitCompleted(int initStatus) {
68         if (DBG) {
69             Log.d(TAG, "init completed: " + initStatus);
70         }
71         mInitStatus = initStatus;
72         if (mPendingRequest != null) {
73             playInternal(mPendingRequest.mTextToSpeak, mPendingRequest.mListener);
74             mPendingRequest = null;
75         }
76     }
77 
requestPlay(CharSequence textToSpeak, Listener listener)78     void requestPlay(CharSequence textToSpeak, Listener listener) {
79         // Check if its still initializing.
80         if (mInitStatus == TextToSpeech.STOPPED) {
81             // Squash any already queued request.
82             if (mPendingRequest != null) {
83                 mPendingRequest.mListener.onTTSStopped();
84             }
85             mPendingRequest = new SpeechRequest(textToSpeak, listener);
86         } else {
87             playInternal(textToSpeak, listener);
88         }
89     }
90 
requestStop()91     void requestStop() {
92         mTextToSpeech.stop();
93     }
94 
playInternal(CharSequence textToSpeak, Listener listener)95     private void playInternal(CharSequence textToSpeak, Listener listener) {
96         if (mInitStatus == TextToSpeech.ERROR) {
97             Log.e(TAG, "TTS setup failed!");
98             mHandler.post(listener::onTTSError);
99             return;
100         }
101 
102         String id = Integer.toString(listener.hashCode());
103         if (DBG) {
104             Log.d(TAG, String.format("Queueing text in TTS: [%s], id=%s", textToSpeak, id));
105         }
106         if (mTextToSpeech.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, null, id)
107                 != TextToSpeech.SUCCESS) {
108             Log.e(TAG, "Queuing text failed!");
109             mHandler.post(listener::onTTSError);
110             return;
111         }
112         mListeners.put(id, listener);
113     }
114 
cleanup()115     void cleanup() {
116         mTextToSpeech.stop();
117         mTextToSpeech.shutdown();
118     }
119 
120     // The TTS engine will invoke onStart and then invoke either onDone, onStop or onError.
121     // Since these callbacks can come on other threads, we push updates back on to the TTSHelper's
122     // Handler.
123     private final UtteranceProgressListener mProgressListener = new UtteranceProgressListener() {
124         private void safeInvokeAsync(String id, boolean cleanup,
125                 Consumer<Listener> callbackCaller) {
126             mHandler.post(() -> {
127                 Listener listener = mListeners.get(id);
128                 if (listener == null) {
129                     Log.e(TAG, "No listener found for: " + id);
130                     return;
131                 }
132                 callbackCaller.accept(listener);
133                 if (cleanup) {
134                     mListeners.remove(id);
135                 }
136             });
137         }
138 
139         @Override
140         public void onStart(String id) {
141             if (DBG) {
142                 Log.d(TAG, "TTS engine onStart: " + id);
143             }
144             safeInvokeAsync(id, false, Listener::onTTSStarted);
145         }
146 
147         @Override
148         public void onDone(String id) {
149             if (DBG) {
150                 Log.d(TAG, "TTS engine onDone: " + id);
151             }
152             safeInvokeAsync(id, true, Listener::onTTSStopped);
153         }
154 
155         @Override
156         public void onStop(String id, boolean interrupted) {
157             if (DBG) {
158                 Log.d(TAG, "TTS engine onStop: " + id);
159             }
160             safeInvokeAsync(id, true, Listener::onTTSStopped);
161         }
162 
163         @Override
164         public void onError(String id) {
165             if (DBG) {
166                 Log.d(TAG, "TTS engine onError: " + id);
167             }
168             safeInvokeAsync(id, true, Listener::onTTSError);
169         }
170    };
171 
172     private static class SpeechRequest {
173         final CharSequence mTextToSpeak;
174         final Listener mListener;
175 
SpeechRequest(CharSequence textToSpeak, Listener listener)176         public SpeechRequest(CharSequence textToSpeak, Listener listener) {
177             mTextToSpeak = textToSpeak;
178             mListener = listener;
179         }
180     };
181 }
182