blob: 57c5133bd1545a5e7a4639e8c06e3ef207978492 [file] [log] [blame]
Weilin Xub2a6ca62022-05-08 23:47:04 +00001/*
2 * Copyright (C) 2022 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#include "BroadcastRadio.h"
18#include <broadcastradio-utils-aidl/Utils.h>
19#include "resources.h"
20
21#include <aidl/android/hardware/broadcastradio/IdentifierType.h>
22#include <aidl/android/hardware/broadcastradio/Result.h>
23
24#include <android-base/logging.h>
25
26namespace aidl::android::hardware::broadcastradio {
27
28using ::aidl::android::hardware::broadcastradio::utils::resultToInt;
29using ::aidl::android::hardware::broadcastradio::utils::tunesTo;
30using ::ndk::ScopedAStatus;
31using ::std::literals::chrono_literals::operator""ms;
32using ::std::literals::chrono_literals::operator""s;
33using ::std::lock_guard;
34using ::std::mutex;
35using ::std::string;
36using ::std::vector;
37
38namespace {
39
40inline constexpr std::chrono::milliseconds kSeekDelayTimeMs = 200ms;
41inline constexpr std::chrono::milliseconds kStepDelayTimeMs = 100ms;
42inline constexpr std::chrono::milliseconds kTuneDelayTimeMs = 150ms;
43inline constexpr std::chrono::seconds kListDelayTimeS = 1s;
44
45// clang-format off
46const AmFmRegionConfig kDefaultAmFmConfig = {
47 {
48 {87500, 108000, 100, 100}, // FM
49 {153, 282, 3, 9}, // AM LW
50 {531, 1620, 9, 9}, // AM MW
51 {1600, 30000, 1, 5}, // AM SW
52 },
53 AmFmRegionConfig::DEEMPHASIS_D50,
54 AmFmRegionConfig::RDS};
55// clang-format on
56
57Properties initProperties(const VirtualRadio& virtualRadio) {
58 Properties prop = {};
59
60 prop.maker = "Android";
61 prop.product = virtualRadio.getName();
62 prop.supportedIdentifierTypes = vector<IdentifierType>({
63 IdentifierType::AMFM_FREQUENCY_KHZ,
64 IdentifierType::RDS_PI,
65 IdentifierType::HD_STATION_ID_EXT,
66 IdentifierType::DAB_SID_EXT,
67 });
68 prop.vendorInfo = vector<VendorKeyValue>({
69 {"com.android.sample", "sample"},
70 });
71
72 return prop;
73}
74
75// Makes ProgramInfo that does not point to any particular program
76ProgramInfo makeSampleProgramInfo(const ProgramSelector& selector) {
77 ProgramInfo info = {};
78 info.selector = selector;
79 info.logicallyTunedTo =
80 utils::makeIdentifier(IdentifierType::AMFM_FREQUENCY_KHZ,
81 utils::getId(selector, IdentifierType::AMFM_FREQUENCY_KHZ));
82 info.physicallyTunedTo = info.logicallyTunedTo;
83 return info;
84}
85
86} // namespace
87
88BroadcastRadio::BroadcastRadio(const VirtualRadio& virtualRadio)
89 : mVirtualRadio(virtualRadio),
90 mAmFmConfig(kDefaultAmFmConfig),
91 mProperties(initProperties(virtualRadio)) {
92 const auto& ranges = kDefaultAmFmConfig.ranges;
93 if (ranges.size() > 0) {
94 ProgramSelector sel = utils::makeSelectorAmfm(ranges[0].lowerBound);
95 VirtualProgram virtualProgram = {};
96 if (mVirtualRadio.getProgram(sel, &virtualProgram)) {
97 mCurrentProgram = virtualProgram.selector;
98 } else {
99 mCurrentProgram = sel;
100 }
101 }
102}
103
104BroadcastRadio::~BroadcastRadio() {
105 mThread.reset();
106}
107
108ScopedAStatus BroadcastRadio::getAmFmRegionConfig(bool full, AmFmRegionConfig* returnConfigs) {
109 if (full) {
110 *returnConfigs = {};
111 returnConfigs->ranges = vector<AmFmBandRange>({
112 {65000, 108000, 10, 0}, // FM
113 {150, 30000, 1, 0}, // AM
114 });
115 returnConfigs->fmDeemphasis =
116 AmFmRegionConfig::DEEMPHASIS_D50 | AmFmRegionConfig::DEEMPHASIS_D75;
117 returnConfigs->fmRds = AmFmRegionConfig::RDS | AmFmRegionConfig::RBDS;
118 return ScopedAStatus::ok();
119 }
120 lock_guard<mutex> lk(mMutex);
121 *returnConfigs = mAmFmConfig;
122 return ScopedAStatus::ok();
123}
124
125ScopedAStatus BroadcastRadio::getDabRegionConfig(vector<DabTableEntry>* returnConfigs) {
126 *returnConfigs = {
127 {"5A", 174928}, {"7D", 194064}, {"8A", 195936}, {"8B", 197648}, {"9A", 202928},
128 {"9B", 204640}, {"9C", 206352}, {"10B", 211648}, {"10C", 213360}, {"10D", 215072},
129 {"11A", 216928}, {"11B", 218640}, {"11C", 220352}, {"11D", 222064}, {"12A", 223936},
130 {"12B", 225648}, {"12C", 227360}, {"12D", 229072},
131 };
132 return ScopedAStatus::ok();
133}
134
135ScopedAStatus BroadcastRadio::getImage(int32_t id, vector<uint8_t>* returnImage) {
136 LOG(DEBUG) << __func__ << ": fetching image " << std::hex << id;
137
138 if (id == resources::kDemoPngId) {
139 *returnImage = vector<uint8_t>(resources::kDemoPng, std::end(resources::kDemoPng));
140 return ScopedAStatus::ok();
141 }
142
143 LOG(WARNING) << __func__ << ": image of id " << std::hex << id << " doesn't exist";
144 *returnImage = {};
145 return ScopedAStatus::ok();
146}
147
148ScopedAStatus BroadcastRadio::getProperties(Properties* returnProperties) {
149 lock_guard<mutex> lk(mMutex);
150 *returnProperties = mProperties;
151 return ScopedAStatus::ok();
152}
153
154ProgramInfo BroadcastRadio::tuneInternalLocked(const ProgramSelector& sel) {
155 LOG(DEBUG) << __func__ << ": tune (internal) to " << sel.toString();
156
157 VirtualProgram virtualProgram = {};
158 ProgramInfo programInfo;
159 if (mVirtualRadio.getProgram(sel, &virtualProgram)) {
160 mCurrentProgram = virtualProgram.selector;
161 programInfo = virtualProgram;
162 } else {
163 mCurrentProgram = sel;
164 programInfo = makeSampleProgramInfo(sel);
165 }
166 mIsTuneCompleted = true;
167
168 return programInfo;
169}
170
171ScopedAStatus BroadcastRadio::setTunerCallback(const std::shared_ptr<ITunerCallback>& callback) {
172 LOG(DEBUG) << __func__ << ": setTunerCallback";
173
174 if (callback == nullptr) {
175 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
176 resultToInt(Result::INVALID_ARGUMENTS), "cannot set tuner callback to null");
177 }
178
179 lock_guard<mutex> lk(mMutex);
180 mCallback = callback;
181
182 return ScopedAStatus::ok();
183}
184
185ScopedAStatus BroadcastRadio::unsetTunerCallback() {
186 LOG(DEBUG) << __func__ << ": unsetTunerCallback";
187
188 lock_guard<mutex> lk(mMutex);
189 mCallback = nullptr;
190
191 return ScopedAStatus::ok();
192}
193
194ScopedAStatus BroadcastRadio::tune(const ProgramSelector& program) {
195 LOG(DEBUG) << __func__ << ": tune to " << program.toString() << "...";
196
197 lock_guard<mutex> lk(mMutex);
198 if (mCallback == nullptr) {
199 LOG(ERROR) << __func__ << ": callback is not registered.";
200 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
201 resultToInt(Result::INVALID_STATE), "callback is not registered");
202 }
203
204 if (!utils::isSupported(mProperties, program)) {
205 LOG(WARNING) << __func__ << ": selector not supported: " << program.toString();
206 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
207 resultToInt(Result::NOT_SUPPORTED), "selector is not supported");
208 }
209
210 if (!utils::isValid(program)) {
211 LOG(ERROR) << __func__ << ": selector is not valid: " << program.toString();
212 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
213 resultToInt(Result::INVALID_ARGUMENTS), "selector is not valid");
214 }
215
216 cancelLocked();
217
218 mIsTuneCompleted = false;
219 std::shared_ptr<ITunerCallback> callback = mCallback;
220 auto task = [this, program, callback]() {
221 ProgramInfo programInfo = {};
222 {
223 lock_guard<mutex> lk(mMutex);
224 programInfo = tuneInternalLocked(program);
225 }
226 callback->onCurrentProgramInfoChanged(programInfo);
227 };
228 mThread->schedule(task, kTuneDelayTimeMs);
229
230 return ScopedAStatus::ok();
231}
232
233ScopedAStatus BroadcastRadio::seek(bool directionUp, bool skipSubChannel) {
234 LOG(DEBUG) << __func__ << ": seek " << (directionUp ? "up" : "down") << " with skipSubChannel? "
235 << (skipSubChannel ? "yes" : "no") << "...";
236
237 lock_guard<mutex> lk(mMutex);
238 if (mCallback == nullptr) {
239 LOG(ERROR) << __func__ << ": callback is not registered.";
240 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
241 resultToInt(Result::INVALID_STATE), "callback is not registered");
242 }
243
244 cancelLocked();
245
246 const auto& list = mVirtualRadio.getProgramList();
247 std::shared_ptr<ITunerCallback> callback = mCallback;
248 if (list.empty()) {
249 mIsTuneCompleted = false;
250 auto task = [callback]() {
251 LOG(DEBUG) << "seek: program list is empty, seek couldn't stop";
252
253 callback->onTuneFailed(Result::TIMEOUT, {});
254 };
255 mThread->schedule(task, kSeekDelayTimeMs);
256
257 return ScopedAStatus::ok();
258 }
259
260 // The list is not sorted here since it has already stored in VirtualRadio.
261 // If the list is not sorted in advance, it should be sorted here.
262 const auto& current = mCurrentProgram;
263 auto found = std::lower_bound(list.begin(), list.end(), VirtualProgram({current}));
264 if (directionUp) {
265 if (found < list.end() - 1) {
266 if (tunesTo(current, found->selector)) found++;
267 } else {
268 found = list.begin();
269 }
270 } else {
271 if (found > list.begin() && found != list.end()) {
272 found--;
273 } else {
274 found = list.end() - 1;
275 }
276 }
277 const ProgramSelector tuneTo = found->selector;
278
279 mIsTuneCompleted = false;
280 auto task = [this, tuneTo, callback]() {
281 ProgramInfo programInfo = {};
282 {
283 lock_guard<mutex> lk(mMutex);
284 programInfo = tuneInternalLocked(tuneTo);
285 }
286 callback->onCurrentProgramInfoChanged(programInfo);
287 };
288 mThread->schedule(task, kSeekDelayTimeMs);
289
290 return ScopedAStatus::ok();
291}
292
293ScopedAStatus BroadcastRadio::step(bool directionUp) {
294 LOG(DEBUG) << __func__ << ": step " << (directionUp ? "up" : "down") << "...";
295
296 lock_guard<mutex> lk(mMutex);
297 if (mCallback == nullptr) {
298 LOG(ERROR) << __func__ << ": callback is not registered.";
299 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
300 resultToInt(Result::INVALID_STATE), "callback is not registered");
301 }
302
303 cancelLocked();
304
305 if (!utils::hasId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY_KHZ)) {
306 LOG(WARNING) << __func__ << ": can't step in anything else than AM/FM";
307 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
308 resultToInt(Result::NOT_SUPPORTED), "cannot step in anything else than AM/FM");
309 }
310
311 int64_t stepTo = utils::getId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY_KHZ);
312 std::optional<AmFmBandRange> range = getAmFmRangeLocked();
313 if (!range) {
314 LOG(ERROR) << __func__ << ": can't find current band or tune operation is in process";
315 ScopedAStatus::fromServiceSpecificErrorWithMessage(
316 resultToInt(Result::INTERNAL_ERROR),
317 "can't find current band or tune operation is in process");
318 }
319
320 if (directionUp) {
321 stepTo += range->spacing;
322 } else {
323 stepTo -= range->spacing;
324 }
325 if (stepTo > range->upperBound) {
326 stepTo = range->lowerBound;
327 }
328 if (stepTo < range->lowerBound) {
329 stepTo = range->upperBound;
330 }
331
332 mIsTuneCompleted = false;
333 std::shared_ptr<ITunerCallback> callback = mCallback;
334 auto task = [this, stepTo, callback]() {
335 ProgramInfo programInfo;
336 {
337 lock_guard<mutex> lk(mMutex);
338 programInfo = tuneInternalLocked(utils::makeSelectorAmfm(stepTo));
339 }
340 callback->onCurrentProgramInfoChanged(programInfo);
341 };
342 mThread->schedule(task, kStepDelayTimeMs);
343
344 return ScopedAStatus::ok();
345}
346
347void BroadcastRadio::cancelLocked() {
348 LOG(DEBUG) << __func__ << ": cancelling current operations...";
349
350 mThread->cancelAll();
351 if (mCurrentProgram.primaryId.type != IdentifierType::INVALID) {
352 mIsTuneCompleted = true;
353 }
354}
355
356ScopedAStatus BroadcastRadio::cancel() {
357 LOG(DEBUG) << __func__ << ": cancel pending tune, seek and step...";
358
359 lock_guard<mutex> lk(mMutex);
360 cancelLocked();
361
362 return ScopedAStatus::ok();
363}
364
365ScopedAStatus BroadcastRadio::startProgramListUpdates(const ProgramFilter& filter) {
366 LOG(DEBUG) << __func__ << ": requested program list updates, filter = " << filter.toString()
367 << "...";
368
369 auto filterCb = [&filter](const VirtualProgram& program) {
370 return utils::satisfies(filter, program.selector);
371 };
372
373 lock_guard<mutex> lk(mMutex);
374
375 const auto& list = mVirtualRadio.getProgramList();
376 vector<VirtualProgram> filteredList;
377 std::copy_if(list.begin(), list.end(), std::back_inserter(filteredList), filterCb);
378
379 auto task = [this, filteredList]() {
380 std::shared_ptr<ITunerCallback> callback;
381 {
382 lock_guard<mutex> lk(mMutex);
383 if (mCallback == nullptr) {
384 LOG(WARNING) << "Callback is null when updating program List";
385 return;
386 }
387 callback = mCallback;
388 }
389
390 ProgramListChunk chunk = {};
391 chunk.purge = true;
392 chunk.complete = true;
393 chunk.modified = vector<ProgramInfo>(filteredList.begin(), filteredList.end());
394
395 callback->onProgramListUpdated(chunk);
396 };
397 mThread->schedule(task, kListDelayTimeS);
398
399 return ScopedAStatus::ok();
400}
401
402ScopedAStatus BroadcastRadio::stopProgramListUpdates() {
403 LOG(DEBUG) << __func__ << ": requested program list updates to stop...";
404 // TODO(b/243681584) Implement stop program list updates method
405 return ScopedAStatus::ok();
406}
407
408ScopedAStatus BroadcastRadio::isConfigFlagSet(ConfigFlag flag, [[maybe_unused]] bool* returnIsSet) {
409 LOG(DEBUG) << __func__ << ": flag = " << toString(flag);
410
411 LOG(INFO) << __func__ << ": getting ConfigFlag is not supported";
412 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
413 resultToInt(Result::NOT_SUPPORTED), "getting ConfigFlag is not supported");
414}
415
416ScopedAStatus BroadcastRadio::setConfigFlag(ConfigFlag flag, bool value) {
417 LOG(DEBUG) << __func__ << ": flag = " << toString(flag) << ", value = " << value;
418
419 LOG(INFO) << __func__ << ": setting ConfigFlag is not supported";
420 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
421 resultToInt(Result::NOT_SUPPORTED), "setting ConfigFlag is not supported");
422}
423
424ScopedAStatus BroadcastRadio::setParameters(
425 [[maybe_unused]] const vector<VendorKeyValue>& parameters,
426 vector<VendorKeyValue>* returnParameters) {
427 // TODO(b/243682330) Support vendor parameter functionality
428 *returnParameters = {};
429 return ScopedAStatus::ok();
430}
431
432ScopedAStatus BroadcastRadio::getParameters([[maybe_unused]] const vector<string>& keys,
433 vector<VendorKeyValue>* returnParameters) {
434 // TODO(b/243682330) Support vendor parameter functionality
435 *returnParameters = {};
436 return ScopedAStatus::ok();
437}
438
439std::optional<AmFmBandRange> BroadcastRadio::getAmFmRangeLocked() const {
440 if (!mIsTuneCompleted) {
441 LOG(WARNING) << __func__ << ": tune operation is in process";
442 return {};
443 }
444 if (!utils::hasId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY_KHZ)) {
445 LOG(WARNING) << __func__ << ": current program does not has AMFM_FREQUENCY_KHZ identifier";
446 return {};
447 }
448
449 int64_t freq = utils::getId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY_KHZ);
450 for (const auto& range : mAmFmConfig.ranges) {
451 if (range.lowerBound <= freq && range.upperBound >= freq) {
452 return range;
453 }
454 }
455
456 return {};
457}
458
459ScopedAStatus BroadcastRadio::registerAnnouncementListener(
460 [[maybe_unused]] const std::shared_ptr<IAnnouncementListener>& listener,
461 const vector<AnnouncementType>& enabled, std::shared_ptr<ICloseHandle>* returnCloseHandle) {
462 LOG(DEBUG) << __func__ << ": registering announcement listener for "
463 << utils::vectorToString(enabled);
464
465 // TODO(b/243683842) Support announcement listener
466 *returnCloseHandle = nullptr;
467 LOG(INFO) << __func__ << ": registering announcementListener is not supported";
468 return ScopedAStatus::fromServiceSpecificErrorWithMessage(
469 resultToInt(Result::NOT_SUPPORTED),
470 "registering announcementListener is not supported");
471}
472
473} // namespace aidl::android::hardware::broadcastradio