blob: 52c7b40c7abbb2bcc72ba4997800f8214d362e6f [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#define LOG_TAG "BcRadioAidlDef.utils"
18
19#include "broadcastradio-utils-aidl/Utils.h"
20
21#include <android-base/logging.h>
Weilin Xu97203b02022-06-23 00:19:03 +000022#include <android-base/parseint.h>
23#include <android-base/strings.h>
Weilin Xub2a6ca62022-05-08 23:47:04 +000024
25#include <math/HashCombine.h>
26
27namespace aidl::android::hardware::broadcastradio {
28
29namespace utils {
30
31namespace {
32
Weilin Xu97203b02022-06-23 00:19:03 +000033using ::android::base::EqualsIgnoreCase;
Weilin Xub2a6ca62022-05-08 23:47:04 +000034using ::std::string;
35using ::std::vector;
36
37const int64_t kValueForNotFoundIdentifier = 0;
38
39bool bothHaveId(const ProgramSelector& a, const ProgramSelector& b, const IdentifierType& type) {
40 return hasId(a, type) && hasId(b, type);
41}
42
43bool haveEqualIds(const ProgramSelector& a, const ProgramSelector& b, const IdentifierType& type) {
44 if (!bothHaveId(a, b, type)) {
45 return false;
46 }
47 /* We should check all Ids of a given type (ie. other AF),
48 * but it doesn't matter for default implementation.
49 */
50 return getId(a, type) == getId(b, type);
51}
52
53int getHdSubchannel(const ProgramSelector& sel) {
54 int64_t hdSidExt = getId(sel, IdentifierType::HD_STATION_ID_EXT, /* defaultValue */ 0);
55 hdSidExt >>= 32; // Station ID number
56 return hdSidExt & 0xF; // HD Radio subchannel
57}
58
59bool maybeGetId(const ProgramSelector& sel, const IdentifierType& type, int64_t* val) {
60 // iterate through primaryId and secondaryIds
61 for (auto it = begin(sel); it != end(sel); it++) {
62 if (it->type == type) {
63 if (val != nullptr) {
64 *val = it->value;
65 }
66 return true;
67 }
68 }
69
70 return false;
71}
72
73} // namespace
74
75IdentifierIterator::IdentifierIterator(const ProgramSelector& sel) : IdentifierIterator(sel, 0) {}
76
77IdentifierIterator::IdentifierIterator(const ProgramSelector& sel, size_t pos)
78 : mSel(sel), mPos(pos) {}
79
80const IdentifierIterator IdentifierIterator::operator++(int) {
81 IdentifierIterator i = *this;
82 mPos++;
83 return i;
84}
85
86IdentifierIterator& IdentifierIterator::operator++() {
87 ++mPos;
88 return *this;
89}
90
91IdentifierIterator::refType IdentifierIterator::operator*() const {
92 if (mPos == 0) {
93 return getSelector().primaryId;
94 }
95
96 // mPos is 1-based for secondary identifiers
97 DCHECK(mPos <= getSelector().secondaryIds.size());
98 return getSelector().secondaryIds[mPos - 1];
99}
100
101bool IdentifierIterator::operator==(const IdentifierIterator& rhs) const {
102 // Check, if both iterators points at the same selector.
103 if (reinterpret_cast<intptr_t>(&getSelector()) !=
104 reinterpret_cast<intptr_t>(&rhs.getSelector())) {
105 return false;
106 }
107
108 return mPos == rhs.mPos;
109}
110
111int32_t resultToInt(Result result) {
112 return static_cast<int32_t>(result);
113}
114
115FrequencyBand getBand(int64_t freq) {
116 // keep in sync with
117 // frameworks/base/services/core/java/com/android/server/broadcastradio/aidl/Utils.java
118 if (freq < 30) return FrequencyBand::UNKNOWN;
119 if (freq < 500) return FrequencyBand::AM_LW;
120 if (freq < 1705) return FrequencyBand::AM_MW;
121 if (freq < 30000) return FrequencyBand::AM_SW;
122 if (freq < 60000) return FrequencyBand::UNKNOWN;
123 if (freq < 110000) return FrequencyBand::FM;
124 return FrequencyBand::UNKNOWN;
125}
126
127bool tunesTo(const ProgramSelector& a, const ProgramSelector& b) {
128 IdentifierType type = b.primaryId.type;
129
130 switch (type) {
131 case IdentifierType::HD_STATION_ID_EXT:
132 case IdentifierType::RDS_PI:
133 case IdentifierType::AMFM_FREQUENCY_KHZ:
134 if (haveEqualIds(a, b, IdentifierType::HD_STATION_ID_EXT)) return true;
135 if (haveEqualIds(a, b, IdentifierType::RDS_PI)) return true;
136 return getHdSubchannel(b) == 0 &&
137 haveEqualIds(a, b, IdentifierType::AMFM_FREQUENCY_KHZ);
138 case IdentifierType::DAB_SID_EXT:
139 return haveEqualIds(a, b, IdentifierType::DAB_SID_EXT);
140 case IdentifierType::DRMO_SERVICE_ID:
141 return haveEqualIds(a, b, IdentifierType::DRMO_SERVICE_ID);
142 case IdentifierType::SXM_SERVICE_ID:
143 return haveEqualIds(a, b, IdentifierType::SXM_SERVICE_ID);
144 default: // includes all vendor types
145 LOG(WARNING) << "unsupported program type: " << toString(type);
146 return false;
147 }
148}
149
150bool hasId(const ProgramSelector& sel, const IdentifierType& type) {
151 return maybeGetId(sel, type, /* val */ nullptr);
152}
153
154int64_t getId(const ProgramSelector& sel, const IdentifierType& type) {
155 int64_t val;
156
157 if (maybeGetId(sel, type, &val)) {
158 return val;
159 }
160
161 LOG(WARNING) << "identifier not found: " << toString(type);
162 return kValueForNotFoundIdentifier;
163}
164
165int64_t getId(const ProgramSelector& sel, const IdentifierType& type, int64_t defaultValue) {
166 if (!hasId(sel, type)) {
167 return defaultValue;
168 }
169 return getId(sel, type);
170}
171
172vector<int> getAllIds(const ProgramSelector& sel, const IdentifierType& type) {
173 vector<int> ret;
174
175 // iterate through primaryId and secondaryIds
176 for (auto it = begin(sel); it != end(sel); it++) {
177 if (it->type == type) {
178 ret.push_back(it->value);
179 }
180 }
181
182 return ret;
183}
184
185bool isSupported(const Properties& prop, const ProgramSelector& sel) {
186 for (auto it = prop.supportedIdentifierTypes.begin(); it != prop.supportedIdentifierTypes.end();
187 it++) {
188 if (hasId(sel, *it)) {
189 return true;
190 }
191 }
192 return false;
193}
194
195bool isValid(const ProgramIdentifier& id) {
196 int64_t val = id.value;
197 bool valid = true;
198
199 auto expect = [&valid](bool condition, const string& message) {
200 if (!condition) {
201 valid = false;
202 LOG(ERROR) << "identifier not valid, expected " << message;
203 }
204 };
205
206 switch (id.type) {
207 case IdentifierType::INVALID:
208 expect(false, "IdentifierType::INVALID");
209 break;
210 case IdentifierType::DAB_FREQUENCY_KHZ:
211 expect(val > 100000u, "f > 100MHz");
212 [[fallthrough]];
213 case IdentifierType::AMFM_FREQUENCY_KHZ:
214 case IdentifierType::DRMO_FREQUENCY_KHZ:
215 expect(val > 100u, "f > 100kHz");
216 expect(val < 10000000u, "f < 10GHz");
217 break;
218 case IdentifierType::RDS_PI:
219 expect(val != 0u, "RDS PI != 0");
220 expect(val <= 0xFFFFu, "16bit id");
221 break;
222 case IdentifierType::HD_STATION_ID_EXT: {
223 int64_t stationId = val & 0xFFFFFFFF; // 32bit
224 val >>= 32;
225 int64_t subchannel = val & 0xF; // 4bit
226 val >>= 4;
227 int64_t freq = val & 0x3FFFF; // 18bit
228 expect(stationId != 0u, "HD station id != 0");
229 expect(subchannel < 8u, "HD subch < 8");
230 expect(freq > 100u, "f > 100kHz");
231 expect(freq < 10000000u, "f < 10GHz");
232 break;
233 }
234 case IdentifierType::HD_STATION_NAME: {
235 while (val > 0) {
236 char ch = static_cast<char>(val & 0xFF);
237 val >>= 8;
238 expect((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z'),
239 "HD_STATION_NAME does not match [A-Z0-9]+");
240 }
241 break;
242 }
243 case IdentifierType::DAB_SID_EXT: {
244 int64_t sid = val & 0xFFFF; // 16bit
245 val >>= 16;
246 int64_t ecc = val & 0xFF; // 8bit
247 expect(sid != 0u, "DAB SId != 0");
248 expect(ecc >= 0xA0u && ecc <= 0xF6u, "Invalid ECC, see ETSI TS 101 756 V2.1.1");
249 break;
250 }
251 case IdentifierType::DAB_ENSEMBLE:
252 expect(val != 0u, "DAB ensemble != 0");
253 expect(val <= 0xFFFFu, "16bit id");
254 break;
255 case IdentifierType::DAB_SCID:
256 expect(val > 0xFu, "12bit SCId (not 4bit SCIdS)");
257 expect(val <= 0xFFFu, "12bit id");
258 break;
259 case IdentifierType::DRMO_SERVICE_ID:
260 expect(val != 0u, "DRM SId != 0");
261 expect(val <= 0xFFFFFFu, "24bit id");
262 break;
263 case IdentifierType::SXM_SERVICE_ID:
264 expect(val != 0u, "SXM SId != 0");
265 expect(val <= 0xFFFFFFFFu, "32bit id");
266 break;
267 case IdentifierType::SXM_CHANNEL:
268 expect(val < 1000u, "SXM channel < 1000");
269 break;
270 case IdentifierType::VENDOR_START:
271 case IdentifierType::VENDOR_END:
272 // skip
273 break;
274 }
275
276 return valid;
277}
278
279bool isValid(const ProgramSelector& sel) {
280 // iterate through primaryId and secondaryIds
281 for (auto it = begin(sel); it != end(sel); it++) {
282 if (!isValid(*it)) {
283 return false;
284 }
285 }
286 return true;
287}
288
289ProgramIdentifier makeIdentifier(IdentifierType type, int64_t value) {
290 return {type, value};
291}
292
293ProgramSelector makeSelectorAmfm(int32_t frequency) {
294 ProgramSelector sel = {};
295 sel.primaryId = makeIdentifier(IdentifierType::AMFM_FREQUENCY_KHZ, frequency);
296 return sel;
297}
298
299ProgramSelector makeSelectorDab(int32_t sidExt, int32_t ensemble) {
300 ProgramSelector sel = {};
301 // TODO(243686545): Have a helper function to create the sidExt instead of
302 // passing the whole identifier here. Something like makeDabSidExt.
303 sel.primaryId = makeIdentifier(IdentifierType::DAB_SID_EXT, sidExt);
304 vector<ProgramIdentifier> secondaryIds = {
305 makeIdentifier(IdentifierType::DAB_ENSEMBLE, ensemble),
306 // TODO(243686545): Include frequency here when the helper method to
307 // translate between ensemble and frequency is implemented.
308 };
309 sel.secondaryIds = std::move(secondaryIds);
310 return sel;
311}
312
313bool satisfies(const ProgramFilter& filter, const ProgramSelector& sel) {
314 if (filter.identifierTypes.size() > 0) {
315 auto typeEquals = [](const ProgramIdentifier& id, IdentifierType type) {
316 return id.type == type;
317 };
318 auto it = std::find_first_of(begin(sel), end(sel), filter.identifierTypes.begin(),
319 filter.identifierTypes.end(), typeEquals);
320 if (it == end(sel)) {
321 return false;
322 }
323 }
324
325 if (filter.identifiers.size() > 0) {
326 auto it = std::find_first_of(begin(sel), end(sel), filter.identifiers.begin(),
327 filter.identifiers.end());
328 if (it == end(sel)) {
329 return false;
330 }
331 }
332
333 if (!filter.includeCategories && sel.primaryId.type == IdentifierType::DAB_ENSEMBLE) {
334 return false;
335 }
336
337 return true;
338}
339
340size_t ProgramInfoHasher::operator()(const ProgramInfo& info) const {
341 const ProgramIdentifier& id = info.selector.primaryId;
342
343 // This is not the best hash implementation, but good enough for default HAL
344 // implementation and tests.
345 size_t h = 0;
346 ::android::hashCombineSingle(h, id.type);
347 ::android::hashCombineSingle(h, id.value);
348 return h;
349}
350
351bool ProgramInfoKeyEqual::operator()(const ProgramInfo& info1, const ProgramInfo& info2) const {
352 const ProgramIdentifier& id1 = info1.selector.primaryId;
353 const ProgramIdentifier& id2 = info2.selector.primaryId;
354 return id1.type == id2.type && id1.value == id2.value;
355}
356
357void updateProgramList(const ProgramListChunk& chunk, ProgramInfoSet* list) {
358 if (chunk.purge) {
359 list->clear();
360 }
361
362 list->insert(chunk.modified.begin(), chunk.modified.end());
363
364 if (!chunk.removed.has_value()) {
365 return;
366 }
367
368 for (auto& id : chunk.removed.value()) {
369 if (id.has_value()) {
370 ProgramInfo info = {};
371 info.selector.primaryId = id.value();
372 list->erase(info);
373 }
374 }
375}
376
377std::optional<std::string> getMetadataString(const ProgramInfo& info, const Metadata::Tag& tag) {
378 auto isRdsPs = [tag](const Metadata& item) { return item.getTag() == tag; };
379
380 auto it = std::find_if(info.metadata.begin(), info.metadata.end(), isRdsPs);
381 if (it == info.metadata.end()) {
382 return std::nullopt;
383 }
384
385 std::string metadataString;
386 switch (it->getTag()) {
387 case Metadata::rdsPs:
388 metadataString = it->get<Metadata::rdsPs>();
389 break;
390 case Metadata::rdsPty:
391 metadataString = std::to_string(it->get<Metadata::rdsPty>());
392 break;
393 case Metadata::rbdsPty:
394 metadataString = std::to_string(it->get<Metadata::rbdsPty>());
395 break;
396 case Metadata::rdsRt:
397 metadataString = it->get<Metadata::rdsRt>();
398 break;
399 case Metadata::songTitle:
400 metadataString = it->get<Metadata::songTitle>();
401 break;
402 case Metadata::songArtist:
403 metadataString = it->get<Metadata::songArtist>();
404 break;
405 case Metadata::songAlbum:
406 metadataString = it->get<Metadata::songAlbum>();
407 break;
408 case Metadata::stationIcon:
409 metadataString = std::to_string(it->get<Metadata::stationIcon>());
410 break;
411 case Metadata::albumArt:
412 metadataString = std::to_string(it->get<Metadata::albumArt>());
413 break;
414 case Metadata::programName:
415 metadataString = it->get<Metadata::programName>();
416 break;
417 case Metadata::dabEnsembleName:
418 metadataString = it->get<Metadata::dabEnsembleName>();
419 break;
420 case Metadata::dabEnsembleNameShort:
421 metadataString = it->get<Metadata::dabEnsembleNameShort>();
422 break;
423 case Metadata::dabServiceName:
424 metadataString = it->get<Metadata::dabServiceName>();
425 break;
426 case Metadata::dabServiceNameShort:
427 metadataString = it->get<Metadata::dabServiceNameShort>();
428 break;
429 case Metadata::dabComponentName:
430 metadataString = it->get<Metadata::dabComponentName>();
431 break;
432 case Metadata::dabComponentNameShort:
433 metadataString = it->get<Metadata::dabComponentNameShort>();
434 break;
435 default:
436 LOG(ERROR) << "Metadata " << it->toString() << " is not converted.";
437 return std::nullopt;
438 }
439 return metadataString;
440}
441
442ProgramIdentifier makeHdRadioStationName(const string& name) {
443 constexpr size_t maxlen = 8;
444
445 string shortName;
446 shortName.reserve(maxlen);
447
448 const auto& loc = std::locale::classic();
449 for (const char& ch : name) {
450 if (!std::isalnum(ch, loc)) {
451 continue;
452 }
453 shortName.push_back(std::toupper(ch, loc));
454 if (shortName.length() >= maxlen) {
455 break;
456 }
457 }
458
459 // Short name is converted to HD_STATION_NAME by encoding each char into its ASCII value in
460 // in little-endian order. For example, "Abc" is converted to 0x434241.
461 int64_t val = 0;
462 for (auto rit = shortName.rbegin(); rit != shortName.rend(); ++rit) {
463 val <<= 8;
464 val |= static_cast<char>(*rit);
465 }
466
467 return makeIdentifier(IdentifierType::HD_STATION_NAME, val);
468}
469
Weilin Xu97203b02022-06-23 00:19:03 +0000470IdentifierType getType(int typeAsInt) {
471 return static_cast<IdentifierType>(typeAsInt);
472}
473
474bool parseArgInt(const string& s, int* out) {
475 return ::android::base::ParseInt(s, out);
476}
477
478bool parseArgLong(const std::string& s, long* out) {
479 return ::android::base::ParseInt(s, out);
480}
481
482bool parseArgBool(const string& s, bool* out) {
483 if (EqualsIgnoreCase(s, "true")) {
484 *out = true;
485 } else if (EqualsIgnoreCase(s, "false")) {
486 *out = false;
487 } else {
488 return false;
489 }
490 return true;
491}
492
493bool parseArgDirection(const string& s, bool* out) {
494 if (EqualsIgnoreCase(s, "up")) {
495 *out = true;
496 } else if (EqualsIgnoreCase(s, "down")) {
497 *out = false;
498 } else {
499 return false;
500 }
501 return true;
502}
503
504bool parseArgIdentifierTypeArray(const string& s, vector<IdentifierType>* out) {
505 for (const string& val : ::android::base::Split(s, ",")) {
506 int outInt;
507 if (!parseArgInt(val, &outInt)) {
508 return false;
509 }
510 out->push_back(getType(outInt));
511 }
512 return true;
513}
514
515bool parseProgramIdentifierList(const std::string& s, vector<ProgramIdentifier>* out) {
516 for (const string& idStr : ::android::base::Split(s, ",")) {
517 const vector<string> idStrPair = ::android::base::Split(idStr, ":");
518 if (idStrPair.size() != 2) {
519 return false;
520 }
521 int idType;
522 if (!parseArgInt(idStrPair[0], &idType)) {
523 return false;
524 }
525 long idVal;
526 if (!parseArgLong(idStrPair[1], &idVal)) {
527 return false;
528 }
529 ProgramIdentifier id = {getType(idType), idVal};
530 out->push_back(id);
531 }
532 return true;
533}
534
Weilin Xub2a6ca62022-05-08 23:47:04 +0000535} // namespace utils
536
537utils::IdentifierIterator begin(const ProgramSelector& sel) {
538 return utils::IdentifierIterator(sel);
539}
540
541utils::IdentifierIterator end(const ProgramSelector& sel) {
542 return utils::IdentifierIterator(sel) + 1 /* primary id */ + sel.secondaryIds.size();
543}
544
545} // namespace aidl::android::hardware::broadcastradio